Adding support for llvm.arm.neon.vaddl[su].* and
[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/CallingConv.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Constants.h"
39 #include "llvm/Function.h"
40 #include "llvm/GlobalValue.h"
41 #include "llvm/Instruction.h"
42 #include "llvm/Instructions.h"
43 #include "llvm/Intrinsics.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Type.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::FREM,      MVT::f64, Expand);
785   setOperationAction(ISD::FREM,      MVT::f32, Expand);
786   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
787       !Subtarget->isThumb1Only()) {
788     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
789     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
790   }
791   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
792   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
793
794   if (!Subtarget->hasVFP4()) {
795     setOperationAction(ISD::FMA, MVT::f64, Expand);
796     setOperationAction(ISD::FMA, MVT::f32, Expand);
797   }
798
799   // Various VFP goodness
800   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
801     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
802     if (Subtarget->hasVFP2()) {
803       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
804       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
805       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
806       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
807     }
808     // Special handling for half-precision FP.
809     if (!Subtarget->hasFP16()) {
810       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
811       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
812     }
813   }
814
815   // We have target-specific dag combine patterns for the following nodes:
816   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
817   setTargetDAGCombine(ISD::ADD);
818   setTargetDAGCombine(ISD::SUB);
819   setTargetDAGCombine(ISD::MUL);
820   setTargetDAGCombine(ISD::AND);
821   setTargetDAGCombine(ISD::OR);
822   setTargetDAGCombine(ISD::XOR);
823
824   if (Subtarget->hasV6Ops())
825     setTargetDAGCombine(ISD::SRL);
826
827   setStackPointerRegisterToSaveRestore(ARM::SP);
828
829   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
830       !Subtarget->hasVFP2())
831     setSchedulingPreference(Sched::RegPressure);
832   else
833     setSchedulingPreference(Sched::Hybrid);
834
835   //// temporary - rewrite interface to use type
836   maxStoresPerMemset = 8;
837   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
838   maxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
839   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
840   maxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
841   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
842
843   // On ARM arguments smaller than 4 bytes are extended, so all arguments
844   // are at least 4 bytes aligned.
845   setMinStackArgumentAlignment(4);
846
847   benefitFromCodePlacementOpt = true;
848
849   // Prefer likely predicted branches to selects on out-of-order cores.
850   predictableSelectIsExpensive = Subtarget->isLikeA9();
851
852   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
853 }
854
855 // FIXME: It might make sense to define the representative register class as the
856 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
857 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
858 // SPR's representative would be DPR_VFP2. This should work well if register
859 // pressure tracking were modified such that a register use would increment the
860 // pressure of the register class's representative and all of it's super
861 // classes' representatives transitively. We have not implemented this because
862 // of the difficulty prior to coalescing of modeling operand register classes
863 // due to the common occurrence of cross class copies and subregister insertions
864 // and extractions.
865 std::pair<const TargetRegisterClass*, uint8_t>
866 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
867   const TargetRegisterClass *RRC = 0;
868   uint8_t Cost = 1;
869   switch (VT.SimpleTy) {
870   default:
871     return TargetLowering::findRepresentativeClass(VT);
872   // Use DPR as representative register class for all floating point
873   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
874   // the cost is 1 for both f32 and f64.
875   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
876   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
877     RRC = &ARM::DPRRegClass;
878     // When NEON is used for SP, only half of the register file is available
879     // because operations that define both SP and DP results will be constrained
880     // to the VFP2 class (D0-D15). We currently model this constraint prior to
881     // coalescing by double-counting the SP regs. See the FIXME above.
882     if (Subtarget->useNEONForSinglePrecisionFP())
883       Cost = 2;
884     break;
885   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
886   case MVT::v4f32: case MVT::v2f64:
887     RRC = &ARM::DPRRegClass;
888     Cost = 2;
889     break;
890   case MVT::v4i64:
891     RRC = &ARM::DPRRegClass;
892     Cost = 4;
893     break;
894   case MVT::v8i64:
895     RRC = &ARM::DPRRegClass;
896     Cost = 8;
897     break;
898   }
899   return std::make_pair(RRC, Cost);
900 }
901
902 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
903   switch (Opcode) {
904   default: return 0;
905   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
906   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
907   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
908   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
909   case ARMISD::CALL:          return "ARMISD::CALL";
910   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
911   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
912   case ARMISD::tCALL:         return "ARMISD::tCALL";
913   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
914   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
915   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
916   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
917   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
918   case ARMISD::CMP:           return "ARMISD::CMP";
919   case ARMISD::CMN:           return "ARMISD::CMN";
920   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
921   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
922   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
923   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
924   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
925
926   case ARMISD::CMOV:          return "ARMISD::CMOV";
927
928   case ARMISD::RBIT:          return "ARMISD::RBIT";
929
930   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
931   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
932   case ARMISD::SITOF:         return "ARMISD::SITOF";
933   case ARMISD::UITOF:         return "ARMISD::UITOF";
934
935   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
936   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
937   case ARMISD::RRX:           return "ARMISD::RRX";
938
939   case ARMISD::ADDC:          return "ARMISD::ADDC";
940   case ARMISD::ADDE:          return "ARMISD::ADDE";
941   case ARMISD::SUBC:          return "ARMISD::SUBC";
942   case ARMISD::SUBE:          return "ARMISD::SUBE";
943
944   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
945   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
946
947   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
948   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
949
950   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
951
952   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
953
954   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
955
956   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
957   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
958
959   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
960
961   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
962   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
963   case ARMISD::VCGE:          return "ARMISD::VCGE";
964   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
965   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
966   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
967   case ARMISD::VCGT:          return "ARMISD::VCGT";
968   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
969   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
970   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
971   case ARMISD::VTST:          return "ARMISD::VTST";
972
973   case ARMISD::VSHL:          return "ARMISD::VSHL";
974   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
975   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
976   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
977   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
978   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
979   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
980   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
981   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
982   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
983   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
984   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
985   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
986   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
987   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
988   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
989   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
990   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
991   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
992   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
993   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
994   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
995   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
996   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
997   case ARMISD::VDUP:          return "ARMISD::VDUP";
998   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
999   case ARMISD::VEXT:          return "ARMISD::VEXT";
1000   case ARMISD::VREV64:        return "ARMISD::VREV64";
1001   case ARMISD::VREV32:        return "ARMISD::VREV32";
1002   case ARMISD::VREV16:        return "ARMISD::VREV16";
1003   case ARMISD::VZIP:          return "ARMISD::VZIP";
1004   case ARMISD::VUZP:          return "ARMISD::VUZP";
1005   case ARMISD::VTRN:          return "ARMISD::VTRN";
1006   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1007   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1008   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1009   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1010   case ARMISD::VADDLs:        return "ARMISD::VADDLs";
1011   case ARMISD::VADDLu:        return "ARMISD::VADDLu";
1012   case ARMISD::VSUBLs:        return "ARMISD::VSUBLs";
1013   case ARMISD::VSUBLu:        return "ARMISD::VSUBLu";
1014   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1015   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1016   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1017   case ARMISD::FMAX:          return "ARMISD::FMAX";
1018   case ARMISD::FMIN:          return "ARMISD::FMIN";
1019   case ARMISD::BFI:           return "ARMISD::BFI";
1020   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1021   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1022   case ARMISD::VBSL:          return "ARMISD::VBSL";
1023   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1024   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1025   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1026   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1027   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1028   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1029   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1030   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1031   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1032   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1033   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1034   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1035   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1036   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1037   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1038   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1039   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1040   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1041   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1042   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1043   }
1044 }
1045
1046 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1047   if (!VT.isVector()) return getPointerTy();
1048   return VT.changeVectorElementTypeToInteger();
1049 }
1050
1051 /// getRegClassFor - Return the register class that should be used for the
1052 /// specified value type.
1053 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1054   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1055   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1056   // load / store 4 to 8 consecutive D registers.
1057   if (Subtarget->hasNEON()) {
1058     if (VT == MVT::v4i64)
1059       return &ARM::QQPRRegClass;
1060     if (VT == MVT::v8i64)
1061       return &ARM::QQQQPRRegClass;
1062   }
1063   return TargetLowering::getRegClassFor(VT);
1064 }
1065
1066 // Create a fast isel object.
1067 FastISel *
1068 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1069                                   const TargetLibraryInfo *libInfo) const {
1070   return ARM::createFastISel(funcInfo, libInfo);
1071 }
1072
1073 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1074 /// be used for loads / stores from the global.
1075 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1076   return (Subtarget->isThumb1Only() ? 127 : 4095);
1077 }
1078
1079 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1080   unsigned NumVals = N->getNumValues();
1081   if (!NumVals)
1082     return Sched::RegPressure;
1083
1084   for (unsigned i = 0; i != NumVals; ++i) {
1085     EVT VT = N->getValueType(i);
1086     if (VT == MVT::Glue || VT == MVT::Other)
1087       continue;
1088     if (VT.isFloatingPoint() || VT.isVector())
1089       return Sched::ILP;
1090   }
1091
1092   if (!N->isMachineOpcode())
1093     return Sched::RegPressure;
1094
1095   // Load are scheduled for latency even if there instruction itinerary
1096   // is not available.
1097   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1098   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1099
1100   if (MCID.getNumDefs() == 0)
1101     return Sched::RegPressure;
1102   if (!Itins->isEmpty() &&
1103       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1104     return Sched::ILP;
1105
1106   return Sched::RegPressure;
1107 }
1108
1109 //===----------------------------------------------------------------------===//
1110 // Lowering Code
1111 //===----------------------------------------------------------------------===//
1112
1113 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1114 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1115   switch (CC) {
1116   default: llvm_unreachable("Unknown condition code!");
1117   case ISD::SETNE:  return ARMCC::NE;
1118   case ISD::SETEQ:  return ARMCC::EQ;
1119   case ISD::SETGT:  return ARMCC::GT;
1120   case ISD::SETGE:  return ARMCC::GE;
1121   case ISD::SETLT:  return ARMCC::LT;
1122   case ISD::SETLE:  return ARMCC::LE;
1123   case ISD::SETUGT: return ARMCC::HI;
1124   case ISD::SETUGE: return ARMCC::HS;
1125   case ISD::SETULT: return ARMCC::LO;
1126   case ISD::SETULE: return ARMCC::LS;
1127   }
1128 }
1129
1130 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1131 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1132                         ARMCC::CondCodes &CondCode2) {
1133   CondCode2 = ARMCC::AL;
1134   switch (CC) {
1135   default: llvm_unreachable("Unknown FP condition!");
1136   case ISD::SETEQ:
1137   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1138   case ISD::SETGT:
1139   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1140   case ISD::SETGE:
1141   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1142   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1143   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1144   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1145   case ISD::SETO:   CondCode = ARMCC::VC; break;
1146   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1147   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1148   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1149   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1150   case ISD::SETLT:
1151   case ISD::SETULT: CondCode = ARMCC::LT; break;
1152   case ISD::SETLE:
1153   case ISD::SETULE: CondCode = ARMCC::LE; break;
1154   case ISD::SETNE:
1155   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1156   }
1157 }
1158
1159 //===----------------------------------------------------------------------===//
1160 //                      Calling Convention Implementation
1161 //===----------------------------------------------------------------------===//
1162
1163 #include "ARMGenCallingConv.inc"
1164
1165 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1166 /// given CallingConvention value.
1167 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1168                                                  bool Return,
1169                                                  bool isVarArg) const {
1170   switch (CC) {
1171   default:
1172     llvm_unreachable("Unsupported calling convention");
1173   case CallingConv::Fast:
1174     if (Subtarget->hasVFP2() && !isVarArg) {
1175       if (!Subtarget->isAAPCS_ABI())
1176         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1177       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1178       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1179     }
1180     // Fallthrough
1181   case CallingConv::C: {
1182     // Use target triple & subtarget features to do actual dispatch.
1183     if (!Subtarget->isAAPCS_ABI())
1184       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1185     else if (Subtarget->hasVFP2() &&
1186              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1187              !isVarArg)
1188       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1189     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1190   }
1191   case CallingConv::ARM_AAPCS_VFP:
1192     if (!isVarArg)
1193       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1194     // Fallthrough
1195   case CallingConv::ARM_AAPCS:
1196     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1197   case CallingConv::ARM_APCS:
1198     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1199   case CallingConv::GHC:
1200     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1201   }
1202 }
1203
1204 /// LowerCallResult - Lower the result values of a call into the
1205 /// appropriate copies out of appropriate physical registers.
1206 SDValue
1207 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1208                                    CallingConv::ID CallConv, bool isVarArg,
1209                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1210                                    DebugLoc dl, SelectionDAG &DAG,
1211                                    SmallVectorImpl<SDValue> &InVals) const {
1212
1213   // Assign locations to each value returned by this call.
1214   SmallVector<CCValAssign, 16> RVLocs;
1215   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1216                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1217   CCInfo.AnalyzeCallResult(Ins,
1218                            CCAssignFnForNode(CallConv, /* Return*/ true,
1219                                              isVarArg));
1220
1221   // Copy all of the result registers out of their specified physreg.
1222   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1223     CCValAssign VA = RVLocs[i];
1224
1225     SDValue Val;
1226     if (VA.needsCustom()) {
1227       // Handle f64 or half of a v2f64.
1228       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1229                                       InFlag);
1230       Chain = Lo.getValue(1);
1231       InFlag = Lo.getValue(2);
1232       VA = RVLocs[++i]; // skip ahead to next loc
1233       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1234                                       InFlag);
1235       Chain = Hi.getValue(1);
1236       InFlag = Hi.getValue(2);
1237       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1238
1239       if (VA.getLocVT() == MVT::v2f64) {
1240         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1241         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1242                           DAG.getConstant(0, MVT::i32));
1243
1244         VA = RVLocs[++i]; // skip ahead to next loc
1245         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1246         Chain = Lo.getValue(1);
1247         InFlag = Lo.getValue(2);
1248         VA = RVLocs[++i]; // skip ahead to next loc
1249         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1250         Chain = Hi.getValue(1);
1251         InFlag = Hi.getValue(2);
1252         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1253         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1254                           DAG.getConstant(1, MVT::i32));
1255       }
1256     } else {
1257       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1258                                InFlag);
1259       Chain = Val.getValue(1);
1260       InFlag = Val.getValue(2);
1261     }
1262
1263     switch (VA.getLocInfo()) {
1264     default: llvm_unreachable("Unknown loc info!");
1265     case CCValAssign::Full: break;
1266     case CCValAssign::BCvt:
1267       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1268       break;
1269     }
1270
1271     InVals.push_back(Val);
1272   }
1273
1274   return Chain;
1275 }
1276
1277 /// LowerMemOpCallTo - Store the argument to the stack.
1278 SDValue
1279 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1280                                     SDValue StackPtr, SDValue Arg,
1281                                     DebugLoc dl, SelectionDAG &DAG,
1282                                     const CCValAssign &VA,
1283                                     ISD::ArgFlagsTy Flags) const {
1284   unsigned LocMemOffset = VA.getLocMemOffset();
1285   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1286   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1287   return DAG.getStore(Chain, dl, Arg, PtrOff,
1288                       MachinePointerInfo::getStack(LocMemOffset),
1289                       false, false, 0);
1290 }
1291
1292 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1293                                          SDValue Chain, SDValue &Arg,
1294                                          RegsToPassVector &RegsToPass,
1295                                          CCValAssign &VA, CCValAssign &NextVA,
1296                                          SDValue &StackPtr,
1297                                          SmallVector<SDValue, 8> &MemOpChains,
1298                                          ISD::ArgFlagsTy Flags) const {
1299
1300   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1301                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1302   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1303
1304   if (NextVA.isRegLoc())
1305     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1306   else {
1307     assert(NextVA.isMemLoc());
1308     if (StackPtr.getNode() == 0)
1309       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1310
1311     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1312                                            dl, DAG, NextVA,
1313                                            Flags));
1314   }
1315 }
1316
1317 /// LowerCall - Lowering a call into a callseq_start <-
1318 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1319 /// nodes.
1320 SDValue
1321 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1322                              SmallVectorImpl<SDValue> &InVals) const {
1323   SelectionDAG &DAG                     = CLI.DAG;
1324   DebugLoc &dl                          = CLI.DL;
1325   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1326   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1327   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1328   SDValue Chain                         = CLI.Chain;
1329   SDValue Callee                        = CLI.Callee;
1330   bool &isTailCall                      = CLI.IsTailCall;
1331   CallingConv::ID CallConv              = CLI.CallConv;
1332   bool doesNotRet                       = CLI.DoesNotReturn;
1333   bool isVarArg                         = CLI.IsVarArg;
1334
1335   MachineFunction &MF = DAG.getMachineFunction();
1336   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1337   bool IsSibCall = false;
1338   // Disable tail calls if they're not supported.
1339   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1340     isTailCall = false;
1341   if (isTailCall) {
1342     // Check if it's really possible to do a tail call.
1343     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1344                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1345                                                    Outs, OutVals, Ins, DAG);
1346     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1347     // detected sibcalls.
1348     if (isTailCall) {
1349       ++NumTailCalls;
1350       IsSibCall = true;
1351     }
1352   }
1353
1354   // Analyze operands of the call, assigning locations to each operand.
1355   SmallVector<CCValAssign, 16> ArgLocs;
1356   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1357                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1358   CCInfo.AnalyzeCallOperands(Outs,
1359                              CCAssignFnForNode(CallConv, /* Return*/ false,
1360                                                isVarArg));
1361
1362   // Get a count of how many bytes are to be pushed on the stack.
1363   unsigned NumBytes = CCInfo.getNextStackOffset();
1364
1365   // For tail calls, memory operands are available in our caller's stack.
1366   if (IsSibCall)
1367     NumBytes = 0;
1368
1369   // Adjust the stack pointer for the new arguments...
1370   // These operations are automatically eliminated by the prolog/epilog pass
1371   if (!IsSibCall)
1372     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1373
1374   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1375
1376   RegsToPassVector RegsToPass;
1377   SmallVector<SDValue, 8> MemOpChains;
1378
1379   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1380   // of tail call optimization, arguments are handled later.
1381   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1382        i != e;
1383        ++i, ++realArgIdx) {
1384     CCValAssign &VA = ArgLocs[i];
1385     SDValue Arg = OutVals[realArgIdx];
1386     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1387     bool isByVal = Flags.isByVal();
1388
1389     // Promote the value if needed.
1390     switch (VA.getLocInfo()) {
1391     default: llvm_unreachable("Unknown loc info!");
1392     case CCValAssign::Full: break;
1393     case CCValAssign::SExt:
1394       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1395       break;
1396     case CCValAssign::ZExt:
1397       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1398       break;
1399     case CCValAssign::AExt:
1400       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1401       break;
1402     case CCValAssign::BCvt:
1403       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1404       break;
1405     }
1406
1407     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1408     if (VA.needsCustom()) {
1409       if (VA.getLocVT() == MVT::v2f64) {
1410         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1411                                   DAG.getConstant(0, MVT::i32));
1412         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1413                                   DAG.getConstant(1, MVT::i32));
1414
1415         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1416                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1417
1418         VA = ArgLocs[++i]; // skip ahead to next loc
1419         if (VA.isRegLoc()) {
1420           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1421                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1422         } else {
1423           assert(VA.isMemLoc());
1424
1425           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1426                                                  dl, DAG, VA, Flags));
1427         }
1428       } else {
1429         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1430                          StackPtr, MemOpChains, Flags);
1431       }
1432     } else if (VA.isRegLoc()) {
1433       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1434     } else if (isByVal) {
1435       assert(VA.isMemLoc());
1436       unsigned offset = 0;
1437
1438       // True if this byval aggregate will be split between registers
1439       // and memory.
1440       if (CCInfo.isFirstByValRegValid()) {
1441         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1442         unsigned int i, j;
1443         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1444           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1445           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1446           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1447                                      MachinePointerInfo(),
1448                                      false, false, false, 0);
1449           MemOpChains.push_back(Load.getValue(1));
1450           RegsToPass.push_back(std::make_pair(j, Load));
1451         }
1452         offset = ARM::R4 - CCInfo.getFirstByValReg();
1453         CCInfo.clearFirstByValReg();
1454       }
1455
1456       if (Flags.getByValSize() - 4*offset > 0) {
1457         unsigned LocMemOffset = VA.getLocMemOffset();
1458         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1459         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1460                                   StkPtrOff);
1461         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1462         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1463         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1464                                            MVT::i32);
1465         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1466
1467         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1468         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1469         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1470                                           Ops, array_lengthof(Ops)));
1471       }
1472     } else if (!IsSibCall) {
1473       assert(VA.isMemLoc());
1474
1475       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1476                                              dl, DAG, VA, Flags));
1477     }
1478   }
1479
1480   if (!MemOpChains.empty())
1481     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1482                         &MemOpChains[0], MemOpChains.size());
1483
1484   // Build a sequence of copy-to-reg nodes chained together with token chain
1485   // and flag operands which copy the outgoing args into the appropriate regs.
1486   SDValue InFlag;
1487   // Tail call byval lowering might overwrite argument registers so in case of
1488   // tail call optimization the copies to registers are lowered later.
1489   if (!isTailCall)
1490     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1491       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1492                                RegsToPass[i].second, InFlag);
1493       InFlag = Chain.getValue(1);
1494     }
1495
1496   // For tail calls lower the arguments to the 'real' stack slot.
1497   if (isTailCall) {
1498     // Force all the incoming stack arguments to be loaded from the stack
1499     // before any new outgoing arguments are stored to the stack, because the
1500     // outgoing stack slots may alias the incoming argument stack slots, and
1501     // the alias isn't otherwise explicit. This is slightly more conservative
1502     // than necessary, because it means that each store effectively depends
1503     // on every argument instead of just those arguments it would clobber.
1504
1505     // Do not flag preceding copytoreg stuff together with the following stuff.
1506     InFlag = SDValue();
1507     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1508       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1509                                RegsToPass[i].second, InFlag);
1510       InFlag = Chain.getValue(1);
1511     }
1512     InFlag =SDValue();
1513   }
1514
1515   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1516   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1517   // node so that legalize doesn't hack it.
1518   bool isDirect = false;
1519   bool isARMFunc = false;
1520   bool isLocalARMFunc = false;
1521   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1522
1523   if (EnableARMLongCalls) {
1524     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1525             && "long-calls with non-static relocation model!");
1526     // Handle a global address or an external symbol. If it's not one of
1527     // those, the target's already in a register, so we don't need to do
1528     // anything extra.
1529     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1530       const GlobalValue *GV = G->getGlobal();
1531       // Create a constant pool entry for the callee address
1532       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1533       ARMConstantPoolValue *CPV =
1534         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1535
1536       // Get the address of the callee into a register
1537       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1538       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1539       Callee = DAG.getLoad(getPointerTy(), dl,
1540                            DAG.getEntryNode(), CPAddr,
1541                            MachinePointerInfo::getConstantPool(),
1542                            false, false, false, 0);
1543     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1544       const char *Sym = S->getSymbol();
1545
1546       // Create a constant pool entry for the callee address
1547       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1548       ARMConstantPoolValue *CPV =
1549         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1550                                       ARMPCLabelIndex, 0);
1551       // Get the address of the callee into a register
1552       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1553       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1554       Callee = DAG.getLoad(getPointerTy(), dl,
1555                            DAG.getEntryNode(), CPAddr,
1556                            MachinePointerInfo::getConstantPool(),
1557                            false, false, false, 0);
1558     }
1559   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1560     const GlobalValue *GV = G->getGlobal();
1561     isDirect = true;
1562     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1563     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1564                    getTargetMachine().getRelocationModel() != Reloc::Static;
1565     isARMFunc = !Subtarget->isThumb() || isStub;
1566     // ARM call to a local ARM function is predicable.
1567     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1568     // tBX takes a register source operand.
1569     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1570       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1571       ARMConstantPoolValue *CPV =
1572         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1573       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1574       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1575       Callee = DAG.getLoad(getPointerTy(), dl,
1576                            DAG.getEntryNode(), CPAddr,
1577                            MachinePointerInfo::getConstantPool(),
1578                            false, false, false, 0);
1579       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1580       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1581                            getPointerTy(), Callee, PICLabel);
1582     } else {
1583       // On ELF targets for PIC code, direct calls should go through the PLT
1584       unsigned OpFlags = 0;
1585       if (Subtarget->isTargetELF() &&
1586                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1587         OpFlags = ARMII::MO_PLT;
1588       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1589     }
1590   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1591     isDirect = true;
1592     bool isStub = Subtarget->isTargetDarwin() &&
1593                   getTargetMachine().getRelocationModel() != Reloc::Static;
1594     isARMFunc = !Subtarget->isThumb() || isStub;
1595     // tBX takes a register source operand.
1596     const char *Sym = S->getSymbol();
1597     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1598       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1599       ARMConstantPoolValue *CPV =
1600         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1601                                       ARMPCLabelIndex, 4);
1602       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1603       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1604       Callee = DAG.getLoad(getPointerTy(), dl,
1605                            DAG.getEntryNode(), CPAddr,
1606                            MachinePointerInfo::getConstantPool(),
1607                            false, false, false, 0);
1608       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1609       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1610                            getPointerTy(), Callee, PICLabel);
1611     } else {
1612       unsigned OpFlags = 0;
1613       // On ELF targets for PIC code, direct calls should go through the PLT
1614       if (Subtarget->isTargetELF() &&
1615                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1616         OpFlags = ARMII::MO_PLT;
1617       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1618     }
1619   }
1620
1621   // FIXME: handle tail calls differently.
1622   unsigned CallOpc;
1623   bool HasMinSizeAttr = MF.getFunction()->getFnAttributes().
1624     hasAttribute(Attribute::MinSize);
1625   if (Subtarget->isThumb()) {
1626     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1627       CallOpc = ARMISD::CALL_NOLINK;
1628     else
1629       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1630   } else {
1631     if (!isDirect && !Subtarget->hasV5TOps())
1632       CallOpc = ARMISD::CALL_NOLINK;
1633     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1634                // Emit regular call when code size is the priority
1635                !HasMinSizeAttr)
1636       // "mov lr, pc; b _foo" to avoid confusing the RSP
1637       CallOpc = ARMISD::CALL_NOLINK;
1638     else
1639       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1640   }
1641
1642   std::vector<SDValue> Ops;
1643   Ops.push_back(Chain);
1644   Ops.push_back(Callee);
1645
1646   // Add argument registers to the end of the list so that they are known live
1647   // into the call.
1648   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1649     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1650                                   RegsToPass[i].second.getValueType()));
1651
1652   // Add a register mask operand representing the call-preserved registers.
1653   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1654   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1655   assert(Mask && "Missing call preserved mask for calling convention");
1656   Ops.push_back(DAG.getRegisterMask(Mask));
1657
1658   if (InFlag.getNode())
1659     Ops.push_back(InFlag);
1660
1661   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1662   if (isTailCall)
1663     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1664
1665   // Returns a chain and a flag for retval copy to use.
1666   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1667   InFlag = Chain.getValue(1);
1668
1669   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1670                              DAG.getIntPtrConstant(0, true), InFlag);
1671   if (!Ins.empty())
1672     InFlag = Chain.getValue(1);
1673
1674   // Handle result values, copying them out of physregs into vregs that we
1675   // return.
1676   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1677                          dl, DAG, InVals);
1678 }
1679
1680 /// HandleByVal - Every parameter *after* a byval parameter is passed
1681 /// on the stack.  Remember the next parameter register to allocate,
1682 /// and then confiscate the rest of the parameter registers to insure
1683 /// this.
1684 void
1685 ARMTargetLowering::HandleByVal(
1686     CCState *State, unsigned &size, unsigned Align) const {
1687   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1688   assert((State->getCallOrPrologue() == Prologue ||
1689           State->getCallOrPrologue() == Call) &&
1690          "unhandled ParmContext");
1691   if ((!State->isFirstByValRegValid()) &&
1692       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1693     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1694       unsigned AlignInRegs = Align / 4;
1695       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1696       for (unsigned i = 0; i < Waste; ++i)
1697         reg = State->AllocateReg(GPRArgRegs, 4);
1698     }
1699     if (reg != 0) {
1700       State->setFirstByValReg(reg);
1701       // At a call site, a byval parameter that is split between
1702       // registers and memory needs its size truncated here.  In a
1703       // function prologue, such byval parameters are reassembled in
1704       // memory, and are not truncated.
1705       if (State->getCallOrPrologue() == Call) {
1706         unsigned excess = 4 * (ARM::R4 - reg);
1707         assert(size >= excess && "expected larger existing stack allocation");
1708         size -= excess;
1709       }
1710     }
1711   }
1712   // Confiscate any remaining parameter registers to preclude their
1713   // assignment to subsequent parameters.
1714   while (State->AllocateReg(GPRArgRegs, 4))
1715     ;
1716 }
1717
1718 /// MatchingStackOffset - Return true if the given stack call argument is
1719 /// already available in the same position (relatively) of the caller's
1720 /// incoming argument stack.
1721 static
1722 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1723                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1724                          const TargetInstrInfo *TII) {
1725   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1726   int FI = INT_MAX;
1727   if (Arg.getOpcode() == ISD::CopyFromReg) {
1728     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1729     if (!TargetRegisterInfo::isVirtualRegister(VR))
1730       return false;
1731     MachineInstr *Def = MRI->getVRegDef(VR);
1732     if (!Def)
1733       return false;
1734     if (!Flags.isByVal()) {
1735       if (!TII->isLoadFromStackSlot(Def, FI))
1736         return false;
1737     } else {
1738       return false;
1739     }
1740   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1741     if (Flags.isByVal())
1742       // ByVal argument is passed in as a pointer but it's now being
1743       // dereferenced. e.g.
1744       // define @foo(%struct.X* %A) {
1745       //   tail call @bar(%struct.X* byval %A)
1746       // }
1747       return false;
1748     SDValue Ptr = Ld->getBasePtr();
1749     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1750     if (!FINode)
1751       return false;
1752     FI = FINode->getIndex();
1753   } else
1754     return false;
1755
1756   assert(FI != INT_MAX);
1757   if (!MFI->isFixedObjectIndex(FI))
1758     return false;
1759   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1760 }
1761
1762 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1763 /// for tail call optimization. Targets which want to do tail call
1764 /// optimization should implement this function.
1765 bool
1766 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1767                                                      CallingConv::ID CalleeCC,
1768                                                      bool isVarArg,
1769                                                      bool isCalleeStructRet,
1770                                                      bool isCallerStructRet,
1771                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1772                                     const SmallVectorImpl<SDValue> &OutVals,
1773                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1774                                                      SelectionDAG& DAG) const {
1775   const Function *CallerF = DAG.getMachineFunction().getFunction();
1776   CallingConv::ID CallerCC = CallerF->getCallingConv();
1777   bool CCMatch = CallerCC == CalleeCC;
1778
1779   // Look for obvious safe cases to perform tail call optimization that do not
1780   // require ABI changes. This is what gcc calls sibcall.
1781
1782   // Do not sibcall optimize vararg calls unless the call site is not passing
1783   // any arguments.
1784   if (isVarArg && !Outs.empty())
1785     return false;
1786
1787   // Also avoid sibcall optimization if either caller or callee uses struct
1788   // return semantics.
1789   if (isCalleeStructRet || isCallerStructRet)
1790     return false;
1791
1792   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1793   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1794   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1795   // support in the assembler and linker to be used. This would need to be
1796   // fixed to fully support tail calls in Thumb1.
1797   //
1798   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1799   // LR.  This means if we need to reload LR, it takes an extra instructions,
1800   // which outweighs the value of the tail call; but here we don't know yet
1801   // whether LR is going to be used.  Probably the right approach is to
1802   // generate the tail call here and turn it back into CALL/RET in
1803   // emitEpilogue if LR is used.
1804
1805   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1806   // but we need to make sure there are enough registers; the only valid
1807   // registers are the 4 used for parameters.  We don't currently do this
1808   // case.
1809   if (Subtarget->isThumb1Only())
1810     return false;
1811
1812   // If the calling conventions do not match, then we'd better make sure the
1813   // results are returned in the same way as what the caller expects.
1814   if (!CCMatch) {
1815     SmallVector<CCValAssign, 16> RVLocs1;
1816     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1817                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1818     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1819
1820     SmallVector<CCValAssign, 16> RVLocs2;
1821     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1822                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1823     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1824
1825     if (RVLocs1.size() != RVLocs2.size())
1826       return false;
1827     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1828       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1829         return false;
1830       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1831         return false;
1832       if (RVLocs1[i].isRegLoc()) {
1833         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1834           return false;
1835       } else {
1836         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1837           return false;
1838       }
1839     }
1840   }
1841
1842   // If Caller's vararg or byval argument has been split between registers and
1843   // stack, do not perform tail call, since part of the argument is in caller's
1844   // local frame.
1845   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1846                                       getInfo<ARMFunctionInfo>();
1847   if (AFI_Caller->getVarArgsRegSaveSize())
1848     return false;
1849
1850   // If the callee takes no arguments then go on to check the results of the
1851   // call.
1852   if (!Outs.empty()) {
1853     // Check if stack adjustment is needed. For now, do not do this if any
1854     // argument is passed on the stack.
1855     SmallVector<CCValAssign, 16> ArgLocs;
1856     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1857                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1858     CCInfo.AnalyzeCallOperands(Outs,
1859                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1860     if (CCInfo.getNextStackOffset()) {
1861       MachineFunction &MF = DAG.getMachineFunction();
1862
1863       // Check if the arguments are already laid out in the right way as
1864       // the caller's fixed stack objects.
1865       MachineFrameInfo *MFI = MF.getFrameInfo();
1866       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1867       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1868       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1869            i != e;
1870            ++i, ++realArgIdx) {
1871         CCValAssign &VA = ArgLocs[i];
1872         EVT RegVT = VA.getLocVT();
1873         SDValue Arg = OutVals[realArgIdx];
1874         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1875         if (VA.getLocInfo() == CCValAssign::Indirect)
1876           return false;
1877         if (VA.needsCustom()) {
1878           // f64 and vector types are split into multiple registers or
1879           // register/stack-slot combinations.  The types will not match
1880           // the registers; give up on memory f64 refs until we figure
1881           // out what to do about this.
1882           if (!VA.isRegLoc())
1883             return false;
1884           if (!ArgLocs[++i].isRegLoc())
1885             return false;
1886           if (RegVT == MVT::v2f64) {
1887             if (!ArgLocs[++i].isRegLoc())
1888               return false;
1889             if (!ArgLocs[++i].isRegLoc())
1890               return false;
1891           }
1892         } else if (!VA.isRegLoc()) {
1893           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1894                                    MFI, MRI, TII))
1895             return false;
1896         }
1897       }
1898     }
1899   }
1900
1901   return true;
1902 }
1903
1904 bool
1905 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1906                                   MachineFunction &MF, bool isVarArg,
1907                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
1908                                   LLVMContext &Context) const {
1909   SmallVector<CCValAssign, 16> RVLocs;
1910   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1911   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1912                                                     isVarArg));
1913 }
1914
1915 SDValue
1916 ARMTargetLowering::LowerReturn(SDValue Chain,
1917                                CallingConv::ID CallConv, bool isVarArg,
1918                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1919                                const SmallVectorImpl<SDValue> &OutVals,
1920                                DebugLoc dl, SelectionDAG &DAG) const {
1921
1922   // CCValAssign - represent the assignment of the return value to a location.
1923   SmallVector<CCValAssign, 16> RVLocs;
1924
1925   // CCState - Info about the registers and stack slots.
1926   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1927                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1928
1929   // Analyze outgoing return values.
1930   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1931                                                isVarArg));
1932
1933   // If this is the first return lowered for this function, add
1934   // the regs to the liveout set for the function.
1935   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1936     for (unsigned i = 0; i != RVLocs.size(); ++i)
1937       if (RVLocs[i].isRegLoc())
1938         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1939   }
1940
1941   SDValue Flag;
1942
1943   // Copy the result values into the output registers.
1944   for (unsigned i = 0, realRVLocIdx = 0;
1945        i != RVLocs.size();
1946        ++i, ++realRVLocIdx) {
1947     CCValAssign &VA = RVLocs[i];
1948     assert(VA.isRegLoc() && "Can only return in registers!");
1949
1950     SDValue Arg = OutVals[realRVLocIdx];
1951
1952     switch (VA.getLocInfo()) {
1953     default: llvm_unreachable("Unknown loc info!");
1954     case CCValAssign::Full: break;
1955     case CCValAssign::BCvt:
1956       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1957       break;
1958     }
1959
1960     if (VA.needsCustom()) {
1961       if (VA.getLocVT() == MVT::v2f64) {
1962         // Extract the first half and return it in two registers.
1963         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1964                                    DAG.getConstant(0, MVT::i32));
1965         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1966                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1967
1968         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1969         Flag = Chain.getValue(1);
1970         VA = RVLocs[++i]; // skip ahead to next loc
1971         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1972                                  HalfGPRs.getValue(1), Flag);
1973         Flag = Chain.getValue(1);
1974         VA = RVLocs[++i]; // skip ahead to next loc
1975
1976         // Extract the 2nd half and fall through to handle it as an f64 value.
1977         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1978                           DAG.getConstant(1, MVT::i32));
1979       }
1980       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1981       // available.
1982       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1983                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1984       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1985       Flag = Chain.getValue(1);
1986       VA = RVLocs[++i]; // skip ahead to next loc
1987       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1988                                Flag);
1989     } else
1990       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1991
1992     // Guarantee that all emitted copies are
1993     // stuck together, avoiding something bad.
1994     Flag = Chain.getValue(1);
1995   }
1996
1997   SDValue result;
1998   if (Flag.getNode())
1999     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
2000   else // Return Void
2001     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
2002
2003   return result;
2004 }
2005
2006 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2007   if (N->getNumValues() != 1)
2008     return false;
2009   if (!N->hasNUsesOfValue(1, 0))
2010     return false;
2011
2012   SDValue TCChain = Chain;
2013   SDNode *Copy = *N->use_begin();
2014   if (Copy->getOpcode() == ISD::CopyToReg) {
2015     // If the copy has a glue operand, we conservatively assume it isn't safe to
2016     // perform a tail call.
2017     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2018       return false;
2019     TCChain = Copy->getOperand(0);
2020   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2021     SDNode *VMov = Copy;
2022     // f64 returned in a pair of GPRs.
2023     SmallPtrSet<SDNode*, 2> Copies;
2024     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2025          UI != UE; ++UI) {
2026       if (UI->getOpcode() != ISD::CopyToReg)
2027         return false;
2028       Copies.insert(*UI);
2029     }
2030     if (Copies.size() > 2)
2031       return false;
2032
2033     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2034          UI != UE; ++UI) {
2035       SDValue UseChain = UI->getOperand(0);
2036       if (Copies.count(UseChain.getNode()))
2037         // Second CopyToReg
2038         Copy = *UI;
2039       else
2040         // First CopyToReg
2041         TCChain = UseChain;
2042     }
2043   } else if (Copy->getOpcode() == ISD::BITCAST) {
2044     // f32 returned in a single GPR.
2045     if (!Copy->hasOneUse())
2046       return false;
2047     Copy = *Copy->use_begin();
2048     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2049       return false;
2050     Chain = Copy->getOperand(0);
2051   } else {
2052     return false;
2053   }
2054
2055   bool HasRet = false;
2056   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2057        UI != UE; ++UI) {
2058     if (UI->getOpcode() != ARMISD::RET_FLAG)
2059       return false;
2060     HasRet = true;
2061   }
2062
2063   if (!HasRet)
2064     return false;
2065
2066   Chain = TCChain;
2067   return true;
2068 }
2069
2070 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2071   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2072     return false;
2073
2074   if (!CI->isTailCall())
2075     return false;
2076
2077   return !Subtarget->isThumb1Only();
2078 }
2079
2080 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2081 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2082 // one of the above mentioned nodes. It has to be wrapped because otherwise
2083 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2084 // be used to form addressing mode. These wrapped nodes will be selected
2085 // into MOVi.
2086 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2087   EVT PtrVT = Op.getValueType();
2088   // FIXME there is no actual debug info here
2089   DebugLoc dl = Op.getDebugLoc();
2090   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2091   SDValue Res;
2092   if (CP->isMachineConstantPoolEntry())
2093     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2094                                     CP->getAlignment());
2095   else
2096     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2097                                     CP->getAlignment());
2098   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2099 }
2100
2101 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2102   return MachineJumpTableInfo::EK_Inline;
2103 }
2104
2105 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2106                                              SelectionDAG &DAG) const {
2107   MachineFunction &MF = DAG.getMachineFunction();
2108   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2109   unsigned ARMPCLabelIndex = 0;
2110   DebugLoc DL = Op.getDebugLoc();
2111   EVT PtrVT = getPointerTy();
2112   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2113   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2114   SDValue CPAddr;
2115   if (RelocM == Reloc::Static) {
2116     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2117   } else {
2118     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2119     ARMPCLabelIndex = AFI->createPICLabelUId();
2120     ARMConstantPoolValue *CPV =
2121       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2122                                       ARMCP::CPBlockAddress, PCAdj);
2123     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2124   }
2125   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2126   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2127                                MachinePointerInfo::getConstantPool(),
2128                                false, false, false, 0);
2129   if (RelocM == Reloc::Static)
2130     return Result;
2131   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2132   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2133 }
2134
2135 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2136 SDValue
2137 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2138                                                  SelectionDAG &DAG) const {
2139   DebugLoc dl = GA->getDebugLoc();
2140   EVT PtrVT = getPointerTy();
2141   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2142   MachineFunction &MF = DAG.getMachineFunction();
2143   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2144   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2145   ARMConstantPoolValue *CPV =
2146     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2147                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2148   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2149   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2150   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2151                          MachinePointerInfo::getConstantPool(),
2152                          false, false, false, 0);
2153   SDValue Chain = Argument.getValue(1);
2154
2155   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2156   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2157
2158   // call __tls_get_addr.
2159   ArgListTy Args;
2160   ArgListEntry Entry;
2161   Entry.Node = Argument;
2162   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2163   Args.push_back(Entry);
2164   // FIXME: is there useful debug info available here?
2165   TargetLowering::CallLoweringInfo CLI(Chain,
2166                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2167                 false, false, false, false,
2168                 0, CallingConv::C, /*isTailCall=*/false,
2169                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2170                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2171   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2172   return CallResult.first;
2173 }
2174
2175 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2176 // "local exec" model.
2177 SDValue
2178 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2179                                         SelectionDAG &DAG,
2180                                         TLSModel::Model model) const {
2181   const GlobalValue *GV = GA->getGlobal();
2182   DebugLoc dl = GA->getDebugLoc();
2183   SDValue Offset;
2184   SDValue Chain = DAG.getEntryNode();
2185   EVT PtrVT = getPointerTy();
2186   // Get the Thread Pointer
2187   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2188
2189   if (model == TLSModel::InitialExec) {
2190     MachineFunction &MF = DAG.getMachineFunction();
2191     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2192     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2193     // Initial exec model.
2194     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2195     ARMConstantPoolValue *CPV =
2196       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2197                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2198                                       true);
2199     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2200     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2201     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2202                          MachinePointerInfo::getConstantPool(),
2203                          false, false, false, 0);
2204     Chain = Offset.getValue(1);
2205
2206     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2207     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2208
2209     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2210                          MachinePointerInfo::getConstantPool(),
2211                          false, false, false, 0);
2212   } else {
2213     // local exec model
2214     assert(model == TLSModel::LocalExec);
2215     ARMConstantPoolValue *CPV =
2216       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2217     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2218     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2219     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2220                          MachinePointerInfo::getConstantPool(),
2221                          false, false, false, 0);
2222   }
2223
2224   // The address of the thread local variable is the add of the thread
2225   // pointer with the offset of the variable.
2226   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2227 }
2228
2229 SDValue
2230 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2231   // TODO: implement the "local dynamic" model
2232   assert(Subtarget->isTargetELF() &&
2233          "TLS not implemented for non-ELF targets");
2234   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2235
2236   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2237
2238   switch (model) {
2239     case TLSModel::GeneralDynamic:
2240     case TLSModel::LocalDynamic:
2241       return LowerToTLSGeneralDynamicModel(GA, DAG);
2242     case TLSModel::InitialExec:
2243     case TLSModel::LocalExec:
2244       return LowerToTLSExecModels(GA, DAG, model);
2245   }
2246   llvm_unreachable("bogus TLS model");
2247 }
2248
2249 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2250                                                  SelectionDAG &DAG) const {
2251   EVT PtrVT = getPointerTy();
2252   DebugLoc dl = Op.getDebugLoc();
2253   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2254   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2255   if (RelocM == Reloc::PIC_) {
2256     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2257     ARMConstantPoolValue *CPV =
2258       ARMConstantPoolConstant::Create(GV,
2259                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2260     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2261     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2262     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2263                                  CPAddr,
2264                                  MachinePointerInfo::getConstantPool(),
2265                                  false, false, false, 0);
2266     SDValue Chain = Result.getValue(1);
2267     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2268     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2269     if (!UseGOTOFF)
2270       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2271                            MachinePointerInfo::getGOT(),
2272                            false, false, false, 0);
2273     return Result;
2274   }
2275
2276   // If we have T2 ops, we can materialize the address directly via movt/movw
2277   // pair. This is always cheaper.
2278   if (Subtarget->useMovt()) {
2279     ++NumMovwMovt;
2280     // FIXME: Once remat is capable of dealing with instructions with register
2281     // operands, expand this into two nodes.
2282     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2283                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2284   } else {
2285     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2286     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2287     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2288                        MachinePointerInfo::getConstantPool(),
2289                        false, false, false, 0);
2290   }
2291 }
2292
2293 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2294                                                     SelectionDAG &DAG) const {
2295   EVT PtrVT = getPointerTy();
2296   DebugLoc dl = Op.getDebugLoc();
2297   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2298   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2299   MachineFunction &MF = DAG.getMachineFunction();
2300   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2301
2302   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2303   // update ARMFastISel::ARMMaterializeGV.
2304   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2305     ++NumMovwMovt;
2306     // FIXME: Once remat is capable of dealing with instructions with register
2307     // operands, expand this into two nodes.
2308     if (RelocM == Reloc::Static)
2309       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2310                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2311
2312     unsigned Wrapper = (RelocM == Reloc::PIC_)
2313       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2314     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2315                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2316     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2317       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2318                            MachinePointerInfo::getGOT(),
2319                            false, false, false, 0);
2320     return Result;
2321   }
2322
2323   unsigned ARMPCLabelIndex = 0;
2324   SDValue CPAddr;
2325   if (RelocM == Reloc::Static) {
2326     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2327   } else {
2328     ARMPCLabelIndex = AFI->createPICLabelUId();
2329     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2330     ARMConstantPoolValue *CPV =
2331       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2332                                       PCAdj);
2333     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2334   }
2335   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2336
2337   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2338                                MachinePointerInfo::getConstantPool(),
2339                                false, false, false, 0);
2340   SDValue Chain = Result.getValue(1);
2341
2342   if (RelocM == Reloc::PIC_) {
2343     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2344     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2345   }
2346
2347   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2348     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2349                          false, false, false, 0);
2350
2351   return Result;
2352 }
2353
2354 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2355                                                     SelectionDAG &DAG) const {
2356   assert(Subtarget->isTargetELF() &&
2357          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2358   MachineFunction &MF = DAG.getMachineFunction();
2359   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2360   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2361   EVT PtrVT = getPointerTy();
2362   DebugLoc dl = Op.getDebugLoc();
2363   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2364   ARMConstantPoolValue *CPV =
2365     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2366                                   ARMPCLabelIndex, PCAdj);
2367   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2369   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2370                                MachinePointerInfo::getConstantPool(),
2371                                false, false, false, 0);
2372   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2373   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2374 }
2375
2376 SDValue
2377 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2378   DebugLoc dl = Op.getDebugLoc();
2379   SDValue Val = DAG.getConstant(0, MVT::i32);
2380   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2381                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2382                      Op.getOperand(1), Val);
2383 }
2384
2385 SDValue
2386 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2387   DebugLoc dl = Op.getDebugLoc();
2388   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2389                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2390 }
2391
2392 SDValue
2393 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2394                                           const ARMSubtarget *Subtarget) const {
2395   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2396   DebugLoc dl = Op.getDebugLoc();
2397   switch (IntNo) {
2398   default: return SDValue();    // Don't custom lower most intrinsics.
2399   case Intrinsic::arm_thread_pointer: {
2400     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2401     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2402   }
2403   case Intrinsic::eh_sjlj_lsda: {
2404     MachineFunction &MF = DAG.getMachineFunction();
2405     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2406     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2407     EVT PtrVT = getPointerTy();
2408     DebugLoc dl = Op.getDebugLoc();
2409     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2410     SDValue CPAddr;
2411     unsigned PCAdj = (RelocM != Reloc::PIC_)
2412       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2413     ARMConstantPoolValue *CPV =
2414       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2415                                       ARMCP::CPLSDA, PCAdj);
2416     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2417     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2418     SDValue Result =
2419       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2420                   MachinePointerInfo::getConstantPool(),
2421                   false, false, false, 0);
2422
2423     if (RelocM == Reloc::PIC_) {
2424       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2425       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2426     }
2427     return Result;
2428   }
2429   case Intrinsic::arm_neon_vmulls:
2430   case Intrinsic::arm_neon_vmullu: {
2431     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2432       ? ARMISD::VMULLs : ARMISD::VMULLu;
2433     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2434                        Op.getOperand(1), Op.getOperand(2));
2435   }
2436   case Intrinsic::arm_neon_vaddls:
2437   case Intrinsic::arm_neon_vaddlu: {
2438     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vaddls)
2439       ? ARMISD::VADDLs : ARMISD::VADDLu;
2440     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2441                        Op.getOperand(1), Op.getOperand(2));
2442   }
2443   case Intrinsic::arm_neon_vsubls:
2444   case Intrinsic::arm_neon_vsublu: {
2445     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vsubls)
2446       ? ARMISD::VSUBLs: ARMISD::VSUBLu;
2447     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2448                        Op.getOperand(1), Op.getOperand(2));
2449   }
2450   }
2451 }
2452
2453 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2454                                const ARMSubtarget *Subtarget) {
2455   DebugLoc dl = Op.getDebugLoc();
2456   if (!Subtarget->hasDataBarrier()) {
2457     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2458     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2459     // here.
2460     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2461            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2462     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2463                        DAG.getConstant(0, MVT::i32));
2464   }
2465
2466   SDValue Op5 = Op.getOperand(5);
2467   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2468   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2469   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2470   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2471
2472   ARM_MB::MemBOpt DMBOpt;
2473   if (isDeviceBarrier)
2474     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2475   else
2476     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2477   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2478                      DAG.getConstant(DMBOpt, MVT::i32));
2479 }
2480
2481
2482 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2483                                  const ARMSubtarget *Subtarget) {
2484   // FIXME: handle "fence singlethread" more efficiently.
2485   DebugLoc dl = Op.getDebugLoc();
2486   if (!Subtarget->hasDataBarrier()) {
2487     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2488     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2489     // here.
2490     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2491            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2492     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2493                        DAG.getConstant(0, MVT::i32));
2494   }
2495
2496   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2497                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2498 }
2499
2500 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2501                              const ARMSubtarget *Subtarget) {
2502   // ARM pre v5TE and Thumb1 does not have preload instructions.
2503   if (!(Subtarget->isThumb2() ||
2504         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2505     // Just preserve the chain.
2506     return Op.getOperand(0);
2507
2508   DebugLoc dl = Op.getDebugLoc();
2509   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2510   if (!isRead &&
2511       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2512     // ARMv7 with MP extension has PLDW.
2513     return Op.getOperand(0);
2514
2515   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2516   if (Subtarget->isThumb()) {
2517     // Invert the bits.
2518     isRead = ~isRead & 1;
2519     isData = ~isData & 1;
2520   }
2521
2522   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2523                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2524                      DAG.getConstant(isData, MVT::i32));
2525 }
2526
2527 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2530
2531   // vastart just stores the address of the VarArgsFrameIndex slot into the
2532   // memory location argument.
2533   DebugLoc dl = Op.getDebugLoc();
2534   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2535   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2536   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2537   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2538                       MachinePointerInfo(SV), false, false, 0);
2539 }
2540
2541 SDValue
2542 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2543                                         SDValue &Root, SelectionDAG &DAG,
2544                                         DebugLoc dl) const {
2545   MachineFunction &MF = DAG.getMachineFunction();
2546   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2547
2548   const TargetRegisterClass *RC;
2549   if (AFI->isThumb1OnlyFunction())
2550     RC = &ARM::tGPRRegClass;
2551   else
2552     RC = &ARM::GPRRegClass;
2553
2554   // Transform the arguments stored in physical registers into virtual ones.
2555   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2556   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2557
2558   SDValue ArgValue2;
2559   if (NextVA.isMemLoc()) {
2560     MachineFrameInfo *MFI = MF.getFrameInfo();
2561     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2562
2563     // Create load node to retrieve arguments from the stack.
2564     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2565     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2566                             MachinePointerInfo::getFixedStack(FI),
2567                             false, false, false, 0);
2568   } else {
2569     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2570     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2571   }
2572
2573   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2574 }
2575
2576 void
2577 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2578                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2579   const {
2580   unsigned NumGPRs;
2581   if (CCInfo.isFirstByValRegValid())
2582     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2583   else {
2584     unsigned int firstUnalloced;
2585     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2586                                                 sizeof(GPRArgRegs) /
2587                                                 sizeof(GPRArgRegs[0]));
2588     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2589   }
2590
2591   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2592   VARegSize = NumGPRs * 4;
2593   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2594 }
2595
2596 // The remaining GPRs hold either the beginning of variable-argument
2597 // data, or the beginning of an aggregate passed by value (usuall
2598 // byval).  Either way, we allocate stack slots adjacent to the data
2599 // provided by our caller, and store the unallocated registers there.
2600 // If this is a variadic function, the va_list pointer will begin with
2601 // these values; otherwise, this reassembles a (byval) structure that
2602 // was split between registers and memory.
2603 void
2604 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2605                                         DebugLoc dl, SDValue &Chain,
2606                                         const Value *OrigArg,
2607                                         unsigned OffsetFromOrigArg,
2608                                         unsigned ArgOffset,
2609                                         bool ForceMutable) const {
2610   MachineFunction &MF = DAG.getMachineFunction();
2611   MachineFrameInfo *MFI = MF.getFrameInfo();
2612   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2613   unsigned firstRegToSaveIndex;
2614   if (CCInfo.isFirstByValRegValid())
2615     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2616   else {
2617     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2618       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2619   }
2620
2621   unsigned VARegSize, VARegSaveSize;
2622   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2623   if (VARegSaveSize) {
2624     // If this function is vararg, store any remaining integer argument regs
2625     // to their spots on the stack so that they may be loaded by deferencing
2626     // the result of va_next.
2627     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2628     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2629                                                      ArgOffset + VARegSaveSize
2630                                                      - VARegSize,
2631                                                      false));
2632     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2633                                     getPointerTy());
2634
2635     SmallVector<SDValue, 4> MemOps;
2636     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2637       const TargetRegisterClass *RC;
2638       if (AFI->isThumb1OnlyFunction())
2639         RC = &ARM::tGPRRegClass;
2640       else
2641         RC = &ARM::GPRRegClass;
2642
2643       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2644       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2645       SDValue Store =
2646         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2647                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2648                      false, false, 0);
2649       MemOps.push_back(Store);
2650       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2651                         DAG.getConstant(4, getPointerTy()));
2652     }
2653     if (!MemOps.empty())
2654       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2655                           &MemOps[0], MemOps.size());
2656   } else
2657     // This will point to the next argument passed via stack.
2658     AFI->setVarArgsFrameIndex(
2659         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2660 }
2661
2662 SDValue
2663 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2664                                         CallingConv::ID CallConv, bool isVarArg,
2665                                         const SmallVectorImpl<ISD::InputArg>
2666                                           &Ins,
2667                                         DebugLoc dl, SelectionDAG &DAG,
2668                                         SmallVectorImpl<SDValue> &InVals)
2669                                           const {
2670   MachineFunction &MF = DAG.getMachineFunction();
2671   MachineFrameInfo *MFI = MF.getFrameInfo();
2672
2673   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2674
2675   // Assign locations to all of the incoming arguments.
2676   SmallVector<CCValAssign, 16> ArgLocs;
2677   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2678                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2679   CCInfo.AnalyzeFormalArguments(Ins,
2680                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2681                                                   isVarArg));
2682   
2683   SmallVector<SDValue, 16> ArgValues;
2684   int lastInsIndex = -1;
2685   SDValue ArgValue;
2686   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2687   unsigned CurArgIdx = 0;
2688   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2689     CCValAssign &VA = ArgLocs[i];
2690     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2691     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2692     // Arguments stored in registers.
2693     if (VA.isRegLoc()) {
2694       EVT RegVT = VA.getLocVT();
2695
2696       if (VA.needsCustom()) {
2697         // f64 and vector types are split up into multiple registers or
2698         // combinations of registers and stack slots.
2699         if (VA.getLocVT() == MVT::v2f64) {
2700           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2701                                                    Chain, DAG, dl);
2702           VA = ArgLocs[++i]; // skip ahead to next loc
2703           SDValue ArgValue2;
2704           if (VA.isMemLoc()) {
2705             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2706             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2707             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2708                                     MachinePointerInfo::getFixedStack(FI),
2709                                     false, false, false, 0);
2710           } else {
2711             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2712                                              Chain, DAG, dl);
2713           }
2714           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2715           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2716                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2717           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2718                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2719         } else
2720           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2721
2722       } else {
2723         const TargetRegisterClass *RC;
2724
2725         if (RegVT == MVT::f32)
2726           RC = &ARM::SPRRegClass;
2727         else if (RegVT == MVT::f64)
2728           RC = &ARM::DPRRegClass;
2729         else if (RegVT == MVT::v2f64)
2730           RC = &ARM::QPRRegClass;
2731         else if (RegVT == MVT::i32)
2732           RC = AFI->isThumb1OnlyFunction() ?
2733             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2734             (const TargetRegisterClass*)&ARM::GPRRegClass;
2735         else
2736           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2737
2738         // Transform the arguments in physical registers into virtual ones.
2739         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2740         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2741       }
2742
2743       // If this is an 8 or 16-bit value, it is really passed promoted
2744       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2745       // truncate to the right size.
2746       switch (VA.getLocInfo()) {
2747       default: llvm_unreachable("Unknown loc info!");
2748       case CCValAssign::Full: break;
2749       case CCValAssign::BCvt:
2750         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2751         break;
2752       case CCValAssign::SExt:
2753         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2754                                DAG.getValueType(VA.getValVT()));
2755         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2756         break;
2757       case CCValAssign::ZExt:
2758         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2759                                DAG.getValueType(VA.getValVT()));
2760         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2761         break;
2762       }
2763
2764       InVals.push_back(ArgValue);
2765
2766     } else { // VA.isRegLoc()
2767
2768       // sanity check
2769       assert(VA.isMemLoc());
2770       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2771
2772       int index = ArgLocs[i].getValNo();
2773
2774       // Some Ins[] entries become multiple ArgLoc[] entries.
2775       // Process them only once.
2776       if (index != lastInsIndex)
2777         {
2778           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2779           // FIXME: For now, all byval parameter objects are marked mutable.
2780           // This can be changed with more analysis.
2781           // In case of tail call optimization mark all arguments mutable.
2782           // Since they could be overwritten by lowering of arguments in case of
2783           // a tail call.
2784           if (Flags.isByVal()) {
2785             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2786             if (!AFI->getVarArgsFrameIndex()) {
2787               VarArgStyleRegisters(CCInfo, DAG,
2788                                    dl, Chain, CurOrigArg,
2789                                    Ins[VA.getValNo()].PartOffset,
2790                                    VA.getLocMemOffset(),
2791                                    true /*force mutable frames*/);
2792               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2793               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2794             } else {
2795               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2796                                               VA.getLocMemOffset(), false);
2797               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2798             }
2799           } else {
2800             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2801                                             VA.getLocMemOffset(), true);
2802
2803             // Create load nodes to retrieve arguments from the stack.
2804             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2805             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2806                                          MachinePointerInfo::getFixedStack(FI),
2807                                          false, false, false, 0));
2808           }
2809           lastInsIndex = index;
2810         }
2811     }
2812   }
2813
2814   // varargs
2815   if (isVarArg)
2816     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2817                          CCInfo.getNextStackOffset());
2818
2819   return Chain;
2820 }
2821
2822 /// isFloatingPointZero - Return true if this is +0.0.
2823 static bool isFloatingPointZero(SDValue Op) {
2824   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2825     return CFP->getValueAPF().isPosZero();
2826   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2827     // Maybe this has already been legalized into the constant pool?
2828     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2829       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2830       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2831         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2832           return CFP->getValueAPF().isPosZero();
2833     }
2834   }
2835   return false;
2836 }
2837
2838 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2839 /// the given operands.
2840 SDValue
2841 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2842                              SDValue &ARMcc, SelectionDAG &DAG,
2843                              DebugLoc dl) const {
2844   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2845     unsigned C = RHSC->getZExtValue();
2846     if (!isLegalICmpImmediate(C)) {
2847       // Constant does not fit, try adjusting it by one?
2848       switch (CC) {
2849       default: break;
2850       case ISD::SETLT:
2851       case ISD::SETGE:
2852         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2853           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2854           RHS = DAG.getConstant(C-1, MVT::i32);
2855         }
2856         break;
2857       case ISD::SETULT:
2858       case ISD::SETUGE:
2859         if (C != 0 && isLegalICmpImmediate(C-1)) {
2860           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2861           RHS = DAG.getConstant(C-1, MVT::i32);
2862         }
2863         break;
2864       case ISD::SETLE:
2865       case ISD::SETGT:
2866         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2867           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2868           RHS = DAG.getConstant(C+1, MVT::i32);
2869         }
2870         break;
2871       case ISD::SETULE:
2872       case ISD::SETUGT:
2873         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2874           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2875           RHS = DAG.getConstant(C+1, MVT::i32);
2876         }
2877         break;
2878       }
2879     }
2880   }
2881
2882   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2883   ARMISD::NodeType CompareType;
2884   switch (CondCode) {
2885   default:
2886     CompareType = ARMISD::CMP;
2887     break;
2888   case ARMCC::EQ:
2889   case ARMCC::NE:
2890     // Uses only Z Flag
2891     CompareType = ARMISD::CMPZ;
2892     break;
2893   }
2894   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2895   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2896 }
2897
2898 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2899 SDValue
2900 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2901                              DebugLoc dl) const {
2902   SDValue Cmp;
2903   if (!isFloatingPointZero(RHS))
2904     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2905   else
2906     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2907   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2908 }
2909
2910 /// duplicateCmp - Glue values can have only one use, so this function
2911 /// duplicates a comparison node.
2912 SDValue
2913 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2914   unsigned Opc = Cmp.getOpcode();
2915   DebugLoc DL = Cmp.getDebugLoc();
2916   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2917     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2918
2919   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2920   Cmp = Cmp.getOperand(0);
2921   Opc = Cmp.getOpcode();
2922   if (Opc == ARMISD::CMPFP)
2923     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2924   else {
2925     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2926     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2927   }
2928   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2929 }
2930
2931 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2932   SDValue Cond = Op.getOperand(0);
2933   SDValue SelectTrue = Op.getOperand(1);
2934   SDValue SelectFalse = Op.getOperand(2);
2935   DebugLoc dl = Op.getDebugLoc();
2936
2937   // Convert:
2938   //
2939   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2940   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2941   //
2942   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2943     const ConstantSDNode *CMOVTrue =
2944       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2945     const ConstantSDNode *CMOVFalse =
2946       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2947
2948     if (CMOVTrue && CMOVFalse) {
2949       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2950       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2951
2952       SDValue True;
2953       SDValue False;
2954       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2955         True = SelectTrue;
2956         False = SelectFalse;
2957       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2958         True = SelectFalse;
2959         False = SelectTrue;
2960       }
2961
2962       if (True.getNode() && False.getNode()) {
2963         EVT VT = Op.getValueType();
2964         SDValue ARMcc = Cond.getOperand(2);
2965         SDValue CCR = Cond.getOperand(3);
2966         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2967         assert(True.getValueType() == VT);
2968         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2969       }
2970     }
2971   }
2972
2973   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2974   // undefined bits before doing a full-word comparison with zero.
2975   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2976                      DAG.getConstant(1, Cond.getValueType()));
2977
2978   return DAG.getSelectCC(dl, Cond,
2979                          DAG.getConstant(0, Cond.getValueType()),
2980                          SelectTrue, SelectFalse, ISD::SETNE);
2981 }
2982
2983 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2984   EVT VT = Op.getValueType();
2985   SDValue LHS = Op.getOperand(0);
2986   SDValue RHS = Op.getOperand(1);
2987   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2988   SDValue TrueVal = Op.getOperand(2);
2989   SDValue FalseVal = Op.getOperand(3);
2990   DebugLoc dl = Op.getDebugLoc();
2991
2992   if (LHS.getValueType() == MVT::i32) {
2993     SDValue ARMcc;
2994     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2995     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2996     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2997   }
2998
2999   ARMCC::CondCodes CondCode, CondCode2;
3000   FPCCToARMCC(CC, CondCode, CondCode2);
3001
3002   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3003   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3004   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3005   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3006                                ARMcc, CCR, Cmp);
3007   if (CondCode2 != ARMCC::AL) {
3008     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3009     // FIXME: Needs another CMP because flag can have but one use.
3010     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3011     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3012                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3013   }
3014   return Result;
3015 }
3016
3017 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3018 /// to morph to an integer compare sequence.
3019 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3020                            const ARMSubtarget *Subtarget) {
3021   SDNode *N = Op.getNode();
3022   if (!N->hasOneUse())
3023     // Otherwise it requires moving the value from fp to integer registers.
3024     return false;
3025   if (!N->getNumValues())
3026     return false;
3027   EVT VT = Op.getValueType();
3028   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3029     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3030     // vmrs are very slow, e.g. cortex-a8.
3031     return false;
3032
3033   if (isFloatingPointZero(Op)) {
3034     SeenZero = true;
3035     return true;
3036   }
3037   return ISD::isNormalLoad(N);
3038 }
3039
3040 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3041   if (isFloatingPointZero(Op))
3042     return DAG.getConstant(0, MVT::i32);
3043
3044   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3045     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3046                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3047                        Ld->isVolatile(), Ld->isNonTemporal(),
3048                        Ld->isInvariant(), Ld->getAlignment());
3049
3050   llvm_unreachable("Unknown VFP cmp argument!");
3051 }
3052
3053 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3054                            SDValue &RetVal1, SDValue &RetVal2) {
3055   if (isFloatingPointZero(Op)) {
3056     RetVal1 = DAG.getConstant(0, MVT::i32);
3057     RetVal2 = DAG.getConstant(0, MVT::i32);
3058     return;
3059   }
3060
3061   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3062     SDValue Ptr = Ld->getBasePtr();
3063     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3064                           Ld->getChain(), Ptr,
3065                           Ld->getPointerInfo(),
3066                           Ld->isVolatile(), Ld->isNonTemporal(),
3067                           Ld->isInvariant(), Ld->getAlignment());
3068
3069     EVT PtrType = Ptr.getValueType();
3070     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3071     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3072                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3073     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3074                           Ld->getChain(), NewPtr,
3075                           Ld->getPointerInfo().getWithOffset(4),
3076                           Ld->isVolatile(), Ld->isNonTemporal(),
3077                           Ld->isInvariant(), NewAlign);
3078     return;
3079   }
3080
3081   llvm_unreachable("Unknown VFP cmp argument!");
3082 }
3083
3084 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3085 /// f32 and even f64 comparisons to integer ones.
3086 SDValue
3087 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3088   SDValue Chain = Op.getOperand(0);
3089   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3090   SDValue LHS = Op.getOperand(2);
3091   SDValue RHS = Op.getOperand(3);
3092   SDValue Dest = Op.getOperand(4);
3093   DebugLoc dl = Op.getDebugLoc();
3094
3095   bool LHSSeenZero = false;
3096   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3097   bool RHSSeenZero = false;
3098   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3099   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3100     // If unsafe fp math optimization is enabled and there are no other uses of
3101     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3102     // to an integer comparison.
3103     if (CC == ISD::SETOEQ)
3104       CC = ISD::SETEQ;
3105     else if (CC == ISD::SETUNE)
3106       CC = ISD::SETNE;
3107
3108     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3109     SDValue ARMcc;
3110     if (LHS.getValueType() == MVT::f32) {
3111       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3112                         bitcastf32Toi32(LHS, DAG), Mask);
3113       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3114                         bitcastf32Toi32(RHS, DAG), Mask);
3115       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3116       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3117       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3118                          Chain, Dest, ARMcc, CCR, Cmp);
3119     }
3120
3121     SDValue LHS1, LHS2;
3122     SDValue RHS1, RHS2;
3123     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3124     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3125     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3126     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3127     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3128     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3129     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3130     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3131     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3132   }
3133
3134   return SDValue();
3135 }
3136
3137 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3138   SDValue Chain = Op.getOperand(0);
3139   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3140   SDValue LHS = Op.getOperand(2);
3141   SDValue RHS = Op.getOperand(3);
3142   SDValue Dest = Op.getOperand(4);
3143   DebugLoc dl = Op.getDebugLoc();
3144
3145   if (LHS.getValueType() == MVT::i32) {
3146     SDValue ARMcc;
3147     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3148     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3149     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3150                        Chain, Dest, ARMcc, CCR, Cmp);
3151   }
3152
3153   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3154
3155   if (getTargetMachine().Options.UnsafeFPMath &&
3156       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3157        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3158     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3159     if (Result.getNode())
3160       return Result;
3161   }
3162
3163   ARMCC::CondCodes CondCode, CondCode2;
3164   FPCCToARMCC(CC, CondCode, CondCode2);
3165
3166   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3167   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3168   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3169   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3170   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3171   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3172   if (CondCode2 != ARMCC::AL) {
3173     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3174     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3175     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3176   }
3177   return Res;
3178 }
3179
3180 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3181   SDValue Chain = Op.getOperand(0);
3182   SDValue Table = Op.getOperand(1);
3183   SDValue Index = Op.getOperand(2);
3184   DebugLoc dl = Op.getDebugLoc();
3185
3186   EVT PTy = getPointerTy();
3187   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3188   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3189   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3190   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3191   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3192   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3193   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3194   if (Subtarget->isThumb2()) {
3195     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3196     // which does another jump to the destination. This also makes it easier
3197     // to translate it to TBB / TBH later.
3198     // FIXME: This might not work if the function is extremely large.
3199     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3200                        Addr, Op.getOperand(2), JTI, UId);
3201   }
3202   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3203     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3204                        MachinePointerInfo::getJumpTable(),
3205                        false, false, false, 0);
3206     Chain = Addr.getValue(1);
3207     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3208     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3209   } else {
3210     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3211                        MachinePointerInfo::getJumpTable(),
3212                        false, false, false, 0);
3213     Chain = Addr.getValue(1);
3214     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3215   }
3216 }
3217
3218 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3219   EVT VT = Op.getValueType();
3220   DebugLoc dl = Op.getDebugLoc();
3221
3222   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3223     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3224       return Op;
3225     return DAG.UnrollVectorOp(Op.getNode());
3226   }
3227
3228   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3229          "Invalid type for custom lowering!");
3230   if (VT != MVT::v4i16)
3231     return DAG.UnrollVectorOp(Op.getNode());
3232
3233   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3234   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3235 }
3236
3237 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3238   EVT VT = Op.getValueType();
3239   if (VT.isVector())
3240     return LowerVectorFP_TO_INT(Op, DAG);
3241
3242   DebugLoc dl = Op.getDebugLoc();
3243   unsigned Opc;
3244
3245   switch (Op.getOpcode()) {
3246   default: llvm_unreachable("Invalid opcode!");
3247   case ISD::FP_TO_SINT:
3248     Opc = ARMISD::FTOSI;
3249     break;
3250   case ISD::FP_TO_UINT:
3251     Opc = ARMISD::FTOUI;
3252     break;
3253   }
3254   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3255   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3256 }
3257
3258 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3259   EVT VT = Op.getValueType();
3260   DebugLoc dl = Op.getDebugLoc();
3261
3262   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3263     if (VT.getVectorElementType() == MVT::f32)
3264       return Op;
3265     return DAG.UnrollVectorOp(Op.getNode());
3266   }
3267
3268   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3269          "Invalid type for custom lowering!");
3270   if (VT != MVT::v4f32)
3271     return DAG.UnrollVectorOp(Op.getNode());
3272
3273   unsigned CastOpc;
3274   unsigned Opc;
3275   switch (Op.getOpcode()) {
3276   default: llvm_unreachable("Invalid opcode!");
3277   case ISD::SINT_TO_FP:
3278     CastOpc = ISD::SIGN_EXTEND;
3279     Opc = ISD::SINT_TO_FP;
3280     break;
3281   case ISD::UINT_TO_FP:
3282     CastOpc = ISD::ZERO_EXTEND;
3283     Opc = ISD::UINT_TO_FP;
3284     break;
3285   }
3286
3287   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3288   return DAG.getNode(Opc, dl, VT, Op);
3289 }
3290
3291 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3292   EVT VT = Op.getValueType();
3293   if (VT.isVector())
3294     return LowerVectorINT_TO_FP(Op, DAG);
3295
3296   DebugLoc dl = Op.getDebugLoc();
3297   unsigned Opc;
3298
3299   switch (Op.getOpcode()) {
3300   default: llvm_unreachable("Invalid opcode!");
3301   case ISD::SINT_TO_FP:
3302     Opc = ARMISD::SITOF;
3303     break;
3304   case ISD::UINT_TO_FP:
3305     Opc = ARMISD::UITOF;
3306     break;
3307   }
3308
3309   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3310   return DAG.getNode(Opc, dl, VT, Op);
3311 }
3312
3313 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3314   // Implement fcopysign with a fabs and a conditional fneg.
3315   SDValue Tmp0 = Op.getOperand(0);
3316   SDValue Tmp1 = Op.getOperand(1);
3317   DebugLoc dl = Op.getDebugLoc();
3318   EVT VT = Op.getValueType();
3319   EVT SrcVT = Tmp1.getValueType();
3320   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3321     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3322   bool UseNEON = !InGPR && Subtarget->hasNEON();
3323
3324   if (UseNEON) {
3325     // Use VBSL to copy the sign bit.
3326     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3327     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3328                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3329     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3330     if (VT == MVT::f64)
3331       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3332                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3333                          DAG.getConstant(32, MVT::i32));
3334     else /*if (VT == MVT::f32)*/
3335       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3336     if (SrcVT == MVT::f32) {
3337       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3338       if (VT == MVT::f64)
3339         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3340                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3341                            DAG.getConstant(32, MVT::i32));
3342     } else if (VT == MVT::f32)
3343       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3344                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3345                          DAG.getConstant(32, MVT::i32));
3346     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3347     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3348
3349     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3350                                             MVT::i32);
3351     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3352     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3353                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3354
3355     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3356                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3357                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3358     if (VT == MVT::f32) {
3359       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3360       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3361                         DAG.getConstant(0, MVT::i32));
3362     } else {
3363       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3364     }
3365
3366     return Res;
3367   }
3368
3369   // Bitcast operand 1 to i32.
3370   if (SrcVT == MVT::f64)
3371     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3372                        &Tmp1, 1).getValue(1);
3373   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3374
3375   // Or in the signbit with integer operations.
3376   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3377   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3378   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3379   if (VT == MVT::f32) {
3380     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3381                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3382     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3383                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3384   }
3385
3386   // f64: Or the high part with signbit and then combine two parts.
3387   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3388                      &Tmp0, 1);
3389   SDValue Lo = Tmp0.getValue(0);
3390   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3391   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3392   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3393 }
3394
3395 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3396   MachineFunction &MF = DAG.getMachineFunction();
3397   MachineFrameInfo *MFI = MF.getFrameInfo();
3398   MFI->setReturnAddressIsTaken(true);
3399
3400   EVT VT = Op.getValueType();
3401   DebugLoc dl = Op.getDebugLoc();
3402   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3403   if (Depth) {
3404     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3405     SDValue Offset = DAG.getConstant(4, MVT::i32);
3406     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3407                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3408                        MachinePointerInfo(), false, false, false, 0);
3409   }
3410
3411   // Return LR, which contains the return address. Mark it an implicit live-in.
3412   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3413   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3414 }
3415
3416 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3417   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3418   MFI->setFrameAddressIsTaken(true);
3419
3420   EVT VT = Op.getValueType();
3421   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3422   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3423   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3424     ? ARM::R7 : ARM::R11;
3425   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3426   while (Depth--)
3427     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3428                             MachinePointerInfo(),
3429                             false, false, false, 0);
3430   return FrameAddr;
3431 }
3432
3433 /// ExpandBITCAST - If the target supports VFP, this function is called to
3434 /// expand a bit convert where either the source or destination type is i64 to
3435 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3436 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3437 /// vectors), since the legalizer won't know what to do with that.
3438 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3440   DebugLoc dl = N->getDebugLoc();
3441   SDValue Op = N->getOperand(0);
3442
3443   // This function is only supposed to be called for i64 types, either as the
3444   // source or destination of the bit convert.
3445   EVT SrcVT = Op.getValueType();
3446   EVT DstVT = N->getValueType(0);
3447   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3448          "ExpandBITCAST called for non-i64 type");
3449
3450   // Turn i64->f64 into VMOVDRR.
3451   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3452     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3453                              DAG.getConstant(0, MVT::i32));
3454     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3455                              DAG.getConstant(1, MVT::i32));
3456     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3457                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3458   }
3459
3460   // Turn f64->i64 into VMOVRRD.
3461   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3462     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3463                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3464     // Merge the pieces into a single i64 value.
3465     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3466   }
3467
3468   return SDValue();
3469 }
3470
3471 /// getZeroVector - Returns a vector of specified type with all zero elements.
3472 /// Zero vectors are used to represent vector negation and in those cases
3473 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3474 /// not support i64 elements, so sometimes the zero vectors will need to be
3475 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3476 /// zero vector.
3477 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3478   assert(VT.isVector() && "Expected a vector type");
3479   // The canonical modified immediate encoding of a zero vector is....0!
3480   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3481   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3482   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3483   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3484 }
3485
3486 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3487 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3488 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3489                                                 SelectionDAG &DAG) const {
3490   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3491   EVT VT = Op.getValueType();
3492   unsigned VTBits = VT.getSizeInBits();
3493   DebugLoc dl = Op.getDebugLoc();
3494   SDValue ShOpLo = Op.getOperand(0);
3495   SDValue ShOpHi = Op.getOperand(1);
3496   SDValue ShAmt  = Op.getOperand(2);
3497   SDValue ARMcc;
3498   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3499
3500   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3501
3502   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3503                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3504   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3505   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3506                                    DAG.getConstant(VTBits, MVT::i32));
3507   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3508   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3509   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3510
3511   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3512   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3513                           ARMcc, DAG, dl);
3514   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3515   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3516                            CCR, Cmp);
3517
3518   SDValue Ops[2] = { Lo, Hi };
3519   return DAG.getMergeValues(Ops, 2, dl);
3520 }
3521
3522 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3523 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3524 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3525                                                SelectionDAG &DAG) const {
3526   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3527   EVT VT = Op.getValueType();
3528   unsigned VTBits = VT.getSizeInBits();
3529   DebugLoc dl = Op.getDebugLoc();
3530   SDValue ShOpLo = Op.getOperand(0);
3531   SDValue ShOpHi = Op.getOperand(1);
3532   SDValue ShAmt  = Op.getOperand(2);
3533   SDValue ARMcc;
3534
3535   assert(Op.getOpcode() == ISD::SHL_PARTS);
3536   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3537                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3538   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3539   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3540                                    DAG.getConstant(VTBits, MVT::i32));
3541   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3542   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3543
3544   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3545   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3546   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3547                           ARMcc, DAG, dl);
3548   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3549   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3550                            CCR, Cmp);
3551
3552   SDValue Ops[2] = { Lo, Hi };
3553   return DAG.getMergeValues(Ops, 2, dl);
3554 }
3555
3556 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3557                                             SelectionDAG &DAG) const {
3558   // The rounding mode is in bits 23:22 of the FPSCR.
3559   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3560   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3561   // so that the shift + and get folded into a bitfield extract.
3562   DebugLoc dl = Op.getDebugLoc();
3563   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3564                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3565                                               MVT::i32));
3566   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3567                                   DAG.getConstant(1U << 22, MVT::i32));
3568   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3569                               DAG.getConstant(22, MVT::i32));
3570   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3571                      DAG.getConstant(3, MVT::i32));
3572 }
3573
3574 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3575                          const ARMSubtarget *ST) {
3576   EVT VT = N->getValueType(0);
3577   DebugLoc dl = N->getDebugLoc();
3578
3579   if (!ST->hasV6T2Ops())
3580     return SDValue();
3581
3582   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3583   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3584 }
3585
3586 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3587 /// for each 16-bit element from operand, repeated.  The basic idea is to
3588 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3589 ///
3590 /// Trace for v4i16:
3591 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3592 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3593 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3594 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 
3595 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3596 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3597 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3598 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3599 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3600   EVT VT = N->getValueType(0);
3601   DebugLoc DL = N->getDebugLoc();
3602
3603   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3604   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3605   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3606   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3607   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3608   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3609 }
3610
3611 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3612 /// bit-count for each 16-bit element from the operand.  We need slightly
3613 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3614 /// 64/128-bit registers.
3615 /// 
3616 /// Trace for v4i16:
3617 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3618 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3619 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3620 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3621 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3622   EVT VT = N->getValueType(0);
3623   DebugLoc DL = N->getDebugLoc();
3624
3625   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3626   if (VT.is64BitVector()) {
3627     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3628     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3629                        DAG.getIntPtrConstant(0));
3630   } else {
3631     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3632                                     BitCounts, DAG.getIntPtrConstant(0));
3633     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3634   }
3635 }
3636
3637 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3638 /// bit-count for each 32-bit element from the operand.  The idea here is
3639 /// to split the vector into 16-bit elements, leverage the 16-bit count
3640 /// routine, and then combine the results.
3641 ///
3642 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3643 /// input    = [v0    v1    ] (vi: 32-bit elements)
3644 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3645 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3646 /// vrev: N0 = [k1 k0 k3 k2 ] 
3647 ///            [k0 k1 k2 k3 ]
3648 ///       N1 =+[k1 k0 k3 k2 ]
3649 ///            [k0 k2 k1 k3 ]
3650 ///       N2 =+[k1 k3 k0 k2 ]
3651 ///            [k0    k2    k1    k3    ]
3652 /// Extended =+[k1    k3    k0    k2    ]
3653 ///            [k0    k2    ]
3654 /// Extracted=+[k1    k3    ]
3655 ///
3656 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3657   EVT VT = N->getValueType(0);
3658   DebugLoc DL = N->getDebugLoc();
3659
3660   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3661
3662   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3663   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3664   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3665   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3666   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3667
3668   if (VT.is64BitVector()) {
3669     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3670     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3671                        DAG.getIntPtrConstant(0));
3672   } else {
3673     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3674                                     DAG.getIntPtrConstant(0));
3675     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3676   }
3677 }
3678
3679 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3680                           const ARMSubtarget *ST) {
3681   EVT VT = N->getValueType(0);
3682
3683   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3684   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3685           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3686          "Unexpected type for custom ctpop lowering");
3687
3688   if (VT.getVectorElementType() == MVT::i32)
3689     return lowerCTPOP32BitElements(N, DAG);
3690   else
3691     return lowerCTPOP16BitElements(N, DAG);
3692 }
3693
3694 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3695                           const ARMSubtarget *ST) {
3696   EVT VT = N->getValueType(0);
3697   DebugLoc dl = N->getDebugLoc();
3698
3699   if (!VT.isVector())
3700     return SDValue();
3701
3702   // Lower vector shifts on NEON to use VSHL.
3703   assert(ST->hasNEON() && "unexpected vector shift");
3704
3705   // Left shifts translate directly to the vshiftu intrinsic.
3706   if (N->getOpcode() == ISD::SHL)
3707     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3708                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3709                        N->getOperand(0), N->getOperand(1));
3710
3711   assert((N->getOpcode() == ISD::SRA ||
3712           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3713
3714   // NEON uses the same intrinsics for both left and right shifts.  For
3715   // right shifts, the shift amounts are negative, so negate the vector of
3716   // shift amounts.
3717   EVT ShiftVT = N->getOperand(1).getValueType();
3718   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3719                                      getZeroVector(ShiftVT, DAG, dl),
3720                                      N->getOperand(1));
3721   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3722                              Intrinsic::arm_neon_vshifts :
3723                              Intrinsic::arm_neon_vshiftu);
3724   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3725                      DAG.getConstant(vshiftInt, MVT::i32),
3726                      N->getOperand(0), NegatedCount);
3727 }
3728
3729 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3730                                 const ARMSubtarget *ST) {
3731   EVT VT = N->getValueType(0);
3732   DebugLoc dl = N->getDebugLoc();
3733
3734   // We can get here for a node like i32 = ISD::SHL i32, i64
3735   if (VT != MVT::i64)
3736     return SDValue();
3737
3738   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3739          "Unknown shift to lower!");
3740
3741   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3742   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3743       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3744     return SDValue();
3745
3746   // If we are in thumb mode, we don't have RRX.
3747   if (ST->isThumb1Only()) return SDValue();
3748
3749   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3750   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3751                            DAG.getConstant(0, MVT::i32));
3752   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3753                            DAG.getConstant(1, MVT::i32));
3754
3755   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3756   // captures the result into a carry flag.
3757   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3758   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3759
3760   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3761   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3762
3763   // Merge the pieces into a single i64 value.
3764  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3765 }
3766
3767 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3768   SDValue TmpOp0, TmpOp1;
3769   bool Invert = false;
3770   bool Swap = false;
3771   unsigned Opc = 0;
3772
3773   SDValue Op0 = Op.getOperand(0);
3774   SDValue Op1 = Op.getOperand(1);
3775   SDValue CC = Op.getOperand(2);
3776   EVT VT = Op.getValueType();
3777   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3778   DebugLoc dl = Op.getDebugLoc();
3779
3780   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3781     switch (SetCCOpcode) {
3782     default: llvm_unreachable("Illegal FP comparison");
3783     case ISD::SETUNE:
3784     case ISD::SETNE:  Invert = true; // Fallthrough
3785     case ISD::SETOEQ:
3786     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3787     case ISD::SETOLT:
3788     case ISD::SETLT: Swap = true; // Fallthrough
3789     case ISD::SETOGT:
3790     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3791     case ISD::SETOLE:
3792     case ISD::SETLE:  Swap = true; // Fallthrough
3793     case ISD::SETOGE:
3794     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3795     case ISD::SETUGE: Swap = true; // Fallthrough
3796     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3797     case ISD::SETUGT: Swap = true; // Fallthrough
3798     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3799     case ISD::SETUEQ: Invert = true; // Fallthrough
3800     case ISD::SETONE:
3801       // Expand this to (OLT | OGT).
3802       TmpOp0 = Op0;
3803       TmpOp1 = Op1;
3804       Opc = ISD::OR;
3805       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3806       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3807       break;
3808     case ISD::SETUO: Invert = true; // Fallthrough
3809     case ISD::SETO:
3810       // Expand this to (OLT | OGE).
3811       TmpOp0 = Op0;
3812       TmpOp1 = Op1;
3813       Opc = ISD::OR;
3814       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3815       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3816       break;
3817     }
3818   } else {
3819     // Integer comparisons.
3820     switch (SetCCOpcode) {
3821     default: llvm_unreachable("Illegal integer comparison");
3822     case ISD::SETNE:  Invert = true;
3823     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3824     case ISD::SETLT:  Swap = true;
3825     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3826     case ISD::SETLE:  Swap = true;
3827     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3828     case ISD::SETULT: Swap = true;
3829     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3830     case ISD::SETULE: Swap = true;
3831     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3832     }
3833
3834     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3835     if (Opc == ARMISD::VCEQ) {
3836
3837       SDValue AndOp;
3838       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3839         AndOp = Op0;
3840       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3841         AndOp = Op1;
3842
3843       // Ignore bitconvert.
3844       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3845         AndOp = AndOp.getOperand(0);
3846
3847       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3848         Opc = ARMISD::VTST;
3849         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3850         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3851         Invert = !Invert;
3852       }
3853     }
3854   }
3855
3856   if (Swap)
3857     std::swap(Op0, Op1);
3858
3859   // If one of the operands is a constant vector zero, attempt to fold the
3860   // comparison to a specialized compare-against-zero form.
3861   SDValue SingleOp;
3862   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3863     SingleOp = Op0;
3864   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3865     if (Opc == ARMISD::VCGE)
3866       Opc = ARMISD::VCLEZ;
3867     else if (Opc == ARMISD::VCGT)
3868       Opc = ARMISD::VCLTZ;
3869     SingleOp = Op1;
3870   }
3871
3872   SDValue Result;
3873   if (SingleOp.getNode()) {
3874     switch (Opc) {
3875     case ARMISD::VCEQ:
3876       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3877     case ARMISD::VCGE:
3878       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3879     case ARMISD::VCLEZ:
3880       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3881     case ARMISD::VCGT:
3882       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3883     case ARMISD::VCLTZ:
3884       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3885     default:
3886       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3887     }
3888   } else {
3889      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3890   }
3891
3892   if (Invert)
3893     Result = DAG.getNOT(dl, Result, VT);
3894
3895   return Result;
3896 }
3897
3898 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3899 /// valid vector constant for a NEON instruction with a "modified immediate"
3900 /// operand (e.g., VMOV).  If so, return the encoded value.
3901 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3902                                  unsigned SplatBitSize, SelectionDAG &DAG,
3903                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3904   unsigned OpCmode, Imm;
3905
3906   // SplatBitSize is set to the smallest size that splats the vector, so a
3907   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3908   // immediate instructions others than VMOV do not support the 8-bit encoding
3909   // of a zero vector, and the default encoding of zero is supposed to be the
3910   // 32-bit version.
3911   if (SplatBits == 0)
3912     SplatBitSize = 32;
3913
3914   switch (SplatBitSize) {
3915   case 8:
3916     if (type != VMOVModImm)
3917       return SDValue();
3918     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3919     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3920     OpCmode = 0xe;
3921     Imm = SplatBits;
3922     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3923     break;
3924
3925   case 16:
3926     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3927     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3928     if ((SplatBits & ~0xff) == 0) {
3929       // Value = 0x00nn: Op=x, Cmode=100x.
3930       OpCmode = 0x8;
3931       Imm = SplatBits;
3932       break;
3933     }
3934     if ((SplatBits & ~0xff00) == 0) {
3935       // Value = 0xnn00: Op=x, Cmode=101x.
3936       OpCmode = 0xa;
3937       Imm = SplatBits >> 8;
3938       break;
3939     }
3940     return SDValue();
3941
3942   case 32:
3943     // NEON's 32-bit VMOV supports splat values where:
3944     // * only one byte is nonzero, or
3945     // * the least significant byte is 0xff and the second byte is nonzero, or
3946     // * the least significant 2 bytes are 0xff and the third is nonzero.
3947     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3948     if ((SplatBits & ~0xff) == 0) {
3949       // Value = 0x000000nn: Op=x, Cmode=000x.
3950       OpCmode = 0;
3951       Imm = SplatBits;
3952       break;
3953     }
3954     if ((SplatBits & ~0xff00) == 0) {
3955       // Value = 0x0000nn00: Op=x, Cmode=001x.
3956       OpCmode = 0x2;
3957       Imm = SplatBits >> 8;
3958       break;
3959     }
3960     if ((SplatBits & ~0xff0000) == 0) {
3961       // Value = 0x00nn0000: Op=x, Cmode=010x.
3962       OpCmode = 0x4;
3963       Imm = SplatBits >> 16;
3964       break;
3965     }
3966     if ((SplatBits & ~0xff000000) == 0) {
3967       // Value = 0xnn000000: Op=x, Cmode=011x.
3968       OpCmode = 0x6;
3969       Imm = SplatBits >> 24;
3970       break;
3971     }
3972
3973     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3974     if (type == OtherModImm) return SDValue();
3975
3976     if ((SplatBits & ~0xffff) == 0 &&
3977         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3978       // Value = 0x0000nnff: Op=x, Cmode=1100.
3979       OpCmode = 0xc;
3980       Imm = SplatBits >> 8;
3981       SplatBits |= 0xff;
3982       break;
3983     }
3984
3985     if ((SplatBits & ~0xffffff) == 0 &&
3986         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3987       // Value = 0x00nnffff: Op=x, Cmode=1101.
3988       OpCmode = 0xd;
3989       Imm = SplatBits >> 16;
3990       SplatBits |= 0xffff;
3991       break;
3992     }
3993
3994     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3995     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3996     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3997     // and fall through here to test for a valid 64-bit splat.  But, then the
3998     // caller would also need to check and handle the change in size.
3999     return SDValue();
4000
4001   case 64: {
4002     if (type != VMOVModImm)
4003       return SDValue();
4004     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4005     uint64_t BitMask = 0xff;
4006     uint64_t Val = 0;
4007     unsigned ImmMask = 1;
4008     Imm = 0;
4009     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4010       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4011         Val |= BitMask;
4012         Imm |= ImmMask;
4013       } else if ((SplatBits & BitMask) != 0) {
4014         return SDValue();
4015       }
4016       BitMask <<= 8;
4017       ImmMask <<= 1;
4018     }
4019     // Op=1, Cmode=1110.
4020     OpCmode = 0x1e;
4021     SplatBits = Val;
4022     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4023     break;
4024   }
4025
4026   default:
4027     llvm_unreachable("unexpected size for isNEONModifiedImm");
4028   }
4029
4030   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4031   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4032 }
4033
4034 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4035                                            const ARMSubtarget *ST) const {
4036   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4037     return SDValue();
4038
4039   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4040   assert(Op.getValueType() == MVT::f32 &&
4041          "ConstantFP custom lowering should only occur for f32.");
4042
4043   // Try splatting with a VMOV.f32...
4044   APFloat FPVal = CFP->getValueAPF();
4045   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4046   if (ImmVal != -1) {
4047     DebugLoc DL = Op.getDebugLoc();
4048     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4049     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4050                                       NewVal);
4051     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4052                        DAG.getConstant(0, MVT::i32));
4053   }
4054
4055   // If that fails, try a VMOV.i32
4056   EVT VMovVT;
4057   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4058   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4059                                      VMOVModImm);
4060   if (NewVal != SDValue()) {
4061     DebugLoc DL = Op.getDebugLoc();
4062     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4063                                       NewVal);
4064     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4065                                        VecConstant);
4066     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4067                        DAG.getConstant(0, MVT::i32));
4068   }
4069
4070   // Finally, try a VMVN.i32
4071   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4072                              VMVNModImm);
4073   if (NewVal != SDValue()) {
4074     DebugLoc DL = Op.getDebugLoc();
4075     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4076     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4077                                        VecConstant);
4078     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4079                        DAG.getConstant(0, MVT::i32));
4080   }
4081
4082   return SDValue();
4083 }
4084
4085 // check if an VEXT instruction can handle the shuffle mask when the
4086 // vector sources of the shuffle are the same.
4087 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4088   unsigned NumElts = VT.getVectorNumElements();
4089
4090   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4091   if (M[0] < 0)
4092     return false;
4093
4094   Imm = M[0];
4095
4096   // If this is a VEXT shuffle, the immediate value is the index of the first
4097   // element.  The other shuffle indices must be the successive elements after
4098   // the first one.
4099   unsigned ExpectedElt = Imm;
4100   for (unsigned i = 1; i < NumElts; ++i) {
4101     // Increment the expected index.  If it wraps around, just follow it
4102     // back to index zero and keep going.
4103     ++ExpectedElt;
4104     if (ExpectedElt == NumElts)
4105       ExpectedElt = 0;
4106
4107     if (M[i] < 0) continue; // ignore UNDEF indices
4108     if (ExpectedElt != static_cast<unsigned>(M[i]))
4109       return false;
4110   }
4111
4112   return true;
4113 }
4114
4115
4116 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4117                        bool &ReverseVEXT, unsigned &Imm) {
4118   unsigned NumElts = VT.getVectorNumElements();
4119   ReverseVEXT = false;
4120
4121   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4122   if (M[0] < 0)
4123     return false;
4124
4125   Imm = M[0];
4126
4127   // If this is a VEXT shuffle, the immediate value is the index of the first
4128   // element.  The other shuffle indices must be the successive elements after
4129   // the first one.
4130   unsigned ExpectedElt = Imm;
4131   for (unsigned i = 1; i < NumElts; ++i) {
4132     // Increment the expected index.  If it wraps around, it may still be
4133     // a VEXT but the source vectors must be swapped.
4134     ExpectedElt += 1;
4135     if (ExpectedElt == NumElts * 2) {
4136       ExpectedElt = 0;
4137       ReverseVEXT = true;
4138     }
4139
4140     if (M[i] < 0) continue; // ignore UNDEF indices
4141     if (ExpectedElt != static_cast<unsigned>(M[i]))
4142       return false;
4143   }
4144
4145   // Adjust the index value if the source operands will be swapped.
4146   if (ReverseVEXT)
4147     Imm -= NumElts;
4148
4149   return true;
4150 }
4151
4152 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4153 /// instruction with the specified blocksize.  (The order of the elements
4154 /// within each block of the vector is reversed.)
4155 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4156   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4157          "Only possible block sizes for VREV are: 16, 32, 64");
4158
4159   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4160   if (EltSz == 64)
4161     return false;
4162
4163   unsigned NumElts = VT.getVectorNumElements();
4164   unsigned BlockElts = M[0] + 1;
4165   // If the first shuffle index is UNDEF, be optimistic.
4166   if (M[0] < 0)
4167     BlockElts = BlockSize / EltSz;
4168
4169   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4170     return false;
4171
4172   for (unsigned i = 0; i < NumElts; ++i) {
4173     if (M[i] < 0) continue; // ignore UNDEF indices
4174     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4175       return false;
4176   }
4177
4178   return true;
4179 }
4180
4181 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4182   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4183   // range, then 0 is placed into the resulting vector. So pretty much any mask
4184   // of 8 elements can work here.
4185   return VT == MVT::v8i8 && M.size() == 8;
4186 }
4187
4188 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4189   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4190   if (EltSz == 64)
4191     return false;
4192
4193   unsigned NumElts = VT.getVectorNumElements();
4194   WhichResult = (M[0] == 0 ? 0 : 1);
4195   for (unsigned i = 0; i < NumElts; i += 2) {
4196     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4197         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4198       return false;
4199   }
4200   return true;
4201 }
4202
4203 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4204 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4205 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4206 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4207   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4208   if (EltSz == 64)
4209     return false;
4210
4211   unsigned NumElts = VT.getVectorNumElements();
4212   WhichResult = (M[0] == 0 ? 0 : 1);
4213   for (unsigned i = 0; i < NumElts; i += 2) {
4214     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4215         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4216       return false;
4217   }
4218   return true;
4219 }
4220
4221 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4222   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4223   if (EltSz == 64)
4224     return false;
4225
4226   unsigned NumElts = VT.getVectorNumElements();
4227   WhichResult = (M[0] == 0 ? 0 : 1);
4228   for (unsigned i = 0; i != NumElts; ++i) {
4229     if (M[i] < 0) continue; // ignore UNDEF indices
4230     if ((unsigned) M[i] != 2 * i + WhichResult)
4231       return false;
4232   }
4233
4234   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4235   if (VT.is64BitVector() && EltSz == 32)
4236     return false;
4237
4238   return true;
4239 }
4240
4241 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4242 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4243 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4244 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4245   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4246   if (EltSz == 64)
4247     return false;
4248
4249   unsigned Half = VT.getVectorNumElements() / 2;
4250   WhichResult = (M[0] == 0 ? 0 : 1);
4251   for (unsigned j = 0; j != 2; ++j) {
4252     unsigned Idx = WhichResult;
4253     for (unsigned i = 0; i != Half; ++i) {
4254       int MIdx = M[i + j * Half];
4255       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4256         return false;
4257       Idx += 2;
4258     }
4259   }
4260
4261   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4262   if (VT.is64BitVector() && EltSz == 32)
4263     return false;
4264
4265   return true;
4266 }
4267
4268 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4269   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4270   if (EltSz == 64)
4271     return false;
4272
4273   unsigned NumElts = VT.getVectorNumElements();
4274   WhichResult = (M[0] == 0 ? 0 : 1);
4275   unsigned Idx = WhichResult * NumElts / 2;
4276   for (unsigned i = 0; i != NumElts; i += 2) {
4277     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4278         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4279       return false;
4280     Idx += 1;
4281   }
4282
4283   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4284   if (VT.is64BitVector() && EltSz == 32)
4285     return false;
4286
4287   return true;
4288 }
4289
4290 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4291 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4292 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4293 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4294   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4295   if (EltSz == 64)
4296     return false;
4297
4298   unsigned NumElts = VT.getVectorNumElements();
4299   WhichResult = (M[0] == 0 ? 0 : 1);
4300   unsigned Idx = WhichResult * NumElts / 2;
4301   for (unsigned i = 0; i != NumElts; i += 2) {
4302     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4303         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4304       return false;
4305     Idx += 1;
4306   }
4307
4308   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4309   if (VT.is64BitVector() && EltSz == 32)
4310     return false;
4311
4312   return true;
4313 }
4314
4315 // If N is an integer constant that can be moved into a register in one
4316 // instruction, return an SDValue of such a constant (will become a MOV
4317 // instruction).  Otherwise return null.
4318 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4319                                      const ARMSubtarget *ST, DebugLoc dl) {
4320   uint64_t Val;
4321   if (!isa<ConstantSDNode>(N))
4322     return SDValue();
4323   Val = cast<ConstantSDNode>(N)->getZExtValue();
4324
4325   if (ST->isThumb1Only()) {
4326     if (Val <= 255 || ~Val <= 255)
4327       return DAG.getConstant(Val, MVT::i32);
4328   } else {
4329     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4330       return DAG.getConstant(Val, MVT::i32);
4331   }
4332   return SDValue();
4333 }
4334
4335 // If this is a case we can't handle, return null and let the default
4336 // expansion code take care of it.
4337 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4338                                              const ARMSubtarget *ST) const {
4339   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4340   DebugLoc dl = Op.getDebugLoc();
4341   EVT VT = Op.getValueType();
4342
4343   APInt SplatBits, SplatUndef;
4344   unsigned SplatBitSize;
4345   bool HasAnyUndefs;
4346   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4347     if (SplatBitSize <= 64) {
4348       // Check if an immediate VMOV works.
4349       EVT VmovVT;
4350       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4351                                       SplatUndef.getZExtValue(), SplatBitSize,
4352                                       DAG, VmovVT, VT.is128BitVector(),
4353                                       VMOVModImm);
4354       if (Val.getNode()) {
4355         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4356         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4357       }
4358
4359       // Try an immediate VMVN.
4360       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4361       Val = isNEONModifiedImm(NegatedImm,
4362                                       SplatUndef.getZExtValue(), SplatBitSize,
4363                                       DAG, VmovVT, VT.is128BitVector(),
4364                                       VMVNModImm);
4365       if (Val.getNode()) {
4366         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4367         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4368       }
4369
4370       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4371       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4372         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4373         if (ImmVal != -1) {
4374           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4375           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4376         }
4377       }
4378     }
4379   }
4380
4381   // Scan through the operands to see if only one value is used.
4382   //
4383   // As an optimisation, even if more than one value is used it may be more
4384   // profitable to splat with one value then change some lanes.
4385   //
4386   // Heuristically we decide to do this if the vector has a "dominant" value,
4387   // defined as splatted to more than half of the lanes.
4388   unsigned NumElts = VT.getVectorNumElements();
4389   bool isOnlyLowElement = true;
4390   bool usesOnlyOneValue = true;
4391   bool hasDominantValue = false;
4392   bool isConstant = true;
4393
4394   // Map of the number of times a particular SDValue appears in the
4395   // element list.
4396   DenseMap<SDValue, unsigned> ValueCounts;
4397   SDValue Value;
4398   for (unsigned i = 0; i < NumElts; ++i) {
4399     SDValue V = Op.getOperand(i);
4400     if (V.getOpcode() == ISD::UNDEF)
4401       continue;
4402     if (i > 0)
4403       isOnlyLowElement = false;
4404     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4405       isConstant = false;
4406
4407     ValueCounts.insert(std::make_pair(V, 0));
4408     unsigned &Count = ValueCounts[V];
4409     
4410     // Is this value dominant? (takes up more than half of the lanes)
4411     if (++Count > (NumElts / 2)) {
4412       hasDominantValue = true;
4413       Value = V;
4414     }
4415   }
4416   if (ValueCounts.size() != 1)
4417     usesOnlyOneValue = false;
4418   if (!Value.getNode() && ValueCounts.size() > 0)
4419     Value = ValueCounts.begin()->first;
4420
4421   if (ValueCounts.size() == 0)
4422     return DAG.getUNDEF(VT);
4423
4424   if (isOnlyLowElement)
4425     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4426
4427   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4428
4429   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4430   // i32 and try again.
4431   if (hasDominantValue && EltSize <= 32) {
4432     if (!isConstant) {
4433       SDValue N;
4434
4435       // If we are VDUPing a value that comes directly from a vector, that will
4436       // cause an unnecessary move to and from a GPR, where instead we could
4437       // just use VDUPLANE.
4438       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4439         // We need to create a new undef vector to use for the VDUPLANE if the
4440         // size of the vector from which we get the value is different than the
4441         // size of the vector that we need to create. We will insert the element
4442         // such that the register coalescer will remove unnecessary copies.
4443         if (VT != Value->getOperand(0).getValueType()) {
4444           ConstantSDNode *constIndex;
4445           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4446           assert(constIndex && "The index is not a constant!");
4447           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4448                              VT.getVectorNumElements();
4449           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4450                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4451                         Value, DAG.getConstant(index, MVT::i32)),
4452                            DAG.getConstant(index, MVT::i32));
4453         } else {
4454           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4455                         Value->getOperand(0), Value->getOperand(1));
4456         }
4457       }
4458       else
4459         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4460
4461       if (!usesOnlyOneValue) {
4462         // The dominant value was splatted as 'N', but we now have to insert
4463         // all differing elements.
4464         for (unsigned I = 0; I < NumElts; ++I) {
4465           if (Op.getOperand(I) == Value)
4466             continue;
4467           SmallVector<SDValue, 3> Ops;
4468           Ops.push_back(N);
4469           Ops.push_back(Op.getOperand(I));
4470           Ops.push_back(DAG.getConstant(I, MVT::i32));
4471           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4472         }
4473       }
4474       return N;
4475     }
4476     if (VT.getVectorElementType().isFloatingPoint()) {
4477       SmallVector<SDValue, 8> Ops;
4478       for (unsigned i = 0; i < NumElts; ++i)
4479         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4480                                   Op.getOperand(i)));
4481       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4482       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4483       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4484       if (Val.getNode())
4485         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4486     }
4487     if (usesOnlyOneValue) {
4488       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4489       if (isConstant && Val.getNode())
4490         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4491     }
4492   }
4493
4494   // If all elements are constants and the case above didn't get hit, fall back
4495   // to the default expansion, which will generate a load from the constant
4496   // pool.
4497   if (isConstant)
4498     return SDValue();
4499
4500   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4501   if (NumElts >= 4) {
4502     SDValue shuffle = ReconstructShuffle(Op, DAG);
4503     if (shuffle != SDValue())
4504       return shuffle;
4505   }
4506
4507   // Vectors with 32- or 64-bit elements can be built by directly assigning
4508   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4509   // will be legalized.
4510   if (EltSize >= 32) {
4511     // Do the expansion with floating-point types, since that is what the VFP
4512     // registers are defined to use, and since i64 is not legal.
4513     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4514     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4515     SmallVector<SDValue, 8> Ops;
4516     for (unsigned i = 0; i < NumElts; ++i)
4517       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4518     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4519     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4520   }
4521
4522   return SDValue();
4523 }
4524
4525 // Gather data to see if the operation can be modelled as a
4526 // shuffle in combination with VEXTs.
4527 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4528                                               SelectionDAG &DAG) const {
4529   DebugLoc dl = Op.getDebugLoc();
4530   EVT VT = Op.getValueType();
4531   unsigned NumElts = VT.getVectorNumElements();
4532
4533   SmallVector<SDValue, 2> SourceVecs;
4534   SmallVector<unsigned, 2> MinElts;
4535   SmallVector<unsigned, 2> MaxElts;
4536
4537   for (unsigned i = 0; i < NumElts; ++i) {
4538     SDValue V = Op.getOperand(i);
4539     if (V.getOpcode() == ISD::UNDEF)
4540       continue;
4541     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4542       // A shuffle can only come from building a vector from various
4543       // elements of other vectors.
4544       return SDValue();
4545     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4546                VT.getVectorElementType()) {
4547       // This code doesn't know how to handle shuffles where the vector
4548       // element types do not match (this happens because type legalization
4549       // promotes the return type of EXTRACT_VECTOR_ELT).
4550       // FIXME: It might be appropriate to extend this code to handle
4551       // mismatched types.
4552       return SDValue();
4553     }
4554
4555     // Record this extraction against the appropriate vector if possible...
4556     SDValue SourceVec = V.getOperand(0);
4557     // If the element number isn't a constant, we can't effectively
4558     // analyze what's going on.
4559     if (!isa<ConstantSDNode>(V.getOperand(1)))
4560       return SDValue();
4561     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4562     bool FoundSource = false;
4563     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4564       if (SourceVecs[j] == SourceVec) {
4565         if (MinElts[j] > EltNo)
4566           MinElts[j] = EltNo;
4567         if (MaxElts[j] < EltNo)
4568           MaxElts[j] = EltNo;
4569         FoundSource = true;
4570         break;
4571       }
4572     }
4573
4574     // Or record a new source if not...
4575     if (!FoundSource) {
4576       SourceVecs.push_back(SourceVec);
4577       MinElts.push_back(EltNo);
4578       MaxElts.push_back(EltNo);
4579     }
4580   }
4581
4582   // Currently only do something sane when at most two source vectors
4583   // involved.
4584   if (SourceVecs.size() > 2)
4585     return SDValue();
4586
4587   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4588   int VEXTOffsets[2] = {0, 0};
4589
4590   // This loop extracts the usage patterns of the source vectors
4591   // and prepares appropriate SDValues for a shuffle if possible.
4592   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4593     if (SourceVecs[i].getValueType() == VT) {
4594       // No VEXT necessary
4595       ShuffleSrcs[i] = SourceVecs[i];
4596       VEXTOffsets[i] = 0;
4597       continue;
4598     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4599       // It probably isn't worth padding out a smaller vector just to
4600       // break it down again in a shuffle.
4601       return SDValue();
4602     }
4603
4604     // Since only 64-bit and 128-bit vectors are legal on ARM and
4605     // we've eliminated the other cases...
4606     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4607            "unexpected vector sizes in ReconstructShuffle");
4608
4609     if (MaxElts[i] - MinElts[i] >= NumElts) {
4610       // Span too large for a VEXT to cope
4611       return SDValue();
4612     }
4613
4614     if (MinElts[i] >= NumElts) {
4615       // The extraction can just take the second half
4616       VEXTOffsets[i] = NumElts;
4617       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4618                                    SourceVecs[i],
4619                                    DAG.getIntPtrConstant(NumElts));
4620     } else if (MaxElts[i] < NumElts) {
4621       // The extraction can just take the first half
4622       VEXTOffsets[i] = 0;
4623       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4624                                    SourceVecs[i],
4625                                    DAG.getIntPtrConstant(0));
4626     } else {
4627       // An actual VEXT is needed
4628       VEXTOffsets[i] = MinElts[i];
4629       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4630                                      SourceVecs[i],
4631                                      DAG.getIntPtrConstant(0));
4632       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4633                                      SourceVecs[i],
4634                                      DAG.getIntPtrConstant(NumElts));
4635       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4636                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4637     }
4638   }
4639
4640   SmallVector<int, 8> Mask;
4641
4642   for (unsigned i = 0; i < NumElts; ++i) {
4643     SDValue Entry = Op.getOperand(i);
4644     if (Entry.getOpcode() == ISD::UNDEF) {
4645       Mask.push_back(-1);
4646       continue;
4647     }
4648
4649     SDValue ExtractVec = Entry.getOperand(0);
4650     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4651                                           .getOperand(1))->getSExtValue();
4652     if (ExtractVec == SourceVecs[0]) {
4653       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4654     } else {
4655       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4656     }
4657   }
4658
4659   // Final check before we try to produce nonsense...
4660   if (isShuffleMaskLegal(Mask, VT))
4661     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4662                                 &Mask[0]);
4663
4664   return SDValue();
4665 }
4666
4667 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4668 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4669 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4670 /// are assumed to be legal.
4671 bool
4672 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4673                                       EVT VT) const {
4674   if (VT.getVectorNumElements() == 4 &&
4675       (VT.is128BitVector() || VT.is64BitVector())) {
4676     unsigned PFIndexes[4];
4677     for (unsigned i = 0; i != 4; ++i) {
4678       if (M[i] < 0)
4679         PFIndexes[i] = 8;
4680       else
4681         PFIndexes[i] = M[i];
4682     }
4683
4684     // Compute the index in the perfect shuffle table.
4685     unsigned PFTableIndex =
4686       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4687     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4688     unsigned Cost = (PFEntry >> 30);
4689
4690     if (Cost <= 4)
4691       return true;
4692   }
4693
4694   bool ReverseVEXT;
4695   unsigned Imm, WhichResult;
4696
4697   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4698   return (EltSize >= 32 ||
4699           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4700           isVREVMask(M, VT, 64) ||
4701           isVREVMask(M, VT, 32) ||
4702           isVREVMask(M, VT, 16) ||
4703           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4704           isVTBLMask(M, VT) ||
4705           isVTRNMask(M, VT, WhichResult) ||
4706           isVUZPMask(M, VT, WhichResult) ||
4707           isVZIPMask(M, VT, WhichResult) ||
4708           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4709           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4710           isVZIP_v_undef_Mask(M, VT, WhichResult));
4711 }
4712
4713 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4714 /// the specified operations to build the shuffle.
4715 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4716                                       SDValue RHS, SelectionDAG &DAG,
4717                                       DebugLoc dl) {
4718   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4719   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4720   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4721
4722   enum {
4723     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4724     OP_VREV,
4725     OP_VDUP0,
4726     OP_VDUP1,
4727     OP_VDUP2,
4728     OP_VDUP3,
4729     OP_VEXT1,
4730     OP_VEXT2,
4731     OP_VEXT3,
4732     OP_VUZPL, // VUZP, left result
4733     OP_VUZPR, // VUZP, right result
4734     OP_VZIPL, // VZIP, left result
4735     OP_VZIPR, // VZIP, right result
4736     OP_VTRNL, // VTRN, left result
4737     OP_VTRNR  // VTRN, right result
4738   };
4739
4740   if (OpNum == OP_COPY) {
4741     if (LHSID == (1*9+2)*9+3) return LHS;
4742     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4743     return RHS;
4744   }
4745
4746   SDValue OpLHS, OpRHS;
4747   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4748   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4749   EVT VT = OpLHS.getValueType();
4750
4751   switch (OpNum) {
4752   default: llvm_unreachable("Unknown shuffle opcode!");
4753   case OP_VREV:
4754     // VREV divides the vector in half and swaps within the half.
4755     if (VT.getVectorElementType() == MVT::i32 ||
4756         VT.getVectorElementType() == MVT::f32)
4757       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4758     // vrev <4 x i16> -> VREV32
4759     if (VT.getVectorElementType() == MVT::i16)
4760       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4761     // vrev <4 x i8> -> VREV16
4762     assert(VT.getVectorElementType() == MVT::i8);
4763     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4764   case OP_VDUP0:
4765   case OP_VDUP1:
4766   case OP_VDUP2:
4767   case OP_VDUP3:
4768     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4769                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4770   case OP_VEXT1:
4771   case OP_VEXT2:
4772   case OP_VEXT3:
4773     return DAG.getNode(ARMISD::VEXT, dl, VT,
4774                        OpLHS, OpRHS,
4775                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4776   case OP_VUZPL:
4777   case OP_VUZPR:
4778     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4779                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4780   case OP_VZIPL:
4781   case OP_VZIPR:
4782     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4783                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4784   case OP_VTRNL:
4785   case OP_VTRNR:
4786     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4787                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4788   }
4789 }
4790
4791 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4792                                        ArrayRef<int> ShuffleMask,
4793                                        SelectionDAG &DAG) {
4794   // Check to see if we can use the VTBL instruction.
4795   SDValue V1 = Op.getOperand(0);
4796   SDValue V2 = Op.getOperand(1);
4797   DebugLoc DL = Op.getDebugLoc();
4798
4799   SmallVector<SDValue, 8> VTBLMask;
4800   for (ArrayRef<int>::iterator
4801          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4802     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4803
4804   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4805     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4806                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4807                                    &VTBLMask[0], 8));
4808
4809   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4810                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4811                                  &VTBLMask[0], 8));
4812 }
4813
4814 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4815   SDValue V1 = Op.getOperand(0);
4816   SDValue V2 = Op.getOperand(1);
4817   DebugLoc dl = Op.getDebugLoc();
4818   EVT VT = Op.getValueType();
4819   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4820
4821   // Convert shuffles that are directly supported on NEON to target-specific
4822   // DAG nodes, instead of keeping them as shuffles and matching them again
4823   // during code selection.  This is more efficient and avoids the possibility
4824   // of inconsistencies between legalization and selection.
4825   // FIXME: floating-point vectors should be canonicalized to integer vectors
4826   // of the same time so that they get CSEd properly.
4827   ArrayRef<int> ShuffleMask = SVN->getMask();
4828
4829   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4830   if (EltSize <= 32) {
4831     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4832       int Lane = SVN->getSplatIndex();
4833       // If this is undef splat, generate it via "just" vdup, if possible.
4834       if (Lane == -1) Lane = 0;
4835
4836       // Test if V1 is a SCALAR_TO_VECTOR.
4837       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4838         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4839       }
4840       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4841       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4842       // reaches it).
4843       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4844           !isa<ConstantSDNode>(V1.getOperand(0))) {
4845         bool IsScalarToVector = true;
4846         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4847           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4848             IsScalarToVector = false;
4849             break;
4850           }
4851         if (IsScalarToVector)
4852           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4853       }
4854       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4855                          DAG.getConstant(Lane, MVT::i32));
4856     }
4857
4858     bool ReverseVEXT;
4859     unsigned Imm;
4860     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4861       if (ReverseVEXT)
4862         std::swap(V1, V2);
4863       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4864                          DAG.getConstant(Imm, MVT::i32));
4865     }
4866
4867     if (isVREVMask(ShuffleMask, VT, 64))
4868       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4869     if (isVREVMask(ShuffleMask, VT, 32))
4870       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4871     if (isVREVMask(ShuffleMask, VT, 16))
4872       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4873
4874     if (V2->getOpcode() == ISD::UNDEF &&
4875         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4876       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4877                          DAG.getConstant(Imm, MVT::i32));
4878     }
4879
4880     // Check for Neon shuffles that modify both input vectors in place.
4881     // If both results are used, i.e., if there are two shuffles with the same
4882     // source operands and with masks corresponding to both results of one of
4883     // these operations, DAG memoization will ensure that a single node is
4884     // used for both shuffles.
4885     unsigned WhichResult;
4886     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4887       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4888                          V1, V2).getValue(WhichResult);
4889     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4890       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4891                          V1, V2).getValue(WhichResult);
4892     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4893       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4894                          V1, V2).getValue(WhichResult);
4895
4896     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4897       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4898                          V1, V1).getValue(WhichResult);
4899     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4900       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4901                          V1, V1).getValue(WhichResult);
4902     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4903       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4904                          V1, V1).getValue(WhichResult);
4905   }
4906
4907   // If the shuffle is not directly supported and it has 4 elements, use
4908   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4909   unsigned NumElts = VT.getVectorNumElements();
4910   if (NumElts == 4) {
4911     unsigned PFIndexes[4];
4912     for (unsigned i = 0; i != 4; ++i) {
4913       if (ShuffleMask[i] < 0)
4914         PFIndexes[i] = 8;
4915       else
4916         PFIndexes[i] = ShuffleMask[i];
4917     }
4918
4919     // Compute the index in the perfect shuffle table.
4920     unsigned PFTableIndex =
4921       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4922     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4923     unsigned Cost = (PFEntry >> 30);
4924
4925     if (Cost <= 4)
4926       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4927   }
4928
4929   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4930   if (EltSize >= 32) {
4931     // Do the expansion with floating-point types, since that is what the VFP
4932     // registers are defined to use, and since i64 is not legal.
4933     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4934     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4935     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4936     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4937     SmallVector<SDValue, 8> Ops;
4938     for (unsigned i = 0; i < NumElts; ++i) {
4939       if (ShuffleMask[i] < 0)
4940         Ops.push_back(DAG.getUNDEF(EltVT));
4941       else
4942         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4943                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4944                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4945                                                   MVT::i32)));
4946     }
4947     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4948     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4949   }
4950
4951   if (VT == MVT::v8i8) {
4952     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4953     if (NewOp.getNode())
4954       return NewOp;
4955   }
4956
4957   return SDValue();
4958 }
4959
4960 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4961   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4962   SDValue Lane = Op.getOperand(2);
4963   if (!isa<ConstantSDNode>(Lane))
4964     return SDValue();
4965
4966   return Op;
4967 }
4968
4969 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4970   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4971   SDValue Lane = Op.getOperand(1);
4972   if (!isa<ConstantSDNode>(Lane))
4973     return SDValue();
4974
4975   SDValue Vec = Op.getOperand(0);
4976   if (Op.getValueType() == MVT::i32 &&
4977       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4978     DebugLoc dl = Op.getDebugLoc();
4979     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4980   }
4981
4982   return Op;
4983 }
4984
4985 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4986   // The only time a CONCAT_VECTORS operation can have legal types is when
4987   // two 64-bit vectors are concatenated to a 128-bit vector.
4988   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4989          "unexpected CONCAT_VECTORS");
4990   DebugLoc dl = Op.getDebugLoc();
4991   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4992   SDValue Op0 = Op.getOperand(0);
4993   SDValue Op1 = Op.getOperand(1);
4994   if (Op0.getOpcode() != ISD::UNDEF)
4995     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4996                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4997                       DAG.getIntPtrConstant(0));
4998   if (Op1.getOpcode() != ISD::UNDEF)
4999     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5000                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5001                       DAG.getIntPtrConstant(1));
5002   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5003 }
5004
5005 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5006 /// element has been zero/sign-extended, depending on the isSigned parameter,
5007 /// from an integer type half its size.
5008 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5009                                    bool isSigned) {
5010   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5011   EVT VT = N->getValueType(0);
5012   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5013     SDNode *BVN = N->getOperand(0).getNode();
5014     if (BVN->getValueType(0) != MVT::v4i32 ||
5015         BVN->getOpcode() != ISD::BUILD_VECTOR)
5016       return false;
5017     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5018     unsigned HiElt = 1 - LoElt;
5019     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5020     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5021     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5022     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5023     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5024       return false;
5025     if (isSigned) {
5026       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5027           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5028         return true;
5029     } else {
5030       if (Hi0->isNullValue() && Hi1->isNullValue())
5031         return true;
5032     }
5033     return false;
5034   }
5035
5036   if (N->getOpcode() != ISD::BUILD_VECTOR)
5037     return false;
5038
5039   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5040     SDNode *Elt = N->getOperand(i).getNode();
5041     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5042       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5043       unsigned HalfSize = EltSize / 2;
5044       if (isSigned) {
5045         if (!isIntN(HalfSize, C->getSExtValue()))
5046           return false;
5047       } else {
5048         if (!isUIntN(HalfSize, C->getZExtValue()))
5049           return false;
5050       }
5051       continue;
5052     }
5053     return false;
5054   }
5055
5056   return true;
5057 }
5058
5059 /// isSignExtended - Check if a node is a vector value that is sign-extended
5060 /// or a constant BUILD_VECTOR with sign-extended elements.
5061 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5062   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5063     return true;
5064   if (isExtendedBUILD_VECTOR(N, DAG, true))
5065     return true;
5066   return false;
5067 }
5068
5069 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5070 /// or a constant BUILD_VECTOR with zero-extended elements.
5071 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5072   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5073     return true;
5074   if (isExtendedBUILD_VECTOR(N, DAG, false))
5075     return true;
5076   return false;
5077 }
5078
5079 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5080 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5081 /// We insert the required extension here to get the vector to fill a D register.
5082 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5083                                             const EVT &OrigTy,
5084                                             const EVT &ExtTy,
5085                                             unsigned ExtOpcode) {
5086   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5087   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5088   // 64-bits we need to insert a new extension so that it will be 64-bits.
5089   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5090   if (OrigTy.getSizeInBits() >= 64)
5091     return N;
5092
5093   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5094   MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5095   EVT NewVT;
5096   switch (OrigSimpleTy) {
5097   default: llvm_unreachable("Unexpected Orig Vector Type");
5098   case MVT::v2i8:
5099   case MVT::v2i16:
5100     NewVT = MVT::v2i32;
5101     break;
5102   case MVT::v4i8:
5103     NewVT = MVT::v4i16;
5104     break;
5105   }
5106   return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5107 }
5108
5109 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5110 /// does not do any sign/zero extension. If the original vector is less
5111 /// than 64 bits, an appropriate extension will be added after the load to
5112 /// reach a total size of 64 bits. We have to add the extension separately
5113 /// because ARM does not have a sign/zero extending load for vectors.
5114 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5115   SDValue NonExtendingLoad =
5116     DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5117                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5118                 LD->isNonTemporal(), LD->isInvariant(),
5119                 LD->getAlignment());
5120   unsigned ExtOp = 0;
5121   switch (LD->getExtensionType()) {
5122   default: llvm_unreachable("Unexpected LoadExtType");
5123   case ISD::EXTLOAD:
5124   case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5125   case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5126   }
5127   MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5128   MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5129   return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5130                                       MemType, ExtType, ExtOp);
5131 }
5132
5133 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5134 /// extending load, or BUILD_VECTOR with extended elements, return the
5135 /// unextended value. The unextended vector should be 64 bits so that it can
5136 /// be used as an operand to a VMULL instruction. If the original vector size
5137 /// before extension is less than 64 bits we add a an extension to resize
5138 /// the vector to 64 bits.
5139 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5140   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5141     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5142                                         N->getOperand(0)->getValueType(0),
5143                                         N->getValueType(0),
5144                                         N->getOpcode());
5145
5146   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5147     return SkipLoadExtensionForVMULL(LD, DAG);
5148
5149   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5150   // have been legalized as a BITCAST from v4i32.
5151   if (N->getOpcode() == ISD::BITCAST) {
5152     SDNode *BVN = N->getOperand(0).getNode();
5153     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5154            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5155     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5156     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5157                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5158   }
5159   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5160   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5161   EVT VT = N->getValueType(0);
5162   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5163   unsigned NumElts = VT.getVectorNumElements();
5164   MVT TruncVT = MVT::getIntegerVT(EltSize);
5165   SmallVector<SDValue, 8> Ops;
5166   for (unsigned i = 0; i != NumElts; ++i) {
5167     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5168     const APInt &CInt = C->getAPIntValue();
5169     // Element types smaller than 32 bits are not legal, so use i32 elements.
5170     // The values are implicitly truncated so sext vs. zext doesn't matter.
5171     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5172   }
5173   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5174                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5175 }
5176
5177 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5178   unsigned Opcode = N->getOpcode();
5179   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5180     SDNode *N0 = N->getOperand(0).getNode();
5181     SDNode *N1 = N->getOperand(1).getNode();
5182     return N0->hasOneUse() && N1->hasOneUse() &&
5183       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5184   }
5185   return false;
5186 }
5187
5188 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5189   unsigned Opcode = N->getOpcode();
5190   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5191     SDNode *N0 = N->getOperand(0).getNode();
5192     SDNode *N1 = N->getOperand(1).getNode();
5193     return N0->hasOneUse() && N1->hasOneUse() &&
5194       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5195   }
5196   return false;
5197 }
5198
5199 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5200   // Multiplications are only custom-lowered for 128-bit vectors so that
5201   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5202   EVT VT = Op.getValueType();
5203   assert(VT.is128BitVector() && VT.isInteger() &&
5204          "unexpected type for custom-lowering ISD::MUL");
5205   SDNode *N0 = Op.getOperand(0).getNode();
5206   SDNode *N1 = Op.getOperand(1).getNode();
5207   unsigned NewOpc = 0;
5208   bool isMLA = false;
5209   bool isN0SExt = isSignExtended(N0, DAG);
5210   bool isN1SExt = isSignExtended(N1, DAG);
5211   if (isN0SExt && isN1SExt)
5212     NewOpc = ARMISD::VMULLs;
5213   else {
5214     bool isN0ZExt = isZeroExtended(N0, DAG);
5215     bool isN1ZExt = isZeroExtended(N1, DAG);
5216     if (isN0ZExt && isN1ZExt)
5217       NewOpc = ARMISD::VMULLu;
5218     else if (isN1SExt || isN1ZExt) {
5219       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5220       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5221       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5222         NewOpc = ARMISD::VMULLs;
5223         isMLA = true;
5224       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5225         NewOpc = ARMISD::VMULLu;
5226         isMLA = true;
5227       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5228         std::swap(N0, N1);
5229         NewOpc = ARMISD::VMULLu;
5230         isMLA = true;
5231       }
5232     }
5233
5234     if (!NewOpc) {
5235       if (VT == MVT::v2i64)
5236         // Fall through to expand this.  It is not legal.
5237         return SDValue();
5238       else
5239         // Other vector multiplications are legal.
5240         return Op;
5241     }
5242   }
5243
5244   // Legalize to a VMULL instruction.
5245   DebugLoc DL = Op.getDebugLoc();
5246   SDValue Op0;
5247   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5248   if (!isMLA) {
5249     Op0 = SkipExtensionForVMULL(N0, DAG);
5250     assert(Op0.getValueType().is64BitVector() &&
5251            Op1.getValueType().is64BitVector() &&
5252            "unexpected types for extended operands to VMULL");
5253     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5254   }
5255
5256   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5257   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5258   //   vmull q0, d4, d6
5259   //   vmlal q0, d5, d6
5260   // is faster than
5261   //   vaddl q0, d4, d5
5262   //   vmovl q1, d6
5263   //   vmul  q0, q0, q1
5264   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5265   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5266   EVT Op1VT = Op1.getValueType();
5267   return DAG.getNode(N0->getOpcode(), DL, VT,
5268                      DAG.getNode(NewOpc, DL, VT,
5269                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5270                      DAG.getNode(NewOpc, DL, VT,
5271                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5272 }
5273
5274 static SDValue
5275 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5276   // Convert to float
5277   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5278   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5279   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5280   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5281   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5282   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5283   // Get reciprocal estimate.
5284   // float4 recip = vrecpeq_f32(yf);
5285   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5286                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5287   // Because char has a smaller range than uchar, we can actually get away
5288   // without any newton steps.  This requires that we use a weird bias
5289   // of 0xb000, however (again, this has been exhaustively tested).
5290   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5291   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5292   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5293   Y = DAG.getConstant(0xb000, MVT::i32);
5294   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5295   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5296   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5297   // Convert back to short.
5298   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5299   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5300   return X;
5301 }
5302
5303 static SDValue
5304 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5305   SDValue N2;
5306   // Convert to float.
5307   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5308   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5309   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5310   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5311   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5312   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5313
5314   // Use reciprocal estimate and one refinement step.
5315   // float4 recip = vrecpeq_f32(yf);
5316   // recip *= vrecpsq_f32(yf, recip);
5317   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5318                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5319   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5320                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5321                    N1, N2);
5322   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5323   // Because short has a smaller range than ushort, we can actually get away
5324   // with only a single newton step.  This requires that we use a weird bias
5325   // of 89, however (again, this has been exhaustively tested).
5326   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5327   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5328   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5329   N1 = DAG.getConstant(0x89, MVT::i32);
5330   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5331   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5332   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5333   // Convert back to integer and return.
5334   // return vmovn_s32(vcvt_s32_f32(result));
5335   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5336   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5337   return N0;
5338 }
5339
5340 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5341   EVT VT = Op.getValueType();
5342   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5343          "unexpected type for custom-lowering ISD::SDIV");
5344
5345   DebugLoc dl = Op.getDebugLoc();
5346   SDValue N0 = Op.getOperand(0);
5347   SDValue N1 = Op.getOperand(1);
5348   SDValue N2, N3;
5349
5350   if (VT == MVT::v8i8) {
5351     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5352     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5353
5354     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5355                      DAG.getIntPtrConstant(4));
5356     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5357                      DAG.getIntPtrConstant(4));
5358     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5359                      DAG.getIntPtrConstant(0));
5360     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5361                      DAG.getIntPtrConstant(0));
5362
5363     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5364     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5365
5366     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5367     N0 = LowerCONCAT_VECTORS(N0, DAG);
5368
5369     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5370     return N0;
5371   }
5372   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5373 }
5374
5375 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5376   EVT VT = Op.getValueType();
5377   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5378          "unexpected type for custom-lowering ISD::UDIV");
5379
5380   DebugLoc dl = Op.getDebugLoc();
5381   SDValue N0 = Op.getOperand(0);
5382   SDValue N1 = Op.getOperand(1);
5383   SDValue N2, N3;
5384
5385   if (VT == MVT::v8i8) {
5386     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5387     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5388
5389     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5390                      DAG.getIntPtrConstant(4));
5391     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5392                      DAG.getIntPtrConstant(4));
5393     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5394                      DAG.getIntPtrConstant(0));
5395     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5396                      DAG.getIntPtrConstant(0));
5397
5398     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5399     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5400
5401     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5402     N0 = LowerCONCAT_VECTORS(N0, DAG);
5403
5404     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5405                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5406                      N0);
5407     return N0;
5408   }
5409
5410   // v4i16 sdiv ... Convert to float.
5411   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5412   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5413   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5414   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5415   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5416   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5417
5418   // Use reciprocal estimate and two refinement steps.
5419   // float4 recip = vrecpeq_f32(yf);
5420   // recip *= vrecpsq_f32(yf, recip);
5421   // recip *= vrecpsq_f32(yf, recip);
5422   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5423                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5424   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5425                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5426                    BN1, N2);
5427   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5428   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5429                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5430                    BN1, N2);
5431   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5432   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5433   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5434   // and that it will never cause us to return an answer too large).
5435   // float4 result = as_float4(as_int4(xf*recip) + 2);
5436   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5437   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5438   N1 = DAG.getConstant(2, MVT::i32);
5439   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5440   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5441   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5442   // Convert back to integer and return.
5443   // return vmovn_u32(vcvt_s32_f32(result));
5444   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5445   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5446   return N0;
5447 }
5448
5449 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5450   EVT VT = Op.getNode()->getValueType(0);
5451   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5452
5453   unsigned Opc;
5454   bool ExtraOp = false;
5455   switch (Op.getOpcode()) {
5456   default: llvm_unreachable("Invalid code");
5457   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5458   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5459   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5460   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5461   }
5462
5463   if (!ExtraOp)
5464     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5465                        Op.getOperand(1));
5466   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5467                      Op.getOperand(1), Op.getOperand(2));
5468 }
5469
5470 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5471   // Monotonic load/store is legal for all targets
5472   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5473     return Op;
5474
5475   // Aquire/Release load/store is not legal for targets without a
5476   // dmb or equivalent available.
5477   return SDValue();
5478 }
5479
5480
5481 static void
5482 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5483                     SelectionDAG &DAG, unsigned NewOp) {
5484   DebugLoc dl = Node->getDebugLoc();
5485   assert (Node->getValueType(0) == MVT::i64 &&
5486           "Only know how to expand i64 atomics");
5487
5488   SmallVector<SDValue, 6> Ops;
5489   Ops.push_back(Node->getOperand(0)); // Chain
5490   Ops.push_back(Node->getOperand(1)); // Ptr
5491   // Low part of Val1
5492   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5493                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5494   // High part of Val1
5495   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5496                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5497   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5498     // High part of Val1
5499     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5500                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5501     // High part of Val2
5502     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5503                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5504   }
5505   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5506   SDValue Result =
5507     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5508                             cast<MemSDNode>(Node)->getMemOperand());
5509   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5510   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5511   Results.push_back(Result.getValue(2));
5512 }
5513
5514 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5515   switch (Op.getOpcode()) {
5516   default: llvm_unreachable("Don't know how to custom lower this!");
5517   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5518   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5519   case ISD::GlobalAddress:
5520     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5521       LowerGlobalAddressELF(Op, DAG);
5522   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5523   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5524   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5525   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5526   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5527   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5528   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5529   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5530   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5531   case ISD::SINT_TO_FP:
5532   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5533   case ISD::FP_TO_SINT:
5534   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5535   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5536   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5537   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5538   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5539   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5540   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5541   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5542                                                                Subtarget);
5543   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5544   case ISD::SHL:
5545   case ISD::SRL:
5546   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5547   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5548   case ISD::SRL_PARTS:
5549   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5550   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5551   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5552   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5553   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5554   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5555   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5556   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5557   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5558   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5559   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5560   case ISD::MUL:           return LowerMUL(Op, DAG);
5561   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5562   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5563   case ISD::ADDC:
5564   case ISD::ADDE:
5565   case ISD::SUBC:
5566   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5567   case ISD::ATOMIC_LOAD:
5568   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5569   }
5570 }
5571
5572 /// ReplaceNodeResults - Replace the results of node with an illegal result
5573 /// type with new values built out of custom code.
5574 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5575                                            SmallVectorImpl<SDValue>&Results,
5576                                            SelectionDAG &DAG) const {
5577   SDValue Res;
5578   switch (N->getOpcode()) {
5579   default:
5580     llvm_unreachable("Don't know how to custom expand this!");
5581   case ISD::BITCAST:
5582     Res = ExpandBITCAST(N, DAG);
5583     break;
5584   case ISD::SRL:
5585   case ISD::SRA:
5586     Res = Expand64BitShift(N, DAG, Subtarget);
5587     break;
5588   case ISD::ATOMIC_LOAD_ADD:
5589     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5590     return;
5591   case ISD::ATOMIC_LOAD_AND:
5592     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5593     return;
5594   case ISD::ATOMIC_LOAD_NAND:
5595     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5596     return;
5597   case ISD::ATOMIC_LOAD_OR:
5598     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5599     return;
5600   case ISD::ATOMIC_LOAD_SUB:
5601     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5602     return;
5603   case ISD::ATOMIC_LOAD_XOR:
5604     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5605     return;
5606   case ISD::ATOMIC_SWAP:
5607     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5608     return;
5609   case ISD::ATOMIC_CMP_SWAP:
5610     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5611     return;
5612   case ISD::ATOMIC_LOAD_MIN:
5613     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5614     return;
5615   case ISD::ATOMIC_LOAD_UMIN:
5616     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5617     return;
5618   case ISD::ATOMIC_LOAD_MAX:
5619     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5620     return;
5621   case ISD::ATOMIC_LOAD_UMAX:
5622     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5623     return;
5624   }
5625   if (Res.getNode())
5626     Results.push_back(Res);
5627 }
5628
5629 //===----------------------------------------------------------------------===//
5630 //                           ARM Scheduler Hooks
5631 //===----------------------------------------------------------------------===//
5632
5633 MachineBasicBlock *
5634 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5635                                      MachineBasicBlock *BB,
5636                                      unsigned Size) const {
5637   unsigned dest    = MI->getOperand(0).getReg();
5638   unsigned ptr     = MI->getOperand(1).getReg();
5639   unsigned oldval  = MI->getOperand(2).getReg();
5640   unsigned newval  = MI->getOperand(3).getReg();
5641   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5642   DebugLoc dl = MI->getDebugLoc();
5643   bool isThumb2 = Subtarget->isThumb2();
5644
5645   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5646   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5647     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5648     (const TargetRegisterClass*)&ARM::GPRRegClass);
5649
5650   if (isThumb2) {
5651     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5652     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5653     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5654   }
5655
5656   unsigned ldrOpc, strOpc;
5657   switch (Size) {
5658   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5659   case 1:
5660     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5661     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5662     break;
5663   case 2:
5664     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5665     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5666     break;
5667   case 4:
5668     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5669     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5670     break;
5671   }
5672
5673   MachineFunction *MF = BB->getParent();
5674   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5675   MachineFunction::iterator It = BB;
5676   ++It; // insert the new blocks after the current block
5677
5678   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5679   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5680   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5681   MF->insert(It, loop1MBB);
5682   MF->insert(It, loop2MBB);
5683   MF->insert(It, exitMBB);
5684
5685   // Transfer the remainder of BB and its successor edges to exitMBB.
5686   exitMBB->splice(exitMBB->begin(), BB,
5687                   llvm::next(MachineBasicBlock::iterator(MI)),
5688                   BB->end());
5689   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5690
5691   //  thisMBB:
5692   //   ...
5693   //   fallthrough --> loop1MBB
5694   BB->addSuccessor(loop1MBB);
5695
5696   // loop1MBB:
5697   //   ldrex dest, [ptr]
5698   //   cmp dest, oldval
5699   //   bne exitMBB
5700   BB = loop1MBB;
5701   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5702   if (ldrOpc == ARM::t2LDREX)
5703     MIB.addImm(0);
5704   AddDefaultPred(MIB);
5705   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5706                  .addReg(dest).addReg(oldval));
5707   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5708     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5709   BB->addSuccessor(loop2MBB);
5710   BB->addSuccessor(exitMBB);
5711
5712   // loop2MBB:
5713   //   strex scratch, newval, [ptr]
5714   //   cmp scratch, #0
5715   //   bne loop1MBB
5716   BB = loop2MBB;
5717   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5718   if (strOpc == ARM::t2STREX)
5719     MIB.addImm(0);
5720   AddDefaultPred(MIB);
5721   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5722                  .addReg(scratch).addImm(0));
5723   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5724     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5725   BB->addSuccessor(loop1MBB);
5726   BB->addSuccessor(exitMBB);
5727
5728   //  exitMBB:
5729   //   ...
5730   BB = exitMBB;
5731
5732   MI->eraseFromParent();   // The instruction is gone now.
5733
5734   return BB;
5735 }
5736
5737 MachineBasicBlock *
5738 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5739                                     unsigned Size, unsigned BinOpcode) const {
5740   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5741   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5742
5743   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5744   MachineFunction *MF = BB->getParent();
5745   MachineFunction::iterator It = BB;
5746   ++It;
5747
5748   unsigned dest = MI->getOperand(0).getReg();
5749   unsigned ptr = MI->getOperand(1).getReg();
5750   unsigned incr = MI->getOperand(2).getReg();
5751   DebugLoc dl = MI->getDebugLoc();
5752   bool isThumb2 = Subtarget->isThumb2();
5753
5754   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5755   if (isThumb2) {
5756     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5757     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5758   }
5759
5760   unsigned ldrOpc, strOpc;
5761   switch (Size) {
5762   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5763   case 1:
5764     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5765     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5766     break;
5767   case 2:
5768     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5769     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5770     break;
5771   case 4:
5772     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5773     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5774     break;
5775   }
5776
5777   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5778   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5779   MF->insert(It, loopMBB);
5780   MF->insert(It, exitMBB);
5781
5782   // Transfer the remainder of BB and its successor edges to exitMBB.
5783   exitMBB->splice(exitMBB->begin(), BB,
5784                   llvm::next(MachineBasicBlock::iterator(MI)),
5785                   BB->end());
5786   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5787
5788   const TargetRegisterClass *TRC = isThumb2 ?
5789     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5790     (const TargetRegisterClass*)&ARM::GPRRegClass;
5791   unsigned scratch = MRI.createVirtualRegister(TRC);
5792   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5793
5794   //  thisMBB:
5795   //   ...
5796   //   fallthrough --> loopMBB
5797   BB->addSuccessor(loopMBB);
5798
5799   //  loopMBB:
5800   //   ldrex dest, ptr
5801   //   <binop> scratch2, dest, incr
5802   //   strex scratch, scratch2, ptr
5803   //   cmp scratch, #0
5804   //   bne- loopMBB
5805   //   fallthrough --> exitMBB
5806   BB = loopMBB;
5807   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5808   if (ldrOpc == ARM::t2LDREX)
5809     MIB.addImm(0);
5810   AddDefaultPred(MIB);
5811   if (BinOpcode) {
5812     // operand order needs to go the other way for NAND
5813     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5814       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5815                      addReg(incr).addReg(dest)).addReg(0);
5816     else
5817       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5818                      addReg(dest).addReg(incr)).addReg(0);
5819   }
5820
5821   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5822   if (strOpc == ARM::t2STREX)
5823     MIB.addImm(0);
5824   AddDefaultPred(MIB);
5825   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5826                  .addReg(scratch).addImm(0));
5827   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5828     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5829
5830   BB->addSuccessor(loopMBB);
5831   BB->addSuccessor(exitMBB);
5832
5833   //  exitMBB:
5834   //   ...
5835   BB = exitMBB;
5836
5837   MI->eraseFromParent();   // The instruction is gone now.
5838
5839   return BB;
5840 }
5841
5842 MachineBasicBlock *
5843 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5844                                           MachineBasicBlock *BB,
5845                                           unsigned Size,
5846                                           bool signExtend,
5847                                           ARMCC::CondCodes Cond) const {
5848   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5849
5850   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5851   MachineFunction *MF = BB->getParent();
5852   MachineFunction::iterator It = BB;
5853   ++It;
5854
5855   unsigned dest = MI->getOperand(0).getReg();
5856   unsigned ptr = MI->getOperand(1).getReg();
5857   unsigned incr = MI->getOperand(2).getReg();
5858   unsigned oldval = dest;
5859   DebugLoc dl = MI->getDebugLoc();
5860   bool isThumb2 = Subtarget->isThumb2();
5861
5862   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5863   if (isThumb2) {
5864     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5865     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5866   }
5867
5868   unsigned ldrOpc, strOpc, extendOpc;
5869   switch (Size) {
5870   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5871   case 1:
5872     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5873     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5874     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5875     break;
5876   case 2:
5877     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5878     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5879     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5880     break;
5881   case 4:
5882     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5883     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5884     extendOpc = 0;
5885     break;
5886   }
5887
5888   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5889   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5890   MF->insert(It, loopMBB);
5891   MF->insert(It, exitMBB);
5892
5893   // Transfer the remainder of BB and its successor edges to exitMBB.
5894   exitMBB->splice(exitMBB->begin(), BB,
5895                   llvm::next(MachineBasicBlock::iterator(MI)),
5896                   BB->end());
5897   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5898
5899   const TargetRegisterClass *TRC = isThumb2 ?
5900     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5901     (const TargetRegisterClass*)&ARM::GPRRegClass;
5902   unsigned scratch = MRI.createVirtualRegister(TRC);
5903   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5904
5905   //  thisMBB:
5906   //   ...
5907   //   fallthrough --> loopMBB
5908   BB->addSuccessor(loopMBB);
5909
5910   //  loopMBB:
5911   //   ldrex dest, ptr
5912   //   (sign extend dest, if required)
5913   //   cmp dest, incr
5914   //   cmov.cond scratch2, incr, dest
5915   //   strex scratch, scratch2, ptr
5916   //   cmp scratch, #0
5917   //   bne- loopMBB
5918   //   fallthrough --> exitMBB
5919   BB = loopMBB;
5920   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5921   if (ldrOpc == ARM::t2LDREX)
5922     MIB.addImm(0);
5923   AddDefaultPred(MIB);
5924
5925   // Sign extend the value, if necessary.
5926   if (signExtend && extendOpc) {
5927     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5928     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5929                      .addReg(dest)
5930                      .addImm(0));
5931   }
5932
5933   // Build compare and cmov instructions.
5934   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5935                  .addReg(oldval).addReg(incr));
5936   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5937          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5938
5939   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5940   if (strOpc == ARM::t2STREX)
5941     MIB.addImm(0);
5942   AddDefaultPred(MIB);
5943   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5944                  .addReg(scratch).addImm(0));
5945   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5946     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5947
5948   BB->addSuccessor(loopMBB);
5949   BB->addSuccessor(exitMBB);
5950
5951   //  exitMBB:
5952   //   ...
5953   BB = exitMBB;
5954
5955   MI->eraseFromParent();   // The instruction is gone now.
5956
5957   return BB;
5958 }
5959
5960 MachineBasicBlock *
5961 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5962                                       unsigned Op1, unsigned Op2,
5963                                       bool NeedsCarry, bool IsCmpxchg,
5964                                       bool IsMinMax, ARMCC::CondCodes CC) const {
5965   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5966   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5967
5968   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5969   MachineFunction *MF = BB->getParent();
5970   MachineFunction::iterator It = BB;
5971   ++It;
5972
5973   unsigned destlo = MI->getOperand(0).getReg();
5974   unsigned desthi = MI->getOperand(1).getReg();
5975   unsigned ptr = MI->getOperand(2).getReg();
5976   unsigned vallo = MI->getOperand(3).getReg();
5977   unsigned valhi = MI->getOperand(4).getReg();
5978   DebugLoc dl = MI->getDebugLoc();
5979   bool isThumb2 = Subtarget->isThumb2();
5980
5981   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5982   if (isThumb2) {
5983     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5984     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5985     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5986   }
5987
5988   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5989   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5990
5991   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5992   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5993   if (IsCmpxchg || IsMinMax)
5994     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5995   if (IsCmpxchg)
5996     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5997   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5998
5999   MF->insert(It, loopMBB);
6000   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6001   if (IsCmpxchg) MF->insert(It, cont2BB);
6002   MF->insert(It, exitMBB);
6003
6004   // Transfer the remainder of BB and its successor edges to exitMBB.
6005   exitMBB->splice(exitMBB->begin(), BB,
6006                   llvm::next(MachineBasicBlock::iterator(MI)),
6007                   BB->end());
6008   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6009
6010   const TargetRegisterClass *TRC = isThumb2 ?
6011     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6012     (const TargetRegisterClass*)&ARM::GPRRegClass;
6013   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6014
6015   //  thisMBB:
6016   //   ...
6017   //   fallthrough --> loopMBB
6018   BB->addSuccessor(loopMBB);
6019
6020   //  loopMBB:
6021   //   ldrexd r2, r3, ptr
6022   //   <binopa> r0, r2, incr
6023   //   <binopb> r1, r3, incr
6024   //   strexd storesuccess, r0, r1, ptr
6025   //   cmp storesuccess, #0
6026   //   bne- loopMBB
6027   //   fallthrough --> exitMBB
6028   //
6029   // Note that the registers are explicitly specified because there is not any
6030   // way to force the register allocator to allocate a register pair.
6031   //
6032   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
6033   // need to properly enforce the restriction that the two output registers
6034   // for ldrexd must be different.
6035   BB = loopMBB;
6036   // Load
6037   unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6038   unsigned GPRPair1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6039   unsigned GPRPair2;
6040   if (IsMinMax) {
6041     //We need an extra double register for doing min/max.
6042     unsigned undef = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6043     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6044     GPRPair2 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6045     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), undef);
6046     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6047       .addReg(undef)
6048       .addReg(vallo)
6049       .addImm(ARM::gsub_0);
6050     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair2)
6051       .addReg(r1)
6052       .addReg(valhi)
6053       .addImm(ARM::gsub_1);
6054   }
6055
6056   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6057                  .addReg(GPRPair0, RegState::Define).addReg(ptr));
6058   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6059   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6060     .addReg(GPRPair0, 0, ARM::gsub_0);
6061   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6062     .addReg(GPRPair0, 0, ARM::gsub_1);
6063
6064   if (IsCmpxchg) {
6065     // Add early exit
6066     for (unsigned i = 0; i < 2; i++) {
6067       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6068                                                          ARM::CMPrr))
6069                      .addReg(i == 0 ? destlo : desthi)
6070                      .addReg(i == 0 ? vallo : valhi));
6071       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6072         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6073       BB->addSuccessor(exitMBB);
6074       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6075       BB = (i == 0 ? contBB : cont2BB);
6076     }
6077
6078     // Copy to physregs for strexd
6079     unsigned setlo = MI->getOperand(5).getReg();
6080     unsigned sethi = MI->getOperand(6).getReg();
6081     unsigned undef = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6082     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6083     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), undef);
6084     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6085       .addReg(undef)
6086       .addReg(setlo)
6087       .addImm(ARM::gsub_0);
6088     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6089       .addReg(r1)
6090       .addReg(sethi)
6091       .addImm(ARM::gsub_1);
6092   } else if (Op1) {
6093     // Perform binary operation
6094     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6095     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6096                    .addReg(destlo).addReg(vallo))
6097         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6098     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6099     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6100                    .addReg(desthi).addReg(valhi))
6101         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6102
6103     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6104     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6105     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6106     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6107       .addReg(UndefPair)
6108       .addReg(tmpRegLo)
6109       .addImm(ARM::gsub_0);
6110     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6111       .addReg(r1)
6112       .addReg(tmpRegHi)
6113       .addImm(ARM::gsub_1);
6114   } else {
6115     // Copy to physregs for strexd
6116     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6117     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6118     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6119     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6120       .addReg(UndefPair)
6121       .addReg(vallo)
6122       .addImm(ARM::gsub_0);
6123     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6124       .addReg(r1)
6125       .addReg(valhi)
6126       .addImm(ARM::gsub_1);
6127   }
6128   unsigned GPRPairStore = GPRPair1;
6129   if (IsMinMax) {
6130     // Compare and branch to exit block.
6131     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6132       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6133     BB->addSuccessor(exitMBB);
6134     BB->addSuccessor(contBB);
6135     BB = contBB;
6136     GPRPairStore = GPRPair2;
6137   }
6138
6139   // Store
6140   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6141                  .addReg(GPRPairStore).addReg(ptr));
6142   // Cmp+jump
6143   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6144                  .addReg(storesuccess).addImm(0));
6145   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6146     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6147
6148   BB->addSuccessor(loopMBB);
6149   BB->addSuccessor(exitMBB);
6150
6151   //  exitMBB:
6152   //   ...
6153   BB = exitMBB;
6154
6155   MI->eraseFromParent();   // The instruction is gone now.
6156
6157   return BB;
6158 }
6159
6160 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6161 /// registers the function context.
6162 void ARMTargetLowering::
6163 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6164                        MachineBasicBlock *DispatchBB, int FI) const {
6165   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6166   DebugLoc dl = MI->getDebugLoc();
6167   MachineFunction *MF = MBB->getParent();
6168   MachineRegisterInfo *MRI = &MF->getRegInfo();
6169   MachineConstantPool *MCP = MF->getConstantPool();
6170   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6171   const Function *F = MF->getFunction();
6172
6173   bool isThumb = Subtarget->isThumb();
6174   bool isThumb2 = Subtarget->isThumb2();
6175
6176   unsigned PCLabelId = AFI->createPICLabelUId();
6177   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6178   ARMConstantPoolValue *CPV =
6179     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6180   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6181
6182   const TargetRegisterClass *TRC = isThumb ?
6183     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6184     (const TargetRegisterClass*)&ARM::GPRRegClass;
6185
6186   // Grab constant pool and fixed stack memory operands.
6187   MachineMemOperand *CPMMO =
6188     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6189                              MachineMemOperand::MOLoad, 4, 4);
6190
6191   MachineMemOperand *FIMMOSt =
6192     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6193                              MachineMemOperand::MOStore, 4, 4);
6194
6195   // Load the address of the dispatch MBB into the jump buffer.
6196   if (isThumb2) {
6197     // Incoming value: jbuf
6198     //   ldr.n  r5, LCPI1_1
6199     //   orr    r5, r5, #1
6200     //   add    r5, pc
6201     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6202     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6203     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6204                    .addConstantPoolIndex(CPI)
6205                    .addMemOperand(CPMMO));
6206     // Set the low bit because of thumb mode.
6207     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6208     AddDefaultCC(
6209       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6210                      .addReg(NewVReg1, RegState::Kill)
6211                      .addImm(0x01)));
6212     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6213     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6214       .addReg(NewVReg2, RegState::Kill)
6215       .addImm(PCLabelId);
6216     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6217                    .addReg(NewVReg3, RegState::Kill)
6218                    .addFrameIndex(FI)
6219                    .addImm(36)  // &jbuf[1] :: pc
6220                    .addMemOperand(FIMMOSt));
6221   } else if (isThumb) {
6222     // Incoming value: jbuf
6223     //   ldr.n  r1, LCPI1_4
6224     //   add    r1, pc
6225     //   mov    r2, #1
6226     //   orrs   r1, r2
6227     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6228     //   str    r1, [r2]
6229     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6230     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6231                    .addConstantPoolIndex(CPI)
6232                    .addMemOperand(CPMMO));
6233     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6234     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6235       .addReg(NewVReg1, RegState::Kill)
6236       .addImm(PCLabelId);
6237     // Set the low bit because of thumb mode.
6238     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6239     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6240                    .addReg(ARM::CPSR, RegState::Define)
6241                    .addImm(1));
6242     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6243     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6244                    .addReg(ARM::CPSR, RegState::Define)
6245                    .addReg(NewVReg2, RegState::Kill)
6246                    .addReg(NewVReg3, RegState::Kill));
6247     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6248     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6249                    .addFrameIndex(FI)
6250                    .addImm(36)); // &jbuf[1] :: pc
6251     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6252                    .addReg(NewVReg4, RegState::Kill)
6253                    .addReg(NewVReg5, RegState::Kill)
6254                    .addImm(0)
6255                    .addMemOperand(FIMMOSt));
6256   } else {
6257     // Incoming value: jbuf
6258     //   ldr  r1, LCPI1_1
6259     //   add  r1, pc, r1
6260     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6261     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6262     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6263                    .addConstantPoolIndex(CPI)
6264                    .addImm(0)
6265                    .addMemOperand(CPMMO));
6266     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6267     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6268                    .addReg(NewVReg1, RegState::Kill)
6269                    .addImm(PCLabelId));
6270     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6271                    .addReg(NewVReg2, RegState::Kill)
6272                    .addFrameIndex(FI)
6273                    .addImm(36)  // &jbuf[1] :: pc
6274                    .addMemOperand(FIMMOSt));
6275   }
6276 }
6277
6278 MachineBasicBlock *ARMTargetLowering::
6279 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6280   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6281   DebugLoc dl = MI->getDebugLoc();
6282   MachineFunction *MF = MBB->getParent();
6283   MachineRegisterInfo *MRI = &MF->getRegInfo();
6284   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6285   MachineFrameInfo *MFI = MF->getFrameInfo();
6286   int FI = MFI->getFunctionContextIndex();
6287
6288   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6289     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6290     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6291
6292   // Get a mapping of the call site numbers to all of the landing pads they're
6293   // associated with.
6294   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6295   unsigned MaxCSNum = 0;
6296   MachineModuleInfo &MMI = MF->getMMI();
6297   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6298        ++BB) {
6299     if (!BB->isLandingPad()) continue;
6300
6301     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6302     // pad.
6303     for (MachineBasicBlock::iterator
6304            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6305       if (!II->isEHLabel()) continue;
6306
6307       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6308       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6309
6310       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6311       for (SmallVectorImpl<unsigned>::iterator
6312              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6313            CSI != CSE; ++CSI) {
6314         CallSiteNumToLPad[*CSI].push_back(BB);
6315         MaxCSNum = std::max(MaxCSNum, *CSI);
6316       }
6317       break;
6318     }
6319   }
6320
6321   // Get an ordered list of the machine basic blocks for the jump table.
6322   std::vector<MachineBasicBlock*> LPadList;
6323   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6324   LPadList.reserve(CallSiteNumToLPad.size());
6325   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6326     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6327     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6328            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6329       LPadList.push_back(*II);
6330       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6331     }
6332   }
6333
6334   assert(!LPadList.empty() &&
6335          "No landing pad destinations for the dispatch jump table!");
6336
6337   // Create the jump table and associated information.
6338   MachineJumpTableInfo *JTI =
6339     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6340   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6341   unsigned UId = AFI->createJumpTableUId();
6342
6343   // Create the MBBs for the dispatch code.
6344
6345   // Shove the dispatch's address into the return slot in the function context.
6346   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6347   DispatchBB->setIsLandingPad();
6348
6349   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6350   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6351   DispatchBB->addSuccessor(TrapBB);
6352
6353   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6354   DispatchBB->addSuccessor(DispContBB);
6355
6356   // Insert and MBBs.
6357   MF->insert(MF->end(), DispatchBB);
6358   MF->insert(MF->end(), DispContBB);
6359   MF->insert(MF->end(), TrapBB);
6360
6361   // Insert code into the entry block that creates and registers the function
6362   // context.
6363   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6364
6365   MachineMemOperand *FIMMOLd =
6366     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6367                              MachineMemOperand::MOLoad |
6368                              MachineMemOperand::MOVolatile, 4, 4);
6369
6370   MachineInstrBuilder MIB;
6371   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6372
6373   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6374   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6375
6376   // Add a register mask with no preserved registers.  This results in all
6377   // registers being marked as clobbered.
6378   MIB.addRegMask(RI.getNoPreservedMask());
6379
6380   unsigned NumLPads = LPadList.size();
6381   if (Subtarget->isThumb2()) {
6382     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6383     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6384                    .addFrameIndex(FI)
6385                    .addImm(4)
6386                    .addMemOperand(FIMMOLd));
6387
6388     if (NumLPads < 256) {
6389       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6390                      .addReg(NewVReg1)
6391                      .addImm(LPadList.size()));
6392     } else {
6393       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6394       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6395                      .addImm(NumLPads & 0xFFFF));
6396
6397       unsigned VReg2 = VReg1;
6398       if ((NumLPads & 0xFFFF0000) != 0) {
6399         VReg2 = MRI->createVirtualRegister(TRC);
6400         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6401                        .addReg(VReg1)
6402                        .addImm(NumLPads >> 16));
6403       }
6404
6405       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6406                      .addReg(NewVReg1)
6407                      .addReg(VReg2));
6408     }
6409
6410     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6411       .addMBB(TrapBB)
6412       .addImm(ARMCC::HI)
6413       .addReg(ARM::CPSR);
6414
6415     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6416     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6417                    .addJumpTableIndex(MJTI)
6418                    .addImm(UId));
6419
6420     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6421     AddDefaultCC(
6422       AddDefaultPred(
6423         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6424         .addReg(NewVReg3, RegState::Kill)
6425         .addReg(NewVReg1)
6426         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6427
6428     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6429       .addReg(NewVReg4, RegState::Kill)
6430       .addReg(NewVReg1)
6431       .addJumpTableIndex(MJTI)
6432       .addImm(UId);
6433   } else if (Subtarget->isThumb()) {
6434     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6435     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6436                    .addFrameIndex(FI)
6437                    .addImm(1)
6438                    .addMemOperand(FIMMOLd));
6439
6440     if (NumLPads < 256) {
6441       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6442                      .addReg(NewVReg1)
6443                      .addImm(NumLPads));
6444     } else {
6445       MachineConstantPool *ConstantPool = MF->getConstantPool();
6446       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6447       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6448
6449       // MachineConstantPool wants an explicit alignment.
6450       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6451       if (Align == 0)
6452         Align = getDataLayout()->getTypeAllocSize(C->getType());
6453       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6454
6455       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6456       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6457                      .addReg(VReg1, RegState::Define)
6458                      .addConstantPoolIndex(Idx));
6459       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6460                      .addReg(NewVReg1)
6461                      .addReg(VReg1));
6462     }
6463
6464     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6465       .addMBB(TrapBB)
6466       .addImm(ARMCC::HI)
6467       .addReg(ARM::CPSR);
6468
6469     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6470     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6471                    .addReg(ARM::CPSR, RegState::Define)
6472                    .addReg(NewVReg1)
6473                    .addImm(2));
6474
6475     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6476     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6477                    .addJumpTableIndex(MJTI)
6478                    .addImm(UId));
6479
6480     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6481     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6482                    .addReg(ARM::CPSR, RegState::Define)
6483                    .addReg(NewVReg2, RegState::Kill)
6484                    .addReg(NewVReg3));
6485
6486     MachineMemOperand *JTMMOLd =
6487       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6488                                MachineMemOperand::MOLoad, 4, 4);
6489
6490     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6491     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6492                    .addReg(NewVReg4, RegState::Kill)
6493                    .addImm(0)
6494                    .addMemOperand(JTMMOLd));
6495
6496     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6497     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6498                    .addReg(ARM::CPSR, RegState::Define)
6499                    .addReg(NewVReg5, RegState::Kill)
6500                    .addReg(NewVReg3));
6501
6502     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6503       .addReg(NewVReg6, RegState::Kill)
6504       .addJumpTableIndex(MJTI)
6505       .addImm(UId);
6506   } else {
6507     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6508     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6509                    .addFrameIndex(FI)
6510                    .addImm(4)
6511                    .addMemOperand(FIMMOLd));
6512
6513     if (NumLPads < 256) {
6514       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6515                      .addReg(NewVReg1)
6516                      .addImm(NumLPads));
6517     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6518       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6519       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6520                      .addImm(NumLPads & 0xFFFF));
6521
6522       unsigned VReg2 = VReg1;
6523       if ((NumLPads & 0xFFFF0000) != 0) {
6524         VReg2 = MRI->createVirtualRegister(TRC);
6525         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6526                        .addReg(VReg1)
6527                        .addImm(NumLPads >> 16));
6528       }
6529
6530       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6531                      .addReg(NewVReg1)
6532                      .addReg(VReg2));
6533     } else {
6534       MachineConstantPool *ConstantPool = MF->getConstantPool();
6535       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6536       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6537
6538       // MachineConstantPool wants an explicit alignment.
6539       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6540       if (Align == 0)
6541         Align = getDataLayout()->getTypeAllocSize(C->getType());
6542       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6543
6544       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6545       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6546                      .addReg(VReg1, RegState::Define)
6547                      .addConstantPoolIndex(Idx)
6548                      .addImm(0));
6549       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6550                      .addReg(NewVReg1)
6551                      .addReg(VReg1, RegState::Kill));
6552     }
6553
6554     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6555       .addMBB(TrapBB)
6556       .addImm(ARMCC::HI)
6557       .addReg(ARM::CPSR);
6558
6559     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6560     AddDefaultCC(
6561       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6562                      .addReg(NewVReg1)
6563                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6564     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6565     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6566                    .addJumpTableIndex(MJTI)
6567                    .addImm(UId));
6568
6569     MachineMemOperand *JTMMOLd =
6570       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6571                                MachineMemOperand::MOLoad, 4, 4);
6572     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6573     AddDefaultPred(
6574       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6575       .addReg(NewVReg3, RegState::Kill)
6576       .addReg(NewVReg4)
6577       .addImm(0)
6578       .addMemOperand(JTMMOLd));
6579
6580     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6581       .addReg(NewVReg5, RegState::Kill)
6582       .addReg(NewVReg4)
6583       .addJumpTableIndex(MJTI)
6584       .addImm(UId);
6585   }
6586
6587   // Add the jump table entries as successors to the MBB.
6588   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6589   for (std::vector<MachineBasicBlock*>::iterator
6590          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6591     MachineBasicBlock *CurMBB = *I;
6592     if (SeenMBBs.insert(CurMBB))
6593       DispContBB->addSuccessor(CurMBB);
6594   }
6595
6596   // N.B. the order the invoke BBs are processed in doesn't matter here.
6597   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6598   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6599   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6600          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6601     MachineBasicBlock *BB = *I;
6602
6603     // Remove the landing pad successor from the invoke block and replace it
6604     // with the new dispatch block.
6605     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6606                                                   BB->succ_end());
6607     while (!Successors.empty()) {
6608       MachineBasicBlock *SMBB = Successors.pop_back_val();
6609       if (SMBB->isLandingPad()) {
6610         BB->removeSuccessor(SMBB);
6611         MBBLPads.push_back(SMBB);
6612       }
6613     }
6614
6615     BB->addSuccessor(DispatchBB);
6616
6617     // Find the invoke call and mark all of the callee-saved registers as
6618     // 'implicit defined' so that they're spilled. This prevents code from
6619     // moving instructions to before the EH block, where they will never be
6620     // executed.
6621     for (MachineBasicBlock::reverse_iterator
6622            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6623       if (!II->isCall()) continue;
6624
6625       DenseMap<unsigned, bool> DefRegs;
6626       for (MachineInstr::mop_iterator
6627              OI = II->operands_begin(), OE = II->operands_end();
6628            OI != OE; ++OI) {
6629         if (!OI->isReg()) continue;
6630         DefRegs[OI->getReg()] = true;
6631       }
6632
6633       MachineInstrBuilder MIB(*MF, &*II);
6634
6635       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6636         unsigned Reg = SavedRegs[i];
6637         if (Subtarget->isThumb2() &&
6638             !ARM::tGPRRegClass.contains(Reg) &&
6639             !ARM::hGPRRegClass.contains(Reg))
6640           continue;
6641         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6642           continue;
6643         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6644           continue;
6645         if (!DefRegs[Reg])
6646           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6647       }
6648
6649       break;
6650     }
6651   }
6652
6653   // Mark all former landing pads as non-landing pads. The dispatch is the only
6654   // landing pad now.
6655   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6656          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6657     (*I)->setIsLandingPad(false);
6658
6659   // The instruction is gone now.
6660   MI->eraseFromParent();
6661
6662   return MBB;
6663 }
6664
6665 static
6666 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6667   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6668        E = MBB->succ_end(); I != E; ++I)
6669     if (*I != Succ)
6670       return *I;
6671   llvm_unreachable("Expecting a BB with two successors!");
6672 }
6673
6674 MachineBasicBlock *ARMTargetLowering::
6675 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6676   // This pseudo instruction has 3 operands: dst, src, size
6677   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6678   // Otherwise, we will generate unrolled scalar copies.
6679   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6680   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6681   MachineFunction::iterator It = BB;
6682   ++It;
6683
6684   unsigned dest = MI->getOperand(0).getReg();
6685   unsigned src = MI->getOperand(1).getReg();
6686   unsigned SizeVal = MI->getOperand(2).getImm();
6687   unsigned Align = MI->getOperand(3).getImm();
6688   DebugLoc dl = MI->getDebugLoc();
6689
6690   bool isThumb2 = Subtarget->isThumb2();
6691   MachineFunction *MF = BB->getParent();
6692   MachineRegisterInfo &MRI = MF->getRegInfo();
6693   unsigned ldrOpc, strOpc, UnitSize = 0;
6694
6695   const TargetRegisterClass *TRC = isThumb2 ?
6696     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6697     (const TargetRegisterClass*)&ARM::GPRRegClass;
6698   const TargetRegisterClass *TRC_Vec = 0;
6699
6700   if (Align & 1) {
6701     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6702     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6703     UnitSize = 1;
6704   } else if (Align & 2) {
6705     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6706     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6707     UnitSize = 2;
6708   } else {
6709     // Check whether we can use NEON instructions.
6710     if (!MF->getFunction()->getFnAttributes().
6711           hasAttribute(Attribute::NoImplicitFloat) &&
6712         Subtarget->hasNEON()) {
6713       if ((Align % 16 == 0) && SizeVal >= 16) {
6714         ldrOpc = ARM::VLD1q32wb_fixed;
6715         strOpc = ARM::VST1q32wb_fixed;
6716         UnitSize = 16;
6717         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6718       }
6719       else if ((Align % 8 == 0) && SizeVal >= 8) {
6720         ldrOpc = ARM::VLD1d32wb_fixed;
6721         strOpc = ARM::VST1d32wb_fixed;
6722         UnitSize = 8;
6723         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6724       }
6725     }
6726     // Can't use NEON instructions.
6727     if (UnitSize == 0) {
6728       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6729       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6730       UnitSize = 4;
6731     }
6732   }
6733
6734   unsigned BytesLeft = SizeVal % UnitSize;
6735   unsigned LoopSize = SizeVal - BytesLeft;
6736
6737   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6738     // Use LDR and STR to copy.
6739     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6740     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6741     unsigned srcIn = src;
6742     unsigned destIn = dest;
6743     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6744       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6745       unsigned srcOut = MRI.createVirtualRegister(TRC);
6746       unsigned destOut = MRI.createVirtualRegister(TRC);
6747       if (UnitSize >= 8) {
6748         AddDefaultPred(BuildMI(*BB, MI, dl,
6749           TII->get(ldrOpc), scratch)
6750           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6751
6752         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6753           .addReg(destIn).addImm(0).addReg(scratch));
6754       } else if (isThumb2) {
6755         AddDefaultPred(BuildMI(*BB, MI, dl,
6756           TII->get(ldrOpc), scratch)
6757           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6758
6759         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6760           .addReg(scratch).addReg(destIn)
6761           .addImm(UnitSize));
6762       } else {
6763         AddDefaultPred(BuildMI(*BB, MI, dl,
6764           TII->get(ldrOpc), scratch)
6765           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6766           .addImm(UnitSize));
6767
6768         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6769           .addReg(scratch).addReg(destIn)
6770           .addReg(0).addImm(UnitSize));
6771       }
6772       srcIn = srcOut;
6773       destIn = destOut;
6774     }
6775
6776     // Handle the leftover bytes with LDRB and STRB.
6777     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6778     // [destOut] = STRB_POST(scratch, destIn, 1)
6779     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6780     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6781     for (unsigned i = 0; i < BytesLeft; i++) {
6782       unsigned scratch = MRI.createVirtualRegister(TRC);
6783       unsigned srcOut = MRI.createVirtualRegister(TRC);
6784       unsigned destOut = MRI.createVirtualRegister(TRC);
6785       if (isThumb2) {
6786         AddDefaultPred(BuildMI(*BB, MI, dl,
6787           TII->get(ldrOpc),scratch)
6788           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6789
6790         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6791           .addReg(scratch).addReg(destIn)
6792           .addReg(0).addImm(1));
6793       } else {
6794         AddDefaultPred(BuildMI(*BB, MI, dl,
6795           TII->get(ldrOpc),scratch)
6796           .addReg(srcOut, RegState::Define).addReg(srcIn)
6797           .addReg(0).addImm(1));
6798
6799         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6800           .addReg(scratch).addReg(destIn)
6801           .addReg(0).addImm(1));
6802       }
6803       srcIn = srcOut;
6804       destIn = destOut;
6805     }
6806     MI->eraseFromParent();   // The instruction is gone now.
6807     return BB;
6808   }
6809
6810   // Expand the pseudo op to a loop.
6811   // thisMBB:
6812   //   ...
6813   //   movw varEnd, # --> with thumb2
6814   //   movt varEnd, #
6815   //   ldrcp varEnd, idx --> without thumb2
6816   //   fallthrough --> loopMBB
6817   // loopMBB:
6818   //   PHI varPhi, varEnd, varLoop
6819   //   PHI srcPhi, src, srcLoop
6820   //   PHI destPhi, dst, destLoop
6821   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6822   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6823   //   subs varLoop, varPhi, #UnitSize
6824   //   bne loopMBB
6825   //   fallthrough --> exitMBB
6826   // exitMBB:
6827   //   epilogue to handle left-over bytes
6828   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6829   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6830   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6831   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6832   MF->insert(It, loopMBB);
6833   MF->insert(It, exitMBB);
6834
6835   // Transfer the remainder of BB and its successor edges to exitMBB.
6836   exitMBB->splice(exitMBB->begin(), BB,
6837                   llvm::next(MachineBasicBlock::iterator(MI)),
6838                   BB->end());
6839   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6840
6841   // Load an immediate to varEnd.
6842   unsigned varEnd = MRI.createVirtualRegister(TRC);
6843   if (isThumb2) {
6844     unsigned VReg1 = varEnd;
6845     if ((LoopSize & 0xFFFF0000) != 0)
6846       VReg1 = MRI.createVirtualRegister(TRC);
6847     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6848                    .addImm(LoopSize & 0xFFFF));
6849
6850     if ((LoopSize & 0xFFFF0000) != 0)
6851       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6852                      .addReg(VReg1)
6853                      .addImm(LoopSize >> 16));
6854   } else {
6855     MachineConstantPool *ConstantPool = MF->getConstantPool();
6856     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6857     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6858
6859     // MachineConstantPool wants an explicit alignment.
6860     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6861     if (Align == 0)
6862       Align = getDataLayout()->getTypeAllocSize(C->getType());
6863     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6864
6865     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6866                    .addReg(varEnd, RegState::Define)
6867                    .addConstantPoolIndex(Idx)
6868                    .addImm(0));
6869   }
6870   BB->addSuccessor(loopMBB);
6871
6872   // Generate the loop body:
6873   //   varPhi = PHI(varLoop, varEnd)
6874   //   srcPhi = PHI(srcLoop, src)
6875   //   destPhi = PHI(destLoop, dst)
6876   MachineBasicBlock *entryBB = BB;
6877   BB = loopMBB;
6878   unsigned varLoop = MRI.createVirtualRegister(TRC);
6879   unsigned varPhi = MRI.createVirtualRegister(TRC);
6880   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6881   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6882   unsigned destLoop = MRI.createVirtualRegister(TRC);
6883   unsigned destPhi = MRI.createVirtualRegister(TRC);
6884
6885   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6886     .addReg(varLoop).addMBB(loopMBB)
6887     .addReg(varEnd).addMBB(entryBB);
6888   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6889     .addReg(srcLoop).addMBB(loopMBB)
6890     .addReg(src).addMBB(entryBB);
6891   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6892     .addReg(destLoop).addMBB(loopMBB)
6893     .addReg(dest).addMBB(entryBB);
6894
6895   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6896   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6897   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6898   if (UnitSize >= 8) {
6899     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6900       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6901
6902     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6903       .addReg(destPhi).addImm(0).addReg(scratch));
6904   } else if (isThumb2) {
6905     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6906       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6907
6908     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6909       .addReg(scratch).addReg(destPhi)
6910       .addImm(UnitSize));
6911   } else {
6912     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6913       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6914       .addImm(UnitSize));
6915
6916     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6917       .addReg(scratch).addReg(destPhi)
6918       .addReg(0).addImm(UnitSize));
6919   }
6920
6921   // Decrement loop variable by UnitSize.
6922   MachineInstrBuilder MIB = BuildMI(BB, dl,
6923     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6924   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6925   MIB->getOperand(5).setReg(ARM::CPSR);
6926   MIB->getOperand(5).setIsDef(true);
6927
6928   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6929     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6930
6931   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6932   BB->addSuccessor(loopMBB);
6933   BB->addSuccessor(exitMBB);
6934
6935   // Add epilogue to handle BytesLeft.
6936   BB = exitMBB;
6937   MachineInstr *StartOfExit = exitMBB->begin();
6938   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6939   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6940
6941   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6942   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6943   unsigned srcIn = srcLoop;
6944   unsigned destIn = destLoop;
6945   for (unsigned i = 0; i < BytesLeft; i++) {
6946     unsigned scratch = MRI.createVirtualRegister(TRC);
6947     unsigned srcOut = MRI.createVirtualRegister(TRC);
6948     unsigned destOut = MRI.createVirtualRegister(TRC);
6949     if (isThumb2) {
6950       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6951         TII->get(ldrOpc),scratch)
6952         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6953
6954       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6955         .addReg(scratch).addReg(destIn)
6956         .addImm(1));
6957     } else {
6958       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6959         TII->get(ldrOpc),scratch)
6960         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6961
6962       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6963         .addReg(scratch).addReg(destIn)
6964         .addReg(0).addImm(1));
6965     }
6966     srcIn = srcOut;
6967     destIn = destOut;
6968   }
6969
6970   MI->eraseFromParent();   // The instruction is gone now.
6971   return BB;
6972 }
6973
6974 MachineBasicBlock *
6975 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6976                                                MachineBasicBlock *BB) const {
6977   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6978   DebugLoc dl = MI->getDebugLoc();
6979   bool isThumb2 = Subtarget->isThumb2();
6980   switch (MI->getOpcode()) {
6981   default: {
6982     MI->dump();
6983     llvm_unreachable("Unexpected instr type to insert");
6984   }
6985   // The Thumb2 pre-indexed stores have the same MI operands, they just
6986   // define them differently in the .td files from the isel patterns, so
6987   // they need pseudos.
6988   case ARM::t2STR_preidx:
6989     MI->setDesc(TII->get(ARM::t2STR_PRE));
6990     return BB;
6991   case ARM::t2STRB_preidx:
6992     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6993     return BB;
6994   case ARM::t2STRH_preidx:
6995     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6996     return BB;
6997
6998   case ARM::STRi_preidx:
6999   case ARM::STRBi_preidx: {
7000     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7001       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7002     // Decode the offset.
7003     unsigned Offset = MI->getOperand(4).getImm();
7004     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7005     Offset = ARM_AM::getAM2Offset(Offset);
7006     if (isSub)
7007       Offset = -Offset;
7008
7009     MachineMemOperand *MMO = *MI->memoperands_begin();
7010     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7011       .addOperand(MI->getOperand(0))  // Rn_wb
7012       .addOperand(MI->getOperand(1))  // Rt
7013       .addOperand(MI->getOperand(2))  // Rn
7014       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7015       .addOperand(MI->getOperand(5))  // pred
7016       .addOperand(MI->getOperand(6))
7017       .addMemOperand(MMO);
7018     MI->eraseFromParent();
7019     return BB;
7020   }
7021   case ARM::STRr_preidx:
7022   case ARM::STRBr_preidx:
7023   case ARM::STRH_preidx: {
7024     unsigned NewOpc;
7025     switch (MI->getOpcode()) {
7026     default: llvm_unreachable("unexpected opcode!");
7027     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7028     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7029     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7030     }
7031     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7032     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7033       MIB.addOperand(MI->getOperand(i));
7034     MI->eraseFromParent();
7035     return BB;
7036   }
7037   case ARM::ATOMIC_LOAD_ADD_I8:
7038      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7039   case ARM::ATOMIC_LOAD_ADD_I16:
7040      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7041   case ARM::ATOMIC_LOAD_ADD_I32:
7042      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7043
7044   case ARM::ATOMIC_LOAD_AND_I8:
7045      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7046   case ARM::ATOMIC_LOAD_AND_I16:
7047      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7048   case ARM::ATOMIC_LOAD_AND_I32:
7049      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7050
7051   case ARM::ATOMIC_LOAD_OR_I8:
7052      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7053   case ARM::ATOMIC_LOAD_OR_I16:
7054      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7055   case ARM::ATOMIC_LOAD_OR_I32:
7056      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7057
7058   case ARM::ATOMIC_LOAD_XOR_I8:
7059      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7060   case ARM::ATOMIC_LOAD_XOR_I16:
7061      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7062   case ARM::ATOMIC_LOAD_XOR_I32:
7063      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7064
7065   case ARM::ATOMIC_LOAD_NAND_I8:
7066      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7067   case ARM::ATOMIC_LOAD_NAND_I16:
7068      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7069   case ARM::ATOMIC_LOAD_NAND_I32:
7070      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7071
7072   case ARM::ATOMIC_LOAD_SUB_I8:
7073      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7074   case ARM::ATOMIC_LOAD_SUB_I16:
7075      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7076   case ARM::ATOMIC_LOAD_SUB_I32:
7077      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7078
7079   case ARM::ATOMIC_LOAD_MIN_I8:
7080      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7081   case ARM::ATOMIC_LOAD_MIN_I16:
7082      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7083   case ARM::ATOMIC_LOAD_MIN_I32:
7084      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7085
7086   case ARM::ATOMIC_LOAD_MAX_I8:
7087      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7088   case ARM::ATOMIC_LOAD_MAX_I16:
7089      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7090   case ARM::ATOMIC_LOAD_MAX_I32:
7091      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7092
7093   case ARM::ATOMIC_LOAD_UMIN_I8:
7094      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7095   case ARM::ATOMIC_LOAD_UMIN_I16:
7096      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7097   case ARM::ATOMIC_LOAD_UMIN_I32:
7098      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7099
7100   case ARM::ATOMIC_LOAD_UMAX_I8:
7101      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7102   case ARM::ATOMIC_LOAD_UMAX_I16:
7103      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7104   case ARM::ATOMIC_LOAD_UMAX_I32:
7105      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7106
7107   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7108   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7109   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7110
7111   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7112   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7113   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7114
7115
7116   case ARM::ATOMADD6432:
7117     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7118                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7119                               /*NeedsCarry*/ true);
7120   case ARM::ATOMSUB6432:
7121     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7122                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7123                               /*NeedsCarry*/ true);
7124   case ARM::ATOMOR6432:
7125     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7126                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7127   case ARM::ATOMXOR6432:
7128     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7129                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7130   case ARM::ATOMAND6432:
7131     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7132                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7133   case ARM::ATOMSWAP6432:
7134     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7135   case ARM::ATOMCMPXCHG6432:
7136     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7137                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7138                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7139   case ARM::ATOMMIN6432:
7140     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7141                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7142                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7143                               /*IsMinMax*/ true, ARMCC::LE);
7144   case ARM::ATOMMAX6432:
7145     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7146                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7147                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7148                               /*IsMinMax*/ true, ARMCC::GE);
7149   case ARM::ATOMUMIN6432:
7150     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7151                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7152                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7153                               /*IsMinMax*/ true, ARMCC::LS);
7154   case ARM::ATOMUMAX6432:
7155     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7156                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7157                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7158                               /*IsMinMax*/ true, ARMCC::HS);
7159
7160   case ARM::tMOVCCr_pseudo: {
7161     // To "insert" a SELECT_CC instruction, we actually have to insert the
7162     // diamond control-flow pattern.  The incoming instruction knows the
7163     // destination vreg to set, the condition code register to branch on, the
7164     // true/false values to select between, and a branch opcode to use.
7165     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7166     MachineFunction::iterator It = BB;
7167     ++It;
7168
7169     //  thisMBB:
7170     //  ...
7171     //   TrueVal = ...
7172     //   cmpTY ccX, r1, r2
7173     //   bCC copy1MBB
7174     //   fallthrough --> copy0MBB
7175     MachineBasicBlock *thisMBB  = BB;
7176     MachineFunction *F = BB->getParent();
7177     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7178     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7179     F->insert(It, copy0MBB);
7180     F->insert(It, sinkMBB);
7181
7182     // Transfer the remainder of BB and its successor edges to sinkMBB.
7183     sinkMBB->splice(sinkMBB->begin(), BB,
7184                     llvm::next(MachineBasicBlock::iterator(MI)),
7185                     BB->end());
7186     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7187
7188     BB->addSuccessor(copy0MBB);
7189     BB->addSuccessor(sinkMBB);
7190
7191     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7192       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7193
7194     //  copy0MBB:
7195     //   %FalseValue = ...
7196     //   # fallthrough to sinkMBB
7197     BB = copy0MBB;
7198
7199     // Update machine-CFG edges
7200     BB->addSuccessor(sinkMBB);
7201
7202     //  sinkMBB:
7203     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7204     //  ...
7205     BB = sinkMBB;
7206     BuildMI(*BB, BB->begin(), dl,
7207             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7208       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7209       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7210
7211     MI->eraseFromParent();   // The pseudo instruction is gone now.
7212     return BB;
7213   }
7214
7215   case ARM::BCCi64:
7216   case ARM::BCCZi64: {
7217     // If there is an unconditional branch to the other successor, remove it.
7218     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7219
7220     // Compare both parts that make up the double comparison separately for
7221     // equality.
7222     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7223
7224     unsigned LHS1 = MI->getOperand(1).getReg();
7225     unsigned LHS2 = MI->getOperand(2).getReg();
7226     if (RHSisZero) {
7227       AddDefaultPred(BuildMI(BB, dl,
7228                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7229                      .addReg(LHS1).addImm(0));
7230       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7231         .addReg(LHS2).addImm(0)
7232         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7233     } else {
7234       unsigned RHS1 = MI->getOperand(3).getReg();
7235       unsigned RHS2 = MI->getOperand(4).getReg();
7236       AddDefaultPred(BuildMI(BB, dl,
7237                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7238                      .addReg(LHS1).addReg(RHS1));
7239       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7240         .addReg(LHS2).addReg(RHS2)
7241         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7242     }
7243
7244     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7245     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7246     if (MI->getOperand(0).getImm() == ARMCC::NE)
7247       std::swap(destMBB, exitMBB);
7248
7249     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7250       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7251     if (isThumb2)
7252       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7253     else
7254       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7255
7256     MI->eraseFromParent();   // The pseudo instruction is gone now.
7257     return BB;
7258   }
7259
7260   case ARM::Int_eh_sjlj_setjmp:
7261   case ARM::Int_eh_sjlj_setjmp_nofp:
7262   case ARM::tInt_eh_sjlj_setjmp:
7263   case ARM::t2Int_eh_sjlj_setjmp:
7264   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7265     EmitSjLjDispatchBlock(MI, BB);
7266     return BB;
7267
7268   case ARM::ABS:
7269   case ARM::t2ABS: {
7270     // To insert an ABS instruction, we have to insert the
7271     // diamond control-flow pattern.  The incoming instruction knows the
7272     // source vreg to test against 0, the destination vreg to set,
7273     // the condition code register to branch on, the
7274     // true/false values to select between, and a branch opcode to use.
7275     // It transforms
7276     //     V1 = ABS V0
7277     // into
7278     //     V2 = MOVS V0
7279     //     BCC                      (branch to SinkBB if V0 >= 0)
7280     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7281     //     SinkBB: V1 = PHI(V2, V3)
7282     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7283     MachineFunction::iterator BBI = BB;
7284     ++BBI;
7285     MachineFunction *Fn = BB->getParent();
7286     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7287     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7288     Fn->insert(BBI, RSBBB);
7289     Fn->insert(BBI, SinkBB);
7290
7291     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7292     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7293     bool isThumb2 = Subtarget->isThumb2();
7294     MachineRegisterInfo &MRI = Fn->getRegInfo();
7295     // In Thumb mode S must not be specified if source register is the SP or
7296     // PC and if destination register is the SP, so restrict register class
7297     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7298       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7299       (const TargetRegisterClass*)&ARM::GPRRegClass);
7300
7301     // Transfer the remainder of BB and its successor edges to sinkMBB.
7302     SinkBB->splice(SinkBB->begin(), BB,
7303       llvm::next(MachineBasicBlock::iterator(MI)),
7304       BB->end());
7305     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7306
7307     BB->addSuccessor(RSBBB);
7308     BB->addSuccessor(SinkBB);
7309
7310     // fall through to SinkMBB
7311     RSBBB->addSuccessor(SinkBB);
7312
7313     // insert a cmp at the end of BB
7314     AddDefaultPred(BuildMI(BB, dl,
7315                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7316                    .addReg(ABSSrcReg).addImm(0));
7317
7318     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7319     BuildMI(BB, dl,
7320       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7321       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7322
7323     // insert rsbri in RSBBB
7324     // Note: BCC and rsbri will be converted into predicated rsbmi
7325     // by if-conversion pass
7326     BuildMI(*RSBBB, RSBBB->begin(), dl,
7327       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7328       .addReg(ABSSrcReg, RegState::Kill)
7329       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7330
7331     // insert PHI in SinkBB,
7332     // reuse ABSDstReg to not change uses of ABS instruction
7333     BuildMI(*SinkBB, SinkBB->begin(), dl,
7334       TII->get(ARM::PHI), ABSDstReg)
7335       .addReg(NewRsbDstReg).addMBB(RSBBB)
7336       .addReg(ABSSrcReg).addMBB(BB);
7337
7338     // remove ABS instruction
7339     MI->eraseFromParent();
7340
7341     // return last added BB
7342     return SinkBB;
7343   }
7344   case ARM::COPY_STRUCT_BYVAL_I32:
7345     ++NumLoopByVals;
7346     return EmitStructByval(MI, BB);
7347   }
7348 }
7349
7350 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7351                                                       SDNode *Node) const {
7352   if (!MI->hasPostISelHook()) {
7353     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7354            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7355     return;
7356   }
7357
7358   const MCInstrDesc *MCID = &MI->getDesc();
7359   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7360   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7361   // operand is still set to noreg. If needed, set the optional operand's
7362   // register to CPSR, and remove the redundant implicit def.
7363   //
7364   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7365
7366   // Rename pseudo opcodes.
7367   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7368   if (NewOpc) {
7369     const ARMBaseInstrInfo *TII =
7370       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7371     MCID = &TII->get(NewOpc);
7372
7373     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7374            "converted opcode should be the same except for cc_out");
7375
7376     MI->setDesc(*MCID);
7377
7378     // Add the optional cc_out operand
7379     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7380   }
7381   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7382
7383   // Any ARM instruction that sets the 's' bit should specify an optional
7384   // "cc_out" operand in the last operand position.
7385   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7386     assert(!NewOpc && "Optional cc_out operand required");
7387     return;
7388   }
7389   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7390   // since we already have an optional CPSR def.
7391   bool definesCPSR = false;
7392   bool deadCPSR = false;
7393   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7394        i != e; ++i) {
7395     const MachineOperand &MO = MI->getOperand(i);
7396     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7397       definesCPSR = true;
7398       if (MO.isDead())
7399         deadCPSR = true;
7400       MI->RemoveOperand(i);
7401       break;
7402     }
7403   }
7404   if (!definesCPSR) {
7405     assert(!NewOpc && "Optional cc_out operand required");
7406     return;
7407   }
7408   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7409   if (deadCPSR) {
7410     assert(!MI->getOperand(ccOutIdx).getReg() &&
7411            "expect uninitialized optional cc_out operand");
7412     return;
7413   }
7414
7415   // If this instruction was defined with an optional CPSR def and its dag node
7416   // had a live implicit CPSR def, then activate the optional CPSR def.
7417   MachineOperand &MO = MI->getOperand(ccOutIdx);
7418   MO.setReg(ARM::CPSR);
7419   MO.setIsDef(true);
7420 }
7421
7422 //===----------------------------------------------------------------------===//
7423 //                           ARM Optimization Hooks
7424 //===----------------------------------------------------------------------===//
7425
7426 // Helper function that checks if N is a null or all ones constant.
7427 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7428   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7429   if (!C)
7430     return false;
7431   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7432 }
7433
7434 // Return true if N is conditionally 0 or all ones.
7435 // Detects these expressions where cc is an i1 value:
7436 //
7437 //   (select cc 0, y)   [AllOnes=0]
7438 //   (select cc y, 0)   [AllOnes=0]
7439 //   (zext cc)          [AllOnes=0]
7440 //   (sext cc)          [AllOnes=0/1]
7441 //   (select cc -1, y)  [AllOnes=1]
7442 //   (select cc y, -1)  [AllOnes=1]
7443 //
7444 // Invert is set when N is the null/all ones constant when CC is false.
7445 // OtherOp is set to the alternative value of N.
7446 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7447                                        SDValue &CC, bool &Invert,
7448                                        SDValue &OtherOp,
7449                                        SelectionDAG &DAG) {
7450   switch (N->getOpcode()) {
7451   default: return false;
7452   case ISD::SELECT: {
7453     CC = N->getOperand(0);
7454     SDValue N1 = N->getOperand(1);
7455     SDValue N2 = N->getOperand(2);
7456     if (isZeroOrAllOnes(N1, AllOnes)) {
7457       Invert = false;
7458       OtherOp = N2;
7459       return true;
7460     }
7461     if (isZeroOrAllOnes(N2, AllOnes)) {
7462       Invert = true;
7463       OtherOp = N1;
7464       return true;
7465     }
7466     return false;
7467   }
7468   case ISD::ZERO_EXTEND:
7469     // (zext cc) can never be the all ones value.
7470     if (AllOnes)
7471       return false;
7472     // Fall through.
7473   case ISD::SIGN_EXTEND: {
7474     EVT VT = N->getValueType(0);
7475     CC = N->getOperand(0);
7476     if (CC.getValueType() != MVT::i1)
7477       return false;
7478     Invert = !AllOnes;
7479     if (AllOnes)
7480       // When looking for an AllOnes constant, N is an sext, and the 'other'
7481       // value is 0.
7482       OtherOp = DAG.getConstant(0, VT);
7483     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7484       // When looking for a 0 constant, N can be zext or sext.
7485       OtherOp = DAG.getConstant(1, VT);
7486     else
7487       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7488     return true;
7489   }
7490   }
7491 }
7492
7493 // Combine a constant select operand into its use:
7494 //
7495 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7496 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7497 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7498 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7499 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7500 //
7501 // The transform is rejected if the select doesn't have a constant operand that
7502 // is null, or all ones when AllOnes is set.
7503 //
7504 // Also recognize sext/zext from i1:
7505 //
7506 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7507 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7508 //
7509 // These transformations eventually create predicated instructions.
7510 //
7511 // @param N       The node to transform.
7512 // @param Slct    The N operand that is a select.
7513 // @param OtherOp The other N operand (x above).
7514 // @param DCI     Context.
7515 // @param AllOnes Require the select constant to be all ones instead of null.
7516 // @returns The new node, or SDValue() on failure.
7517 static
7518 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7519                             TargetLowering::DAGCombinerInfo &DCI,
7520                             bool AllOnes = false) {
7521   SelectionDAG &DAG = DCI.DAG;
7522   EVT VT = N->getValueType(0);
7523   SDValue NonConstantVal;
7524   SDValue CCOp;
7525   bool SwapSelectOps;
7526   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7527                                   NonConstantVal, DAG))
7528     return SDValue();
7529
7530   // Slct is now know to be the desired identity constant when CC is true.
7531   SDValue TrueVal = OtherOp;
7532   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7533                                  OtherOp, NonConstantVal);
7534   // Unless SwapSelectOps says CC should be false.
7535   if (SwapSelectOps)
7536     std::swap(TrueVal, FalseVal);
7537
7538   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7539                      CCOp, TrueVal, FalseVal);
7540 }
7541
7542 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7543 static
7544 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7545                                        TargetLowering::DAGCombinerInfo &DCI) {
7546   SDValue N0 = N->getOperand(0);
7547   SDValue N1 = N->getOperand(1);
7548   if (N0.getNode()->hasOneUse()) {
7549     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7550     if (Result.getNode())
7551       return Result;
7552   }
7553   if (N1.getNode()->hasOneUse()) {
7554     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7555     if (Result.getNode())
7556       return Result;
7557   }
7558   return SDValue();
7559 }
7560
7561 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7562 // (only after legalization).
7563 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7564                                  TargetLowering::DAGCombinerInfo &DCI,
7565                                  const ARMSubtarget *Subtarget) {
7566
7567   // Only perform optimization if after legalize, and if NEON is available. We
7568   // also expected both operands to be BUILD_VECTORs.
7569   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7570       || N0.getOpcode() != ISD::BUILD_VECTOR
7571       || N1.getOpcode() != ISD::BUILD_VECTOR)
7572     return SDValue();
7573
7574   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7575   EVT VT = N->getValueType(0);
7576   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7577     return SDValue();
7578
7579   // Check that the vector operands are of the right form.
7580   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7581   // operands, where N is the size of the formed vector.
7582   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7583   // index such that we have a pair wise add pattern.
7584
7585   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7586   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7587     return SDValue();
7588   SDValue Vec = N0->getOperand(0)->getOperand(0);
7589   SDNode *V = Vec.getNode();
7590   unsigned nextIndex = 0;
7591
7592   // For each operands to the ADD which are BUILD_VECTORs,
7593   // check to see if each of their operands are an EXTRACT_VECTOR with
7594   // the same vector and appropriate index.
7595   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7596     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7597         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7598
7599       SDValue ExtVec0 = N0->getOperand(i);
7600       SDValue ExtVec1 = N1->getOperand(i);
7601
7602       // First operand is the vector, verify its the same.
7603       if (V != ExtVec0->getOperand(0).getNode() ||
7604           V != ExtVec1->getOperand(0).getNode())
7605         return SDValue();
7606
7607       // Second is the constant, verify its correct.
7608       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7609       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7610
7611       // For the constant, we want to see all the even or all the odd.
7612       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7613           || C1->getZExtValue() != nextIndex+1)
7614         return SDValue();
7615
7616       // Increment index.
7617       nextIndex+=2;
7618     } else
7619       return SDValue();
7620   }
7621
7622   // Create VPADDL node.
7623   SelectionDAG &DAG = DCI.DAG;
7624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7625
7626   // Build operand list.
7627   SmallVector<SDValue, 8> Ops;
7628   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7629                                 TLI.getPointerTy()));
7630
7631   // Input is the vector.
7632   Ops.push_back(Vec);
7633
7634   // Get widened type and narrowed type.
7635   MVT widenType;
7636   unsigned numElem = VT.getVectorNumElements();
7637   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7638     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7639     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7640     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7641     default:
7642       llvm_unreachable("Invalid vector element type for padd optimization.");
7643   }
7644
7645   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7646                             widenType, &Ops[0], Ops.size());
7647   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7648 }
7649
7650 static SDValue findMUL_LOHI(SDValue V) {
7651   if (V->getOpcode() == ISD::UMUL_LOHI ||
7652       V->getOpcode() == ISD::SMUL_LOHI)
7653     return V;
7654   return SDValue();
7655 }
7656
7657 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7658                                      TargetLowering::DAGCombinerInfo &DCI,
7659                                      const ARMSubtarget *Subtarget) {
7660
7661   if (Subtarget->isThumb1Only()) return SDValue();
7662
7663   // Only perform the checks after legalize when the pattern is available.
7664   if (DCI.isBeforeLegalize()) return SDValue();
7665
7666   // Look for multiply add opportunities.
7667   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7668   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7669   // a glue link from the first add to the second add.
7670   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7671   // a S/UMLAL instruction.
7672   //          loAdd   UMUL_LOHI
7673   //            \    / :lo    \ :hi
7674   //             \  /          \          [no multiline comment]
7675   //              ADDC         |  hiAdd
7676   //                 \ :glue  /  /
7677   //                  \      /  /
7678   //                    ADDE
7679   //
7680   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7681   SDValue AddcOp0 = AddcNode->getOperand(0);
7682   SDValue AddcOp1 = AddcNode->getOperand(1);
7683
7684   // Check if the two operands are from the same mul_lohi node.
7685   if (AddcOp0.getNode() == AddcOp1.getNode())
7686     return SDValue();
7687
7688   assert(AddcNode->getNumValues() == 2 &&
7689          AddcNode->getValueType(0) == MVT::i32 &&
7690          AddcNode->getValueType(1) == MVT::Glue &&
7691          "Expect ADDC with two result values: i32, glue");
7692
7693   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7694   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7695       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7696       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7697       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7698     return SDValue();
7699
7700   // Look for the glued ADDE.
7701   SDNode* AddeNode = AddcNode->getGluedUser();
7702   if (AddeNode == NULL)
7703     return SDValue();
7704
7705   // Make sure it is really an ADDE.
7706   if (AddeNode->getOpcode() != ISD::ADDE)
7707     return SDValue();
7708
7709   assert(AddeNode->getNumOperands() == 3 &&
7710          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7711          "ADDE node has the wrong inputs");
7712
7713   // Check for the triangle shape.
7714   SDValue AddeOp0 = AddeNode->getOperand(0);
7715   SDValue AddeOp1 = AddeNode->getOperand(1);
7716
7717   // Make sure that the ADDE operands are not coming from the same node.
7718   if (AddeOp0.getNode() == AddeOp1.getNode())
7719     return SDValue();
7720
7721   // Find the MUL_LOHI node walking up ADDE's operands.
7722   bool IsLeftOperandMUL = false;
7723   SDValue MULOp = findMUL_LOHI(AddeOp0);
7724   if (MULOp == SDValue())
7725    MULOp = findMUL_LOHI(AddeOp1);
7726   else
7727     IsLeftOperandMUL = true;
7728   if (MULOp == SDValue())
7729      return SDValue();
7730
7731   // Figure out the right opcode.
7732   unsigned Opc = MULOp->getOpcode();
7733   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7734
7735   // Figure out the high and low input values to the MLAL node.
7736   SDValue* HiMul = &MULOp;
7737   SDValue* HiAdd = NULL;
7738   SDValue* LoMul = NULL;
7739   SDValue* LowAdd = NULL;
7740
7741   if (IsLeftOperandMUL)
7742     HiAdd = &AddeOp1;
7743   else
7744     HiAdd = &AddeOp0;
7745
7746
7747   if (AddcOp0->getOpcode() == Opc) {
7748     LoMul = &AddcOp0;
7749     LowAdd = &AddcOp1;
7750   }
7751   if (AddcOp1->getOpcode() == Opc) {
7752     LoMul = &AddcOp1;
7753     LowAdd = &AddcOp0;
7754   }
7755
7756   if (LoMul == NULL)
7757     return SDValue();
7758
7759   if (LoMul->getNode() != HiMul->getNode())
7760     return SDValue();
7761
7762   // Create the merged node.
7763   SelectionDAG &DAG = DCI.DAG;
7764
7765   // Build operand list.
7766   SmallVector<SDValue, 8> Ops;
7767   Ops.push_back(LoMul->getOperand(0));
7768   Ops.push_back(LoMul->getOperand(1));
7769   Ops.push_back(*LowAdd);
7770   Ops.push_back(*HiAdd);
7771
7772   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7773                                  DAG.getVTList(MVT::i32, MVT::i32),
7774                                  &Ops[0], Ops.size());
7775
7776   // Replace the ADDs' nodes uses by the MLA node's values.
7777   SDValue HiMLALResult(MLALNode.getNode(), 1);
7778   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7779
7780   SDValue LoMLALResult(MLALNode.getNode(), 0);
7781   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7782
7783   // Return original node to notify the driver to stop replacing.
7784   SDValue resNode(AddcNode, 0);
7785   return resNode;
7786 }
7787
7788 /// PerformADDCCombine - Target-specific dag combine transform from
7789 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7790 static SDValue PerformADDCCombine(SDNode *N,
7791                                  TargetLowering::DAGCombinerInfo &DCI,
7792                                  const ARMSubtarget *Subtarget) {
7793
7794   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7795
7796 }
7797
7798 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7799 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7800 /// called with the default operands, and if that fails, with commuted
7801 /// operands.
7802 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7803                                           TargetLowering::DAGCombinerInfo &DCI,
7804                                           const ARMSubtarget *Subtarget){
7805
7806   // Attempt to create vpaddl for this add.
7807   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7808   if (Result.getNode())
7809     return Result;
7810
7811   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7812   if (N0.getNode()->hasOneUse()) {
7813     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7814     if (Result.getNode()) return Result;
7815   }
7816   return SDValue();
7817 }
7818
7819 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7820 ///
7821 static SDValue PerformADDCombine(SDNode *N,
7822                                  TargetLowering::DAGCombinerInfo &DCI,
7823                                  const ARMSubtarget *Subtarget) {
7824   SDValue N0 = N->getOperand(0);
7825   SDValue N1 = N->getOperand(1);
7826
7827   // First try with the default operand order.
7828   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7829   if (Result.getNode())
7830     return Result;
7831
7832   // If that didn't work, try again with the operands commuted.
7833   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7834 }
7835
7836 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7837 ///
7838 static SDValue PerformSUBCombine(SDNode *N,
7839                                  TargetLowering::DAGCombinerInfo &DCI) {
7840   SDValue N0 = N->getOperand(0);
7841   SDValue N1 = N->getOperand(1);
7842
7843   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7844   if (N1.getNode()->hasOneUse()) {
7845     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7846     if (Result.getNode()) return Result;
7847   }
7848
7849   return SDValue();
7850 }
7851
7852 /// PerformVMULCombine
7853 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7854 /// special multiplier accumulator forwarding.
7855 ///   vmul d3, d0, d2
7856 ///   vmla d3, d1, d2
7857 /// is faster than
7858 ///   vadd d3, d0, d1
7859 ///   vmul d3, d3, d2
7860 static SDValue PerformVMULCombine(SDNode *N,
7861                                   TargetLowering::DAGCombinerInfo &DCI,
7862                                   const ARMSubtarget *Subtarget) {
7863   if (!Subtarget->hasVMLxForwarding())
7864     return SDValue();
7865
7866   SelectionDAG &DAG = DCI.DAG;
7867   SDValue N0 = N->getOperand(0);
7868   SDValue N1 = N->getOperand(1);
7869   unsigned Opcode = N0.getOpcode();
7870   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7871       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7872     Opcode = N1.getOpcode();
7873     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7874         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7875       return SDValue();
7876     std::swap(N0, N1);
7877   }
7878
7879   EVT VT = N->getValueType(0);
7880   DebugLoc DL = N->getDebugLoc();
7881   SDValue N00 = N0->getOperand(0);
7882   SDValue N01 = N0->getOperand(1);
7883   return DAG.getNode(Opcode, DL, VT,
7884                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7885                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7886 }
7887
7888 static SDValue PerformMULCombine(SDNode *N,
7889                                  TargetLowering::DAGCombinerInfo &DCI,
7890                                  const ARMSubtarget *Subtarget) {
7891   SelectionDAG &DAG = DCI.DAG;
7892
7893   if (Subtarget->isThumb1Only())
7894     return SDValue();
7895
7896   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7897     return SDValue();
7898
7899   EVT VT = N->getValueType(0);
7900   if (VT.is64BitVector() || VT.is128BitVector())
7901     return PerformVMULCombine(N, DCI, Subtarget);
7902   if (VT != MVT::i32)
7903     return SDValue();
7904
7905   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7906   if (!C)
7907     return SDValue();
7908
7909   int64_t MulAmt = C->getSExtValue();
7910   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7911
7912   ShiftAmt = ShiftAmt & (32 - 1);
7913   SDValue V = N->getOperand(0);
7914   DebugLoc DL = N->getDebugLoc();
7915
7916   SDValue Res;
7917   MulAmt >>= ShiftAmt;
7918
7919   if (MulAmt >= 0) {
7920     if (isPowerOf2_32(MulAmt - 1)) {
7921       // (mul x, 2^N + 1) => (add (shl x, N), x)
7922       Res = DAG.getNode(ISD::ADD, DL, VT,
7923                         V,
7924                         DAG.getNode(ISD::SHL, DL, VT,
7925                                     V,
7926                                     DAG.getConstant(Log2_32(MulAmt - 1),
7927                                                     MVT::i32)));
7928     } else if (isPowerOf2_32(MulAmt + 1)) {
7929       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7930       Res = DAG.getNode(ISD::SUB, DL, VT,
7931                         DAG.getNode(ISD::SHL, DL, VT,
7932                                     V,
7933                                     DAG.getConstant(Log2_32(MulAmt + 1),
7934                                                     MVT::i32)),
7935                         V);
7936     } else
7937       return SDValue();
7938   } else {
7939     uint64_t MulAmtAbs = -MulAmt;
7940     if (isPowerOf2_32(MulAmtAbs + 1)) {
7941       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7942       Res = DAG.getNode(ISD::SUB, DL, VT,
7943                         V,
7944                         DAG.getNode(ISD::SHL, DL, VT,
7945                                     V,
7946                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7947                                                     MVT::i32)));
7948     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7949       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7950       Res = DAG.getNode(ISD::ADD, DL, VT,
7951                         V,
7952                         DAG.getNode(ISD::SHL, DL, VT,
7953                                     V,
7954                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7955                                                     MVT::i32)));
7956       Res = DAG.getNode(ISD::SUB, DL, VT,
7957                         DAG.getConstant(0, MVT::i32),Res);
7958
7959     } else
7960       return SDValue();
7961   }
7962
7963   if (ShiftAmt != 0)
7964     Res = DAG.getNode(ISD::SHL, DL, VT,
7965                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7966
7967   // Do not add new nodes to DAG combiner worklist.
7968   DCI.CombineTo(N, Res, false);
7969   return SDValue();
7970 }
7971
7972 static SDValue PerformANDCombine(SDNode *N,
7973                                  TargetLowering::DAGCombinerInfo &DCI,
7974                                  const ARMSubtarget *Subtarget) {
7975
7976   // Attempt to use immediate-form VBIC
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 &&
7989       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7990     if (SplatBitSize <= 64) {
7991       EVT VbicVT;
7992       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7993                                       SplatUndef.getZExtValue(), SplatBitSize,
7994                                       DAG, VbicVT, VT.is128BitVector(),
7995                                       OtherModImm);
7996       if (Val.getNode()) {
7997         SDValue Input =
7998           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7999         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8000         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8001       }
8002     }
8003   }
8004
8005   if (!Subtarget->isThumb1Only()) {
8006     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8007     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8008     if (Result.getNode())
8009       return Result;
8010   }
8011
8012   return SDValue();
8013 }
8014
8015 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8016 static SDValue PerformORCombine(SDNode *N,
8017                                 TargetLowering::DAGCombinerInfo &DCI,
8018                                 const ARMSubtarget *Subtarget) {
8019   // Attempt to use immediate-form VORR
8020   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8021   DebugLoc dl = N->getDebugLoc();
8022   EVT VT = N->getValueType(0);
8023   SelectionDAG &DAG = DCI.DAG;
8024
8025   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8026     return SDValue();
8027
8028   APInt SplatBits, SplatUndef;
8029   unsigned SplatBitSize;
8030   bool HasAnyUndefs;
8031   if (BVN && Subtarget->hasNEON() &&
8032       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8033     if (SplatBitSize <= 64) {
8034       EVT VorrVT;
8035       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8036                                       SplatUndef.getZExtValue(), SplatBitSize,
8037                                       DAG, VorrVT, VT.is128BitVector(),
8038                                       OtherModImm);
8039       if (Val.getNode()) {
8040         SDValue Input =
8041           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8042         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8043         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8044       }
8045     }
8046   }
8047
8048   if (!Subtarget->isThumb1Only()) {
8049     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8050     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8051     if (Result.getNode())
8052       return Result;
8053   }
8054
8055   // The code below optimizes (or (and X, Y), Z).
8056   // The AND operand needs to have a single user to make these optimizations
8057   // profitable.
8058   SDValue N0 = N->getOperand(0);
8059   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8060     return SDValue();
8061   SDValue N1 = N->getOperand(1);
8062
8063   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8064   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8065       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8066     APInt SplatUndef;
8067     unsigned SplatBitSize;
8068     bool HasAnyUndefs;
8069
8070     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8071     APInt SplatBits0;
8072     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8073                                   HasAnyUndefs) && !HasAnyUndefs) {
8074       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8075       APInt SplatBits1;
8076       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8077                                     HasAnyUndefs) && !HasAnyUndefs &&
8078           SplatBits0 == ~SplatBits1) {
8079         // Canonicalize the vector type to make instruction selection simpler.
8080         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8081         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8082                                      N0->getOperand(1), N0->getOperand(0),
8083                                      N1->getOperand(0));
8084         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8085       }
8086     }
8087   }
8088
8089   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8090   // reasonable.
8091
8092   // BFI is only available on V6T2+
8093   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8094     return SDValue();
8095
8096   DebugLoc DL = N->getDebugLoc();
8097   // 1) or (and A, mask), val => ARMbfi A, val, mask
8098   //      iff (val & mask) == val
8099   //
8100   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8101   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8102   //          && mask == ~mask2
8103   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8104   //          && ~mask == mask2
8105   //  (i.e., copy a bitfield value into another bitfield of the same width)
8106
8107   if (VT != MVT::i32)
8108     return SDValue();
8109
8110   SDValue N00 = N0.getOperand(0);
8111
8112   // The value and the mask need to be constants so we can verify this is
8113   // actually a bitfield set. If the mask is 0xffff, we can do better
8114   // via a movt instruction, so don't use BFI in that case.
8115   SDValue MaskOp = N0.getOperand(1);
8116   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8117   if (!MaskC)
8118     return SDValue();
8119   unsigned Mask = MaskC->getZExtValue();
8120   if (Mask == 0xffff)
8121     return SDValue();
8122   SDValue Res;
8123   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8124   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8125   if (N1C) {
8126     unsigned Val = N1C->getZExtValue();
8127     if ((Val & ~Mask) != Val)
8128       return SDValue();
8129
8130     if (ARM::isBitFieldInvertedMask(Mask)) {
8131       Val >>= CountTrailingZeros_32(~Mask);
8132
8133       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8134                         DAG.getConstant(Val, MVT::i32),
8135                         DAG.getConstant(Mask, MVT::i32));
8136
8137       // Do not add new nodes to DAG combiner worklist.
8138       DCI.CombineTo(N, Res, false);
8139       return SDValue();
8140     }
8141   } else if (N1.getOpcode() == ISD::AND) {
8142     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8143     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8144     if (!N11C)
8145       return SDValue();
8146     unsigned Mask2 = N11C->getZExtValue();
8147
8148     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8149     // as is to match.
8150     if (ARM::isBitFieldInvertedMask(Mask) &&
8151         (Mask == ~Mask2)) {
8152       // The pack halfword instruction works better for masks that fit it,
8153       // so use that when it's available.
8154       if (Subtarget->hasT2ExtractPack() &&
8155           (Mask == 0xffff || Mask == 0xffff0000))
8156         return SDValue();
8157       // 2a
8158       unsigned amt = CountTrailingZeros_32(Mask2);
8159       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8160                         DAG.getConstant(amt, MVT::i32));
8161       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8162                         DAG.getConstant(Mask, MVT::i32));
8163       // Do not add new nodes to DAG combiner worklist.
8164       DCI.CombineTo(N, Res, false);
8165       return SDValue();
8166     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8167                (~Mask == Mask2)) {
8168       // The pack halfword instruction works better for masks that fit it,
8169       // so use that when it's available.
8170       if (Subtarget->hasT2ExtractPack() &&
8171           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8172         return SDValue();
8173       // 2b
8174       unsigned lsb = CountTrailingZeros_32(Mask);
8175       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8176                         DAG.getConstant(lsb, MVT::i32));
8177       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8178                         DAG.getConstant(Mask2, MVT::i32));
8179       // Do not add new nodes to DAG combiner worklist.
8180       DCI.CombineTo(N, Res, false);
8181       return SDValue();
8182     }
8183   }
8184
8185   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8186       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8187       ARM::isBitFieldInvertedMask(~Mask)) {
8188     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8189     // where lsb(mask) == #shamt and masked bits of B are known zero.
8190     SDValue ShAmt = N00.getOperand(1);
8191     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8192     unsigned LSB = CountTrailingZeros_32(Mask);
8193     if (ShAmtC != LSB)
8194       return SDValue();
8195
8196     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8197                       DAG.getConstant(~Mask, MVT::i32));
8198
8199     // Do not add new nodes to DAG combiner worklist.
8200     DCI.CombineTo(N, Res, false);
8201   }
8202
8203   return SDValue();
8204 }
8205
8206 static SDValue PerformXORCombine(SDNode *N,
8207                                  TargetLowering::DAGCombinerInfo &DCI,
8208                                  const ARMSubtarget *Subtarget) {
8209   EVT VT = N->getValueType(0);
8210   SelectionDAG &DAG = DCI.DAG;
8211
8212   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8213     return SDValue();
8214
8215   if (!Subtarget->isThumb1Only()) {
8216     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8217     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8218     if (Result.getNode())
8219       return Result;
8220   }
8221
8222   return SDValue();
8223 }
8224
8225 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8226 /// the bits being cleared by the AND are not demanded by the BFI.
8227 static SDValue PerformBFICombine(SDNode *N,
8228                                  TargetLowering::DAGCombinerInfo &DCI) {
8229   SDValue N1 = N->getOperand(1);
8230   if (N1.getOpcode() == ISD::AND) {
8231     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8232     if (!N11C)
8233       return SDValue();
8234     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8235     unsigned LSB = CountTrailingZeros_32(~InvMask);
8236     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8237     unsigned Mask = (1 << Width)-1;
8238     unsigned Mask2 = N11C->getZExtValue();
8239     if ((Mask & (~Mask2)) == 0)
8240       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8241                              N->getOperand(0), N1.getOperand(0),
8242                              N->getOperand(2));
8243   }
8244   return SDValue();
8245 }
8246
8247 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8248 /// ARMISD::VMOVRRD.
8249 static SDValue PerformVMOVRRDCombine(SDNode *N,
8250                                      TargetLowering::DAGCombinerInfo &DCI) {
8251   // vmovrrd(vmovdrr x, y) -> x,y
8252   SDValue InDouble = N->getOperand(0);
8253   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8254     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8255
8256   // vmovrrd(load f64) -> (load i32), (load i32)
8257   SDNode *InNode = InDouble.getNode();
8258   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8259       InNode->getValueType(0) == MVT::f64 &&
8260       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8261       !cast<LoadSDNode>(InNode)->isVolatile()) {
8262     // TODO: Should this be done for non-FrameIndex operands?
8263     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8264
8265     SelectionDAG &DAG = DCI.DAG;
8266     DebugLoc DL = LD->getDebugLoc();
8267     SDValue BasePtr = LD->getBasePtr();
8268     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8269                                  LD->getPointerInfo(), LD->isVolatile(),
8270                                  LD->isNonTemporal(), LD->isInvariant(),
8271                                  LD->getAlignment());
8272
8273     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8274                                     DAG.getConstant(4, MVT::i32));
8275     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8276                                  LD->getPointerInfo(), LD->isVolatile(),
8277                                  LD->isNonTemporal(), LD->isInvariant(),
8278                                  std::min(4U, LD->getAlignment() / 2));
8279
8280     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8281     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8282     DCI.RemoveFromWorklist(LD);
8283     DAG.DeleteNode(LD);
8284     return Result;
8285   }
8286
8287   return SDValue();
8288 }
8289
8290 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8291 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8292 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8293   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8294   SDValue Op0 = N->getOperand(0);
8295   SDValue Op1 = N->getOperand(1);
8296   if (Op0.getOpcode() == ISD::BITCAST)
8297     Op0 = Op0.getOperand(0);
8298   if (Op1.getOpcode() == ISD::BITCAST)
8299     Op1 = Op1.getOperand(0);
8300   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8301       Op0.getNode() == Op1.getNode() &&
8302       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8303     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8304                        N->getValueType(0), Op0.getOperand(0));
8305   return SDValue();
8306 }
8307
8308 /// PerformSTORECombine - Target-specific dag combine xforms for
8309 /// ISD::STORE.
8310 static SDValue PerformSTORECombine(SDNode *N,
8311                                    TargetLowering::DAGCombinerInfo &DCI) {
8312   StoreSDNode *St = cast<StoreSDNode>(N);
8313   if (St->isVolatile())
8314     return SDValue();
8315
8316   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8317   // pack all of the elements in one place.  Next, store to memory in fewer
8318   // chunks.
8319   SDValue StVal = St->getValue();
8320   EVT VT = StVal.getValueType();
8321   if (St->isTruncatingStore() && VT.isVector()) {
8322     SelectionDAG &DAG = DCI.DAG;
8323     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8324     EVT StVT = St->getMemoryVT();
8325     unsigned NumElems = VT.getVectorNumElements();
8326     assert(StVT != VT && "Cannot truncate to the same type");
8327     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8328     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8329
8330     // From, To sizes and ElemCount must be pow of two
8331     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8332
8333     // We are going to use the original vector elt for storing.
8334     // Accumulated smaller vector elements must be a multiple of the store size.
8335     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8336
8337     unsigned SizeRatio  = FromEltSz / ToEltSz;
8338     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8339
8340     // Create a type on which we perform the shuffle.
8341     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8342                                      NumElems*SizeRatio);
8343     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8344
8345     DebugLoc DL = St->getDebugLoc();
8346     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8347     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8348     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8349
8350     // Can't shuffle using an illegal type.
8351     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8352
8353     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8354                                 DAG.getUNDEF(WideVec.getValueType()),
8355                                 ShuffleVec.data());
8356     // At this point all of the data is stored at the bottom of the
8357     // register. We now need to save it to mem.
8358
8359     // Find the largest store unit
8360     MVT StoreType = MVT::i8;
8361     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8362          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8363       MVT Tp = (MVT::SimpleValueType)tp;
8364       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8365         StoreType = Tp;
8366     }
8367     // Didn't find a legal store type.
8368     if (!TLI.isTypeLegal(StoreType))
8369       return SDValue();
8370
8371     // Bitcast the original vector into a vector of store-size units
8372     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8373             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8374     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8375     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8376     SmallVector<SDValue, 8> Chains;
8377     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8378                                         TLI.getPointerTy());
8379     SDValue BasePtr = St->getBasePtr();
8380
8381     // Perform one or more big stores into memory.
8382     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8383     for (unsigned I = 0; I < E; I++) {
8384       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8385                                    StoreType, ShuffWide,
8386                                    DAG.getIntPtrConstant(I));
8387       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8388                                 St->getPointerInfo(), St->isVolatile(),
8389                                 St->isNonTemporal(), St->getAlignment());
8390       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8391                             Increment);
8392       Chains.push_back(Ch);
8393     }
8394     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8395                        Chains.size());
8396   }
8397
8398   if (!ISD::isNormalStore(St))
8399     return SDValue();
8400
8401   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8402   // ARM stores of arguments in the same cache line.
8403   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8404       StVal.getNode()->hasOneUse()) {
8405     SelectionDAG  &DAG = DCI.DAG;
8406     DebugLoc DL = St->getDebugLoc();
8407     SDValue BasePtr = St->getBasePtr();
8408     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8409                                   StVal.getNode()->getOperand(0), BasePtr,
8410                                   St->getPointerInfo(), St->isVolatile(),
8411                                   St->isNonTemporal(), St->getAlignment());
8412
8413     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8414                                     DAG.getConstant(4, MVT::i32));
8415     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8416                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8417                         St->isNonTemporal(),
8418                         std::min(4U, St->getAlignment() / 2));
8419   }
8420
8421   if (StVal.getValueType() != MVT::i64 ||
8422       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8423     return SDValue();
8424
8425   // Bitcast an i64 store extracted from a vector to f64.
8426   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8427   SelectionDAG &DAG = DCI.DAG;
8428   DebugLoc dl = StVal.getDebugLoc();
8429   SDValue IntVec = StVal.getOperand(0);
8430   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8431                                  IntVec.getValueType().getVectorNumElements());
8432   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8433   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8434                                Vec, StVal.getOperand(1));
8435   dl = N->getDebugLoc();
8436   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8437   // Make the DAGCombiner fold the bitcasts.
8438   DCI.AddToWorklist(Vec.getNode());
8439   DCI.AddToWorklist(ExtElt.getNode());
8440   DCI.AddToWorklist(V.getNode());
8441   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8442                       St->getPointerInfo(), St->isVolatile(),
8443                       St->isNonTemporal(), St->getAlignment(),
8444                       St->getTBAAInfo());
8445 }
8446
8447 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8448 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8449 /// i64 vector to have f64 elements, since the value can then be loaded
8450 /// directly into a VFP register.
8451 static bool hasNormalLoadOperand(SDNode *N) {
8452   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8453   for (unsigned i = 0; i < NumElts; ++i) {
8454     SDNode *Elt = N->getOperand(i).getNode();
8455     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8456       return true;
8457   }
8458   return false;
8459 }
8460
8461 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8462 /// ISD::BUILD_VECTOR.
8463 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8464                                           TargetLowering::DAGCombinerInfo &DCI){
8465   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8466   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8467   // into a pair of GPRs, which is fine when the value is used as a scalar,
8468   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8469   SelectionDAG &DAG = DCI.DAG;
8470   if (N->getNumOperands() == 2) {
8471     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8472     if (RV.getNode())
8473       return RV;
8474   }
8475
8476   // Load i64 elements as f64 values so that type legalization does not split
8477   // them up into i32 values.
8478   EVT VT = N->getValueType(0);
8479   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8480     return SDValue();
8481   DebugLoc dl = N->getDebugLoc();
8482   SmallVector<SDValue, 8> Ops;
8483   unsigned NumElts = VT.getVectorNumElements();
8484   for (unsigned i = 0; i < NumElts; ++i) {
8485     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8486     Ops.push_back(V);
8487     // Make the DAGCombiner fold the bitcast.
8488     DCI.AddToWorklist(V.getNode());
8489   }
8490   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8491   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8492   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8493 }
8494
8495 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8496 /// ISD::INSERT_VECTOR_ELT.
8497 static SDValue PerformInsertEltCombine(SDNode *N,
8498                                        TargetLowering::DAGCombinerInfo &DCI) {
8499   // Bitcast an i64 load inserted into a vector to f64.
8500   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8501   EVT VT = N->getValueType(0);
8502   SDNode *Elt = N->getOperand(1).getNode();
8503   if (VT.getVectorElementType() != MVT::i64 ||
8504       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8505     return SDValue();
8506
8507   SelectionDAG &DAG = DCI.DAG;
8508   DebugLoc dl = N->getDebugLoc();
8509   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8510                                  VT.getVectorNumElements());
8511   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8512   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8513   // Make the DAGCombiner fold the bitcasts.
8514   DCI.AddToWorklist(Vec.getNode());
8515   DCI.AddToWorklist(V.getNode());
8516   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8517                                Vec, V, N->getOperand(2));
8518   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8519 }
8520
8521 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8522 /// ISD::VECTOR_SHUFFLE.
8523 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8524   // The LLVM shufflevector instruction does not require the shuffle mask
8525   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8526   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8527   // operands do not match the mask length, they are extended by concatenating
8528   // them with undef vectors.  That is probably the right thing for other
8529   // targets, but for NEON it is better to concatenate two double-register
8530   // size vector operands into a single quad-register size vector.  Do that
8531   // transformation here:
8532   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8533   //   shuffle(concat(v1, v2), undef)
8534   SDValue Op0 = N->getOperand(0);
8535   SDValue Op1 = N->getOperand(1);
8536   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8537       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8538       Op0.getNumOperands() != 2 ||
8539       Op1.getNumOperands() != 2)
8540     return SDValue();
8541   SDValue Concat0Op1 = Op0.getOperand(1);
8542   SDValue Concat1Op1 = Op1.getOperand(1);
8543   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8544       Concat1Op1.getOpcode() != ISD::UNDEF)
8545     return SDValue();
8546   // Skip the transformation if any of the types are illegal.
8547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8548   EVT VT = N->getValueType(0);
8549   if (!TLI.isTypeLegal(VT) ||
8550       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8551       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8552     return SDValue();
8553
8554   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8555                                   Op0.getOperand(0), Op1.getOperand(0));
8556   // Translate the shuffle mask.
8557   SmallVector<int, 16> NewMask;
8558   unsigned NumElts = VT.getVectorNumElements();
8559   unsigned HalfElts = NumElts/2;
8560   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8561   for (unsigned n = 0; n < NumElts; ++n) {
8562     int MaskElt = SVN->getMaskElt(n);
8563     int NewElt = -1;
8564     if (MaskElt < (int)HalfElts)
8565       NewElt = MaskElt;
8566     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8567       NewElt = HalfElts + MaskElt - NumElts;
8568     NewMask.push_back(NewElt);
8569   }
8570   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8571                               DAG.getUNDEF(VT), NewMask.data());
8572 }
8573
8574 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8575 /// NEON load/store intrinsics to merge base address updates.
8576 static SDValue CombineBaseUpdate(SDNode *N,
8577                                  TargetLowering::DAGCombinerInfo &DCI) {
8578   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8579     return SDValue();
8580
8581   SelectionDAG &DAG = DCI.DAG;
8582   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8583                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8584   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8585   SDValue Addr = N->getOperand(AddrOpIdx);
8586
8587   // Search for a use of the address operand that is an increment.
8588   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8589          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8590     SDNode *User = *UI;
8591     if (User->getOpcode() != ISD::ADD ||
8592         UI.getUse().getResNo() != Addr.getResNo())
8593       continue;
8594
8595     // Check that the add is independent of the load/store.  Otherwise, folding
8596     // it would create a cycle.
8597     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8598       continue;
8599
8600     // Find the new opcode for the updating load/store.
8601     bool isLoad = true;
8602     bool isLaneOp = false;
8603     unsigned NewOpc = 0;
8604     unsigned NumVecs = 0;
8605     if (isIntrinsic) {
8606       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8607       switch (IntNo) {
8608       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8609       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8610         NumVecs = 1; break;
8611       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8612         NumVecs = 2; break;
8613       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8614         NumVecs = 3; break;
8615       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8616         NumVecs = 4; break;
8617       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8618         NumVecs = 2; isLaneOp = true; break;
8619       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8620         NumVecs = 3; isLaneOp = true; break;
8621       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8622         NumVecs = 4; isLaneOp = true; break;
8623       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8624         NumVecs = 1; isLoad = false; break;
8625       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8626         NumVecs = 2; isLoad = false; break;
8627       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8628         NumVecs = 3; isLoad = false; break;
8629       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8630         NumVecs = 4; isLoad = false; break;
8631       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8632         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8633       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8634         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8635       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8636         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8637       }
8638     } else {
8639       isLaneOp = true;
8640       switch (N->getOpcode()) {
8641       default: llvm_unreachable("unexpected opcode for Neon base update");
8642       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8643       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8644       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8645       }
8646     }
8647
8648     // Find the size of memory referenced by the load/store.
8649     EVT VecTy;
8650     if (isLoad)
8651       VecTy = N->getValueType(0);
8652     else
8653       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8654     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8655     if (isLaneOp)
8656       NumBytes /= VecTy.getVectorNumElements();
8657
8658     // If the increment is a constant, it must match the memory ref size.
8659     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8660     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8661       uint64_t IncVal = CInc->getZExtValue();
8662       if (IncVal != NumBytes)
8663         continue;
8664     } else if (NumBytes >= 3 * 16) {
8665       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8666       // separate instructions that make it harder to use a non-constant update.
8667       continue;
8668     }
8669
8670     // Create the new updating load/store node.
8671     EVT Tys[6];
8672     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8673     unsigned n;
8674     for (n = 0; n < NumResultVecs; ++n)
8675       Tys[n] = VecTy;
8676     Tys[n++] = MVT::i32;
8677     Tys[n] = MVT::Other;
8678     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8679     SmallVector<SDValue, 8> Ops;
8680     Ops.push_back(N->getOperand(0)); // incoming chain
8681     Ops.push_back(N->getOperand(AddrOpIdx));
8682     Ops.push_back(Inc);
8683     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8684       Ops.push_back(N->getOperand(i));
8685     }
8686     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8687     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8688                                            Ops.data(), Ops.size(),
8689                                            MemInt->getMemoryVT(),
8690                                            MemInt->getMemOperand());
8691
8692     // Update the uses.
8693     std::vector<SDValue> NewResults;
8694     for (unsigned i = 0; i < NumResultVecs; ++i) {
8695       NewResults.push_back(SDValue(UpdN.getNode(), i));
8696     }
8697     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8698     DCI.CombineTo(N, NewResults);
8699     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8700
8701     break;
8702   }
8703   return SDValue();
8704 }
8705
8706 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8707 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8708 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8709 /// return true.
8710 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8711   SelectionDAG &DAG = DCI.DAG;
8712   EVT VT = N->getValueType(0);
8713   // vldN-dup instructions only support 64-bit vectors for N > 1.
8714   if (!VT.is64BitVector())
8715     return false;
8716
8717   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8718   SDNode *VLD = N->getOperand(0).getNode();
8719   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8720     return false;
8721   unsigned NumVecs = 0;
8722   unsigned NewOpc = 0;
8723   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8724   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8725     NumVecs = 2;
8726     NewOpc = ARMISD::VLD2DUP;
8727   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8728     NumVecs = 3;
8729     NewOpc = ARMISD::VLD3DUP;
8730   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8731     NumVecs = 4;
8732     NewOpc = ARMISD::VLD4DUP;
8733   } else {
8734     return false;
8735   }
8736
8737   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8738   // numbers match the load.
8739   unsigned VLDLaneNo =
8740     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8741   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8742        UI != UE; ++UI) {
8743     // Ignore uses of the chain result.
8744     if (UI.getUse().getResNo() == NumVecs)
8745       continue;
8746     SDNode *User = *UI;
8747     if (User->getOpcode() != ARMISD::VDUPLANE ||
8748         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8749       return false;
8750   }
8751
8752   // Create the vldN-dup node.
8753   EVT Tys[5];
8754   unsigned n;
8755   for (n = 0; n < NumVecs; ++n)
8756     Tys[n] = VT;
8757   Tys[n] = MVT::Other;
8758   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8759   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8760   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8761   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8762                                            Ops, 2, VLDMemInt->getMemoryVT(),
8763                                            VLDMemInt->getMemOperand());
8764
8765   // Update the uses.
8766   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8767        UI != UE; ++UI) {
8768     unsigned ResNo = UI.getUse().getResNo();
8769     // Ignore uses of the chain result.
8770     if (ResNo == NumVecs)
8771       continue;
8772     SDNode *User = *UI;
8773     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8774   }
8775
8776   // Now the vldN-lane intrinsic is dead except for its chain result.
8777   // Update uses of the chain.
8778   std::vector<SDValue> VLDDupResults;
8779   for (unsigned n = 0; n < NumVecs; ++n)
8780     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8781   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8782   DCI.CombineTo(VLD, VLDDupResults);
8783
8784   return true;
8785 }
8786
8787 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8788 /// ARMISD::VDUPLANE.
8789 static SDValue PerformVDUPLANECombine(SDNode *N,
8790                                       TargetLowering::DAGCombinerInfo &DCI) {
8791   SDValue Op = N->getOperand(0);
8792
8793   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8794   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8795   if (CombineVLDDUP(N, DCI))
8796     return SDValue(N, 0);
8797
8798   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8799   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8800   while (Op.getOpcode() == ISD::BITCAST)
8801     Op = Op.getOperand(0);
8802   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8803     return SDValue();
8804
8805   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8806   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8807   // The canonical VMOV for a zero vector uses a 32-bit element size.
8808   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8809   unsigned EltBits;
8810   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8811     EltSize = 8;
8812   EVT VT = N->getValueType(0);
8813   if (EltSize > VT.getVectorElementType().getSizeInBits())
8814     return SDValue();
8815
8816   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8817 }
8818
8819 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8820 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8821 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8822 {
8823   integerPart cN;
8824   integerPart c0 = 0;
8825   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8826        I != E; I++) {
8827     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8828     if (!C)
8829       return false;
8830
8831     bool isExact;
8832     APFloat APF = C->getValueAPF();
8833     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8834         != APFloat::opOK || !isExact)
8835       return false;
8836
8837     c0 = (I == 0) ? cN : c0;
8838     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8839       return false;
8840   }
8841   C = c0;
8842   return true;
8843 }
8844
8845 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8846 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8847 /// when the VMUL has a constant operand that is a power of 2.
8848 ///
8849 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8850 ///  vmul.f32        d16, d17, d16
8851 ///  vcvt.s32.f32    d16, d16
8852 /// becomes:
8853 ///  vcvt.s32.f32    d16, d16, #3
8854 static SDValue PerformVCVTCombine(SDNode *N,
8855                                   TargetLowering::DAGCombinerInfo &DCI,
8856                                   const ARMSubtarget *Subtarget) {
8857   SelectionDAG &DAG = DCI.DAG;
8858   SDValue Op = N->getOperand(0);
8859
8860   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8861       Op.getOpcode() != ISD::FMUL)
8862     return SDValue();
8863
8864   uint64_t C;
8865   SDValue N0 = Op->getOperand(0);
8866   SDValue ConstVec = Op->getOperand(1);
8867   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8868
8869   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8870       !isConstVecPow2(ConstVec, isSigned, C))
8871     return SDValue();
8872
8873   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8874     Intrinsic::arm_neon_vcvtfp2fxu;
8875   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8876                      N->getValueType(0),
8877                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8878                      DAG.getConstant(Log2_64(C), MVT::i32));
8879 }
8880
8881 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8882 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8883 /// when the VDIV has a constant operand that is a power of 2.
8884 ///
8885 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8886 ///  vcvt.f32.s32    d16, d16
8887 ///  vdiv.f32        d16, d17, d16
8888 /// becomes:
8889 ///  vcvt.f32.s32    d16, d16, #3
8890 static SDValue PerformVDIVCombine(SDNode *N,
8891                                   TargetLowering::DAGCombinerInfo &DCI,
8892                                   const ARMSubtarget *Subtarget) {
8893   SelectionDAG &DAG = DCI.DAG;
8894   SDValue Op = N->getOperand(0);
8895   unsigned OpOpcode = Op.getNode()->getOpcode();
8896
8897   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8898       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8899     return SDValue();
8900
8901   uint64_t C;
8902   SDValue ConstVec = N->getOperand(1);
8903   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8904
8905   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8906       !isConstVecPow2(ConstVec, isSigned, C))
8907     return SDValue();
8908
8909   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8910     Intrinsic::arm_neon_vcvtfxu2fp;
8911   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8912                      Op.getValueType(),
8913                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8914                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8915 }
8916
8917 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8918 /// operand of a vector shift operation, where all the elements of the
8919 /// build_vector must have the same constant integer value.
8920 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8921   // Ignore bit_converts.
8922   while (Op.getOpcode() == ISD::BITCAST)
8923     Op = Op.getOperand(0);
8924   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8925   APInt SplatBits, SplatUndef;
8926   unsigned SplatBitSize;
8927   bool HasAnyUndefs;
8928   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8929                                       HasAnyUndefs, ElementBits) ||
8930       SplatBitSize > ElementBits)
8931     return false;
8932   Cnt = SplatBits.getSExtValue();
8933   return true;
8934 }
8935
8936 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8937 /// operand of a vector shift left operation.  That value must be in the range:
8938 ///   0 <= Value < ElementBits for a left shift; or
8939 ///   0 <= Value <= ElementBits for a long left shift.
8940 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8941   assert(VT.isVector() && "vector shift count is not a vector type");
8942   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8943   if (! getVShiftImm(Op, ElementBits, Cnt))
8944     return false;
8945   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8946 }
8947
8948 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8949 /// operand of a vector shift right operation.  For a shift opcode, the value
8950 /// is positive, but for an intrinsic the value count must be negative. The
8951 /// absolute value must be in the range:
8952 ///   1 <= |Value| <= ElementBits for a right shift; or
8953 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8954 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8955                          int64_t &Cnt) {
8956   assert(VT.isVector() && "vector shift count is not a vector type");
8957   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8958   if (! getVShiftImm(Op, ElementBits, Cnt))
8959     return false;
8960   if (isIntrinsic)
8961     Cnt = -Cnt;
8962   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8963 }
8964
8965 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8966 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8967   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8968   switch (IntNo) {
8969   default:
8970     // Don't do anything for most intrinsics.
8971     break;
8972
8973   // Vector shifts: check for immediate versions and lower them.
8974   // Note: This is done during DAG combining instead of DAG legalizing because
8975   // the build_vectors for 64-bit vector element shift counts are generally
8976   // not legal, and it is hard to see their values after they get legalized to
8977   // loads from a constant pool.
8978   case Intrinsic::arm_neon_vshifts:
8979   case Intrinsic::arm_neon_vshiftu:
8980   case Intrinsic::arm_neon_vshiftls:
8981   case Intrinsic::arm_neon_vshiftlu:
8982   case Intrinsic::arm_neon_vshiftn:
8983   case Intrinsic::arm_neon_vrshifts:
8984   case Intrinsic::arm_neon_vrshiftu:
8985   case Intrinsic::arm_neon_vrshiftn:
8986   case Intrinsic::arm_neon_vqshifts:
8987   case Intrinsic::arm_neon_vqshiftu:
8988   case Intrinsic::arm_neon_vqshiftsu:
8989   case Intrinsic::arm_neon_vqshiftns:
8990   case Intrinsic::arm_neon_vqshiftnu:
8991   case Intrinsic::arm_neon_vqshiftnsu:
8992   case Intrinsic::arm_neon_vqrshiftns:
8993   case Intrinsic::arm_neon_vqrshiftnu:
8994   case Intrinsic::arm_neon_vqrshiftnsu: {
8995     EVT VT = N->getOperand(1).getValueType();
8996     int64_t Cnt;
8997     unsigned VShiftOpc = 0;
8998
8999     switch (IntNo) {
9000     case Intrinsic::arm_neon_vshifts:
9001     case Intrinsic::arm_neon_vshiftu:
9002       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9003         VShiftOpc = ARMISD::VSHL;
9004         break;
9005       }
9006       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9007         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9008                      ARMISD::VSHRs : ARMISD::VSHRu);
9009         break;
9010       }
9011       return SDValue();
9012
9013     case Intrinsic::arm_neon_vshiftls:
9014     case Intrinsic::arm_neon_vshiftlu:
9015       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9016         break;
9017       llvm_unreachable("invalid shift count for vshll intrinsic");
9018
9019     case Intrinsic::arm_neon_vrshifts:
9020     case Intrinsic::arm_neon_vrshiftu:
9021       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9022         break;
9023       return SDValue();
9024
9025     case Intrinsic::arm_neon_vqshifts:
9026     case Intrinsic::arm_neon_vqshiftu:
9027       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9028         break;
9029       return SDValue();
9030
9031     case Intrinsic::arm_neon_vqshiftsu:
9032       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9033         break;
9034       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9035
9036     case Intrinsic::arm_neon_vshiftn:
9037     case Intrinsic::arm_neon_vrshiftn:
9038     case Intrinsic::arm_neon_vqshiftns:
9039     case Intrinsic::arm_neon_vqshiftnu:
9040     case Intrinsic::arm_neon_vqshiftnsu:
9041     case Intrinsic::arm_neon_vqrshiftns:
9042     case Intrinsic::arm_neon_vqrshiftnu:
9043     case Intrinsic::arm_neon_vqrshiftnsu:
9044       // Narrowing shifts require an immediate right shift.
9045       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9046         break;
9047       llvm_unreachable("invalid shift count for narrowing vector shift "
9048                        "intrinsic");
9049
9050     default:
9051       llvm_unreachable("unhandled vector shift");
9052     }
9053
9054     switch (IntNo) {
9055     case Intrinsic::arm_neon_vshifts:
9056     case Intrinsic::arm_neon_vshiftu:
9057       // Opcode already set above.
9058       break;
9059     case Intrinsic::arm_neon_vshiftls:
9060     case Intrinsic::arm_neon_vshiftlu:
9061       if (Cnt == VT.getVectorElementType().getSizeInBits())
9062         VShiftOpc = ARMISD::VSHLLi;
9063       else
9064         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9065                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9066       break;
9067     case Intrinsic::arm_neon_vshiftn:
9068       VShiftOpc = ARMISD::VSHRN; break;
9069     case Intrinsic::arm_neon_vrshifts:
9070       VShiftOpc = ARMISD::VRSHRs; break;
9071     case Intrinsic::arm_neon_vrshiftu:
9072       VShiftOpc = ARMISD::VRSHRu; break;
9073     case Intrinsic::arm_neon_vrshiftn:
9074       VShiftOpc = ARMISD::VRSHRN; break;
9075     case Intrinsic::arm_neon_vqshifts:
9076       VShiftOpc = ARMISD::VQSHLs; break;
9077     case Intrinsic::arm_neon_vqshiftu:
9078       VShiftOpc = ARMISD::VQSHLu; break;
9079     case Intrinsic::arm_neon_vqshiftsu:
9080       VShiftOpc = ARMISD::VQSHLsu; break;
9081     case Intrinsic::arm_neon_vqshiftns:
9082       VShiftOpc = ARMISD::VQSHRNs; break;
9083     case Intrinsic::arm_neon_vqshiftnu:
9084       VShiftOpc = ARMISD::VQSHRNu; break;
9085     case Intrinsic::arm_neon_vqshiftnsu:
9086       VShiftOpc = ARMISD::VQSHRNsu; break;
9087     case Intrinsic::arm_neon_vqrshiftns:
9088       VShiftOpc = ARMISD::VQRSHRNs; break;
9089     case Intrinsic::arm_neon_vqrshiftnu:
9090       VShiftOpc = ARMISD::VQRSHRNu; break;
9091     case Intrinsic::arm_neon_vqrshiftnsu:
9092       VShiftOpc = ARMISD::VQRSHRNsu; break;
9093     }
9094
9095     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9096                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9097   }
9098
9099   case Intrinsic::arm_neon_vshiftins: {
9100     EVT VT = N->getOperand(1).getValueType();
9101     int64_t Cnt;
9102     unsigned VShiftOpc = 0;
9103
9104     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9105       VShiftOpc = ARMISD::VSLI;
9106     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9107       VShiftOpc = ARMISD::VSRI;
9108     else {
9109       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9110     }
9111
9112     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9113                        N->getOperand(1), N->getOperand(2),
9114                        DAG.getConstant(Cnt, MVT::i32));
9115   }
9116
9117   case Intrinsic::arm_neon_vqrshifts:
9118   case Intrinsic::arm_neon_vqrshiftu:
9119     // No immediate versions of these to check for.
9120     break;
9121   }
9122
9123   return SDValue();
9124 }
9125
9126 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9127 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9128 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9129 /// vector element shift counts are generally not legal, and it is hard to see
9130 /// their values after they get legalized to loads from a constant pool.
9131 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9132                                    const ARMSubtarget *ST) {
9133   EVT VT = N->getValueType(0);
9134   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9135     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9136     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9137     SDValue N1 = N->getOperand(1);
9138     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9139       SDValue N0 = N->getOperand(0);
9140       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9141           DAG.MaskedValueIsZero(N0.getOperand(0),
9142                                 APInt::getHighBitsSet(32, 16)))
9143         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9144     }
9145   }
9146
9147   // Nothing to be done for scalar shifts.
9148   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9149   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9150     return SDValue();
9151
9152   assert(ST->hasNEON() && "unexpected vector shift");
9153   int64_t Cnt;
9154
9155   switch (N->getOpcode()) {
9156   default: llvm_unreachable("unexpected shift opcode");
9157
9158   case ISD::SHL:
9159     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9160       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9161                          DAG.getConstant(Cnt, MVT::i32));
9162     break;
9163
9164   case ISD::SRA:
9165   case ISD::SRL:
9166     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9167       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9168                             ARMISD::VSHRs : ARMISD::VSHRu);
9169       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9170                          DAG.getConstant(Cnt, MVT::i32));
9171     }
9172   }
9173   return SDValue();
9174 }
9175
9176 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9177 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9178 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9179                                     const ARMSubtarget *ST) {
9180   SDValue N0 = N->getOperand(0);
9181
9182   // Check for sign- and zero-extensions of vector extract operations of 8-
9183   // and 16-bit vector elements.  NEON supports these directly.  They are
9184   // handled during DAG combining because type legalization will promote them
9185   // to 32-bit types and it is messy to recognize the operations after that.
9186   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9187     SDValue Vec = N0.getOperand(0);
9188     SDValue Lane = N0.getOperand(1);
9189     EVT VT = N->getValueType(0);
9190     EVT EltVT = N0.getValueType();
9191     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9192
9193     if (VT == MVT::i32 &&
9194         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9195         TLI.isTypeLegal(Vec.getValueType()) &&
9196         isa<ConstantSDNode>(Lane)) {
9197
9198       unsigned Opc = 0;
9199       switch (N->getOpcode()) {
9200       default: llvm_unreachable("unexpected opcode");
9201       case ISD::SIGN_EXTEND:
9202         Opc = ARMISD::VGETLANEs;
9203         break;
9204       case ISD::ZERO_EXTEND:
9205       case ISD::ANY_EXTEND:
9206         Opc = ARMISD::VGETLANEu;
9207         break;
9208       }
9209       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9210     }
9211   }
9212
9213   return SDValue();
9214 }
9215
9216 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9217 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9218 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9219                                        const ARMSubtarget *ST) {
9220   // If the target supports NEON, try to use vmax/vmin instructions for f32
9221   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9222   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9223   // a NaN; only do the transformation when it matches that behavior.
9224
9225   // For now only do this when using NEON for FP operations; if using VFP, it
9226   // is not obvious that the benefit outweighs the cost of switching to the
9227   // NEON pipeline.
9228   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9229       N->getValueType(0) != MVT::f32)
9230     return SDValue();
9231
9232   SDValue CondLHS = N->getOperand(0);
9233   SDValue CondRHS = N->getOperand(1);
9234   SDValue LHS = N->getOperand(2);
9235   SDValue RHS = N->getOperand(3);
9236   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9237
9238   unsigned Opcode = 0;
9239   bool IsReversed;
9240   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9241     IsReversed = false; // x CC y ? x : y
9242   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9243     IsReversed = true ; // x CC y ? y : x
9244   } else {
9245     return SDValue();
9246   }
9247
9248   bool IsUnordered;
9249   switch (CC) {
9250   default: break;
9251   case ISD::SETOLT:
9252   case ISD::SETOLE:
9253   case ISD::SETLT:
9254   case ISD::SETLE:
9255   case ISD::SETULT:
9256   case ISD::SETULE:
9257     // If LHS is NaN, an ordered comparison will be false and the result will
9258     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9259     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9260     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9261     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9262       break;
9263     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9264     // will return -0, so vmin can only be used for unsafe math or if one of
9265     // the operands is known to be nonzero.
9266     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9267         !DAG.getTarget().Options.UnsafeFPMath &&
9268         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9269       break;
9270     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9271     break;
9272
9273   case ISD::SETOGT:
9274   case ISD::SETOGE:
9275   case ISD::SETGT:
9276   case ISD::SETGE:
9277   case ISD::SETUGT:
9278   case ISD::SETUGE:
9279     // If LHS is NaN, an ordered comparison will be false and the result will
9280     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9281     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9282     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9283     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9284       break;
9285     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9286     // will return +0, so vmax can only be used for unsafe math or if one of
9287     // the operands is known to be nonzero.
9288     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9289         !DAG.getTarget().Options.UnsafeFPMath &&
9290         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9291       break;
9292     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9293     break;
9294   }
9295
9296   if (!Opcode)
9297     return SDValue();
9298   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9299 }
9300
9301 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9302 SDValue
9303 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9304   SDValue Cmp = N->getOperand(4);
9305   if (Cmp.getOpcode() != ARMISD::CMPZ)
9306     // Only looking at EQ and NE cases.
9307     return SDValue();
9308
9309   EVT VT = N->getValueType(0);
9310   DebugLoc dl = N->getDebugLoc();
9311   SDValue LHS = Cmp.getOperand(0);
9312   SDValue RHS = Cmp.getOperand(1);
9313   SDValue FalseVal = N->getOperand(0);
9314   SDValue TrueVal = N->getOperand(1);
9315   SDValue ARMcc = N->getOperand(2);
9316   ARMCC::CondCodes CC =
9317     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9318
9319   // Simplify
9320   //   mov     r1, r0
9321   //   cmp     r1, x
9322   //   mov     r0, y
9323   //   moveq   r0, x
9324   // to
9325   //   cmp     r0, x
9326   //   movne   r0, y
9327   //
9328   //   mov     r1, r0
9329   //   cmp     r1, x
9330   //   mov     r0, x
9331   //   movne   r0, y
9332   // to
9333   //   cmp     r0, x
9334   //   movne   r0, y
9335   /// FIXME: Turn this into a target neutral optimization?
9336   SDValue Res;
9337   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9338     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9339                       N->getOperand(3), Cmp);
9340   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9341     SDValue ARMcc;
9342     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9343     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9344                       N->getOperand(3), NewCmp);
9345   }
9346
9347   if (Res.getNode()) {
9348     APInt KnownZero, KnownOne;
9349     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9350     // Capture demanded bits information that would be otherwise lost.
9351     if (KnownZero == 0xfffffffe)
9352       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9353                         DAG.getValueType(MVT::i1));
9354     else if (KnownZero == 0xffffff00)
9355       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9356                         DAG.getValueType(MVT::i8));
9357     else if (KnownZero == 0xffff0000)
9358       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9359                         DAG.getValueType(MVT::i16));
9360   }
9361
9362   return Res;
9363 }
9364
9365 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9366                                              DAGCombinerInfo &DCI) const {
9367   switch (N->getOpcode()) {
9368   default: break;
9369   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9370   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9371   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9372   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9373   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9374   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9375   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9376   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9377   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9378   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9379   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9380   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9381   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9382   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9383   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9384   case ISD::FP_TO_SINT:
9385   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9386   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9387   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9388   case ISD::SHL:
9389   case ISD::SRA:
9390   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9391   case ISD::SIGN_EXTEND:
9392   case ISD::ZERO_EXTEND:
9393   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9394   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9395   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9396   case ARMISD::VLD2DUP:
9397   case ARMISD::VLD3DUP:
9398   case ARMISD::VLD4DUP:
9399     return CombineBaseUpdate(N, DCI);
9400   case ISD::INTRINSIC_VOID:
9401   case ISD::INTRINSIC_W_CHAIN:
9402     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9403     case Intrinsic::arm_neon_vld1:
9404     case Intrinsic::arm_neon_vld2:
9405     case Intrinsic::arm_neon_vld3:
9406     case Intrinsic::arm_neon_vld4:
9407     case Intrinsic::arm_neon_vld2lane:
9408     case Intrinsic::arm_neon_vld3lane:
9409     case Intrinsic::arm_neon_vld4lane:
9410     case Intrinsic::arm_neon_vst1:
9411     case Intrinsic::arm_neon_vst2:
9412     case Intrinsic::arm_neon_vst3:
9413     case Intrinsic::arm_neon_vst4:
9414     case Intrinsic::arm_neon_vst2lane:
9415     case Intrinsic::arm_neon_vst3lane:
9416     case Intrinsic::arm_neon_vst4lane:
9417       return CombineBaseUpdate(N, DCI);
9418     default: break;
9419     }
9420     break;
9421   }
9422   return SDValue();
9423 }
9424
9425 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9426                                                           EVT VT) const {
9427   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9428 }
9429
9430 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9431   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9432   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9433
9434   switch (VT.getSimpleVT().SimpleTy) {
9435   default:
9436     return false;
9437   case MVT::i8:
9438   case MVT::i16:
9439   case MVT::i32: {
9440     // Unaligned access can use (for example) LRDB, LRDH, LDR
9441     if (AllowsUnaligned) {
9442       if (Fast)
9443         *Fast = Subtarget->hasV7Ops();
9444       return true;
9445     }
9446     return false;
9447   }
9448   case MVT::f64:
9449   case MVT::v2f64: {
9450     // For any little-endian targets with neon, we can support unaligned ld/st
9451     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9452     // A big-endian target may also explictly support unaligned accesses
9453     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9454       if (Fast)
9455         *Fast = true;
9456       return true;
9457     }
9458     return false;
9459   }
9460   }
9461 }
9462
9463 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9464                        unsigned AlignCheck) {
9465   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9466           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9467 }
9468
9469 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9470                                            unsigned DstAlign, unsigned SrcAlign,
9471                                            bool IsMemset, bool ZeroMemset,
9472                                            bool MemcpyStrSrc,
9473                                            MachineFunction &MF) const {
9474   const Function *F = MF.getFunction();
9475
9476   // See if we can use NEON instructions for this...
9477   if ((!IsMemset || ZeroMemset) &&
9478       Subtarget->hasNEON() &&
9479       !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
9480     bool Fast;
9481     if (Size >= 16 &&
9482         (memOpAlign(SrcAlign, DstAlign, 16) ||
9483          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9484       return MVT::v2f64;
9485     } else if (Size >= 8 &&
9486                (memOpAlign(SrcAlign, DstAlign, 8) ||
9487                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9488       return MVT::f64;
9489     }
9490   }
9491
9492   // Lowering to i32/i16 if the size permits.
9493   if (Size >= 4)
9494     return MVT::i32;
9495   else if (Size >= 2)
9496     return MVT::i16;
9497
9498   // Let the target-independent logic figure it out.
9499   return MVT::Other;
9500 }
9501
9502 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9503   if (Val.getOpcode() != ISD::LOAD)
9504     return false;
9505
9506   EVT VT1 = Val.getValueType();
9507   if (!VT1.isSimple() || !VT1.isInteger() ||
9508       !VT2.isSimple() || !VT2.isInteger())
9509     return false;
9510
9511   switch (VT1.getSimpleVT().SimpleTy) {
9512   default: break;
9513   case MVT::i1:
9514   case MVT::i8:
9515   case MVT::i16:
9516     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9517     return true;
9518   }
9519
9520   return false;
9521 }
9522
9523 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9524   if (V < 0)
9525     return false;
9526
9527   unsigned Scale = 1;
9528   switch (VT.getSimpleVT().SimpleTy) {
9529   default: return false;
9530   case MVT::i1:
9531   case MVT::i8:
9532     // Scale == 1;
9533     break;
9534   case MVT::i16:
9535     // Scale == 2;
9536     Scale = 2;
9537     break;
9538   case MVT::i32:
9539     // Scale == 4;
9540     Scale = 4;
9541     break;
9542   }
9543
9544   if ((V & (Scale - 1)) != 0)
9545     return false;
9546   V /= Scale;
9547   return V == (V & ((1LL << 5) - 1));
9548 }
9549
9550 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9551                                       const ARMSubtarget *Subtarget) {
9552   bool isNeg = false;
9553   if (V < 0) {
9554     isNeg = true;
9555     V = - V;
9556   }
9557
9558   switch (VT.getSimpleVT().SimpleTy) {
9559   default: return false;
9560   case MVT::i1:
9561   case MVT::i8:
9562   case MVT::i16:
9563   case MVT::i32:
9564     // + imm12 or - imm8
9565     if (isNeg)
9566       return V == (V & ((1LL << 8) - 1));
9567     return V == (V & ((1LL << 12) - 1));
9568   case MVT::f32:
9569   case MVT::f64:
9570     // Same as ARM mode. FIXME: NEON?
9571     if (!Subtarget->hasVFP2())
9572       return false;
9573     if ((V & 3) != 0)
9574       return false;
9575     V >>= 2;
9576     return V == (V & ((1LL << 8) - 1));
9577   }
9578 }
9579
9580 /// isLegalAddressImmediate - Return true if the integer value can be used
9581 /// as the offset of the target addressing mode for load / store of the
9582 /// given type.
9583 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9584                                     const ARMSubtarget *Subtarget) {
9585   if (V == 0)
9586     return true;
9587
9588   if (!VT.isSimple())
9589     return false;
9590
9591   if (Subtarget->isThumb1Only())
9592     return isLegalT1AddressImmediate(V, VT);
9593   else if (Subtarget->isThumb2())
9594     return isLegalT2AddressImmediate(V, VT, Subtarget);
9595
9596   // ARM mode.
9597   if (V < 0)
9598     V = - V;
9599   switch (VT.getSimpleVT().SimpleTy) {
9600   default: return false;
9601   case MVT::i1:
9602   case MVT::i8:
9603   case MVT::i32:
9604     // +- imm12
9605     return V == (V & ((1LL << 12) - 1));
9606   case MVT::i16:
9607     // +- imm8
9608     return V == (V & ((1LL << 8) - 1));
9609   case MVT::f32:
9610   case MVT::f64:
9611     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9612       return false;
9613     if ((V & 3) != 0)
9614       return false;
9615     V >>= 2;
9616     return V == (V & ((1LL << 8) - 1));
9617   }
9618 }
9619
9620 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9621                                                       EVT VT) const {
9622   int Scale = AM.Scale;
9623   if (Scale < 0)
9624     return false;
9625
9626   switch (VT.getSimpleVT().SimpleTy) {
9627   default: return false;
9628   case MVT::i1:
9629   case MVT::i8:
9630   case MVT::i16:
9631   case MVT::i32:
9632     if (Scale == 1)
9633       return true;
9634     // r + r << imm
9635     Scale = Scale & ~1;
9636     return Scale == 2 || Scale == 4 || Scale == 8;
9637   case MVT::i64:
9638     // r + r
9639     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9640       return true;
9641     return false;
9642   case MVT::isVoid:
9643     // Note, we allow "void" uses (basically, uses that aren't loads or
9644     // stores), because arm allows folding a scale into many arithmetic
9645     // operations.  This should be made more precise and revisited later.
9646
9647     // Allow r << imm, but the imm has to be a multiple of two.
9648     if (Scale & 1) return false;
9649     return isPowerOf2_32(Scale);
9650   }
9651 }
9652
9653 /// isLegalAddressingMode - Return true if the addressing mode represented
9654 /// by AM is legal for this target, for a load/store of the specified type.
9655 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9656                                               Type *Ty) const {
9657   EVT VT = getValueType(Ty, true);
9658   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9659     return false;
9660
9661   // Can never fold addr of global into load/store.
9662   if (AM.BaseGV)
9663     return false;
9664
9665   switch (AM.Scale) {
9666   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9667     break;
9668   case 1:
9669     if (Subtarget->isThumb1Only())
9670       return false;
9671     // FALL THROUGH.
9672   default:
9673     // ARM doesn't support any R+R*scale+imm addr modes.
9674     if (AM.BaseOffs)
9675       return false;
9676
9677     if (!VT.isSimple())
9678       return false;
9679
9680     if (Subtarget->isThumb2())
9681       return isLegalT2ScaledAddressingMode(AM, VT);
9682
9683     int Scale = AM.Scale;
9684     switch (VT.getSimpleVT().SimpleTy) {
9685     default: return false;
9686     case MVT::i1:
9687     case MVT::i8:
9688     case MVT::i32:
9689       if (Scale < 0) Scale = -Scale;
9690       if (Scale == 1)
9691         return true;
9692       // r + r << imm
9693       return isPowerOf2_32(Scale & ~1);
9694     case MVT::i16:
9695     case MVT::i64:
9696       // r + r
9697       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9698         return true;
9699       return false;
9700
9701     case MVT::isVoid:
9702       // Note, we allow "void" uses (basically, uses that aren't loads or
9703       // stores), because arm allows folding a scale into many arithmetic
9704       // operations.  This should be made more precise and revisited later.
9705
9706       // Allow r << imm, but the imm has to be a multiple of two.
9707       if (Scale & 1) return false;
9708       return isPowerOf2_32(Scale);
9709     }
9710   }
9711   return true;
9712 }
9713
9714 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9715 /// icmp immediate, that is the target has icmp instructions which can compare
9716 /// a register against the immediate without having to materialize the
9717 /// immediate into a register.
9718 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9719   // Thumb2 and ARM modes can use cmn for negative immediates.
9720   if (!Subtarget->isThumb())
9721     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9722   if (Subtarget->isThumb2())
9723     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9724   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9725   return Imm >= 0 && Imm <= 255;
9726 }
9727
9728 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9729 /// *or sub* immediate, that is the target has add or sub instructions which can
9730 /// add a register with the immediate without having to materialize the
9731 /// immediate into a register.
9732 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9733   // Same encoding for add/sub, just flip the sign.
9734   int64_t AbsImm = llvm::abs64(Imm);
9735   if (!Subtarget->isThumb())
9736     return ARM_AM::getSOImmVal(AbsImm) != -1;
9737   if (Subtarget->isThumb2())
9738     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9739   // Thumb1 only has 8-bit unsigned immediate.
9740   return AbsImm >= 0 && AbsImm <= 255;
9741 }
9742
9743 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9744                                       bool isSEXTLoad, SDValue &Base,
9745                                       SDValue &Offset, bool &isInc,
9746                                       SelectionDAG &DAG) {
9747   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9748     return false;
9749
9750   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9751     // AddressingMode 3
9752     Base = Ptr->getOperand(0);
9753     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9754       int RHSC = (int)RHS->getZExtValue();
9755       if (RHSC < 0 && RHSC > -256) {
9756         assert(Ptr->getOpcode() == ISD::ADD);
9757         isInc = false;
9758         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9759         return true;
9760       }
9761     }
9762     isInc = (Ptr->getOpcode() == ISD::ADD);
9763     Offset = Ptr->getOperand(1);
9764     return true;
9765   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9766     // AddressingMode 2
9767     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9768       int RHSC = (int)RHS->getZExtValue();
9769       if (RHSC < 0 && RHSC > -0x1000) {
9770         assert(Ptr->getOpcode() == ISD::ADD);
9771         isInc = false;
9772         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9773         Base = Ptr->getOperand(0);
9774         return true;
9775       }
9776     }
9777
9778     if (Ptr->getOpcode() == ISD::ADD) {
9779       isInc = true;
9780       ARM_AM::ShiftOpc ShOpcVal=
9781         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9782       if (ShOpcVal != ARM_AM::no_shift) {
9783         Base = Ptr->getOperand(1);
9784         Offset = Ptr->getOperand(0);
9785       } else {
9786         Base = Ptr->getOperand(0);
9787         Offset = Ptr->getOperand(1);
9788       }
9789       return true;
9790     }
9791
9792     isInc = (Ptr->getOpcode() == ISD::ADD);
9793     Base = Ptr->getOperand(0);
9794     Offset = Ptr->getOperand(1);
9795     return true;
9796   }
9797
9798   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9799   return false;
9800 }
9801
9802 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9803                                      bool isSEXTLoad, SDValue &Base,
9804                                      SDValue &Offset, bool &isInc,
9805                                      SelectionDAG &DAG) {
9806   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9807     return false;
9808
9809   Base = Ptr->getOperand(0);
9810   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9811     int RHSC = (int)RHS->getZExtValue();
9812     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9813       assert(Ptr->getOpcode() == ISD::ADD);
9814       isInc = false;
9815       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9816       return true;
9817     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9818       isInc = Ptr->getOpcode() == ISD::ADD;
9819       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9820       return true;
9821     }
9822   }
9823
9824   return false;
9825 }
9826
9827 /// getPreIndexedAddressParts - returns true by value, base pointer and
9828 /// offset pointer and addressing mode by reference if the node's address
9829 /// can be legally represented as pre-indexed load / store address.
9830 bool
9831 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9832                                              SDValue &Offset,
9833                                              ISD::MemIndexedMode &AM,
9834                                              SelectionDAG &DAG) const {
9835   if (Subtarget->isThumb1Only())
9836     return false;
9837
9838   EVT VT;
9839   SDValue Ptr;
9840   bool isSEXTLoad = false;
9841   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9842     Ptr = LD->getBasePtr();
9843     VT  = LD->getMemoryVT();
9844     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9845   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9846     Ptr = ST->getBasePtr();
9847     VT  = ST->getMemoryVT();
9848   } else
9849     return false;
9850
9851   bool isInc;
9852   bool isLegal = false;
9853   if (Subtarget->isThumb2())
9854     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9855                                        Offset, isInc, DAG);
9856   else
9857     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9858                                         Offset, isInc, DAG);
9859   if (!isLegal)
9860     return false;
9861
9862   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9863   return true;
9864 }
9865
9866 /// getPostIndexedAddressParts - returns true by value, base pointer and
9867 /// offset pointer and addressing mode by reference if this node can be
9868 /// combined with a load / store to form a post-indexed load / store.
9869 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9870                                                    SDValue &Base,
9871                                                    SDValue &Offset,
9872                                                    ISD::MemIndexedMode &AM,
9873                                                    SelectionDAG &DAG) const {
9874   if (Subtarget->isThumb1Only())
9875     return false;
9876
9877   EVT VT;
9878   SDValue Ptr;
9879   bool isSEXTLoad = false;
9880   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9881     VT  = LD->getMemoryVT();
9882     Ptr = LD->getBasePtr();
9883     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9884   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9885     VT  = ST->getMemoryVT();
9886     Ptr = ST->getBasePtr();
9887   } else
9888     return false;
9889
9890   bool isInc;
9891   bool isLegal = false;
9892   if (Subtarget->isThumb2())
9893     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9894                                        isInc, DAG);
9895   else
9896     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9897                                         isInc, DAG);
9898   if (!isLegal)
9899     return false;
9900
9901   if (Ptr != Base) {
9902     // Swap base ptr and offset to catch more post-index load / store when
9903     // it's legal. In Thumb2 mode, offset must be an immediate.
9904     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9905         !Subtarget->isThumb2())
9906       std::swap(Base, Offset);
9907
9908     // Post-indexed load / store update the base pointer.
9909     if (Ptr != Base)
9910       return false;
9911   }
9912
9913   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9914   return true;
9915 }
9916
9917 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9918                                                        APInt &KnownZero,
9919                                                        APInt &KnownOne,
9920                                                        const SelectionDAG &DAG,
9921                                                        unsigned Depth) const {
9922   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9923   switch (Op.getOpcode()) {
9924   default: break;
9925   case ARMISD::CMOV: {
9926     // Bits are known zero/one if known on the LHS and RHS.
9927     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9928     if (KnownZero == 0 && KnownOne == 0) return;
9929
9930     APInt KnownZeroRHS, KnownOneRHS;
9931     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9932     KnownZero &= KnownZeroRHS;
9933     KnownOne  &= KnownOneRHS;
9934     return;
9935   }
9936   }
9937 }
9938
9939 //===----------------------------------------------------------------------===//
9940 //                           ARM Inline Assembly Support
9941 //===----------------------------------------------------------------------===//
9942
9943 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9944   // Looking for "rev" which is V6+.
9945   if (!Subtarget->hasV6Ops())
9946     return false;
9947
9948   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9949   std::string AsmStr = IA->getAsmString();
9950   SmallVector<StringRef, 4> AsmPieces;
9951   SplitString(AsmStr, AsmPieces, ";\n");
9952
9953   switch (AsmPieces.size()) {
9954   default: return false;
9955   case 1:
9956     AsmStr = AsmPieces[0];
9957     AsmPieces.clear();
9958     SplitString(AsmStr, AsmPieces, " \t,");
9959
9960     // rev $0, $1
9961     if (AsmPieces.size() == 3 &&
9962         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9963         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9964       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9965       if (Ty && Ty->getBitWidth() == 32)
9966         return IntrinsicLowering::LowerToByteSwap(CI);
9967     }
9968     break;
9969   }
9970
9971   return false;
9972 }
9973
9974 /// getConstraintType - Given a constraint letter, return the type of
9975 /// constraint it is for this target.
9976 ARMTargetLowering::ConstraintType
9977 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9978   if (Constraint.size() == 1) {
9979     switch (Constraint[0]) {
9980     default:  break;
9981     case 'l': return C_RegisterClass;
9982     case 'w': return C_RegisterClass;
9983     case 'h': return C_RegisterClass;
9984     case 'x': return C_RegisterClass;
9985     case 't': return C_RegisterClass;
9986     case 'j': return C_Other; // Constant for movw.
9987       // An address with a single base register. Due to the way we
9988       // currently handle addresses it is the same as an 'r' memory constraint.
9989     case 'Q': return C_Memory;
9990     }
9991   } else if (Constraint.size() == 2) {
9992     switch (Constraint[0]) {
9993     default: break;
9994     // All 'U+' constraints are addresses.
9995     case 'U': return C_Memory;
9996     }
9997   }
9998   return TargetLowering::getConstraintType(Constraint);
9999 }
10000
10001 /// Examine constraint type and operand type and determine a weight value.
10002 /// This object must already have been set up with the operand type
10003 /// and the current alternative constraint selected.
10004 TargetLowering::ConstraintWeight
10005 ARMTargetLowering::getSingleConstraintMatchWeight(
10006     AsmOperandInfo &info, const char *constraint) const {
10007   ConstraintWeight weight = CW_Invalid;
10008   Value *CallOperandVal = info.CallOperandVal;
10009     // If we don't have a value, we can't do a match,
10010     // but allow it at the lowest weight.
10011   if (CallOperandVal == NULL)
10012     return CW_Default;
10013   Type *type = CallOperandVal->getType();
10014   // Look at the constraint type.
10015   switch (*constraint) {
10016   default:
10017     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10018     break;
10019   case 'l':
10020     if (type->isIntegerTy()) {
10021       if (Subtarget->isThumb())
10022         weight = CW_SpecificReg;
10023       else
10024         weight = CW_Register;
10025     }
10026     break;
10027   case 'w':
10028     if (type->isFloatingPointTy())
10029       weight = CW_Register;
10030     break;
10031   }
10032   return weight;
10033 }
10034
10035 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10036 RCPair
10037 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10038                                                 EVT VT) const {
10039   if (Constraint.size() == 1) {
10040     // GCC ARM Constraint Letters
10041     switch (Constraint[0]) {
10042     case 'l': // Low regs or general regs.
10043       if (Subtarget->isThumb())
10044         return RCPair(0U, &ARM::tGPRRegClass);
10045       return RCPair(0U, &ARM::GPRRegClass);
10046     case 'h': // High regs or no regs.
10047       if (Subtarget->isThumb())
10048         return RCPair(0U, &ARM::hGPRRegClass);
10049       break;
10050     case 'r':
10051       return RCPair(0U, &ARM::GPRRegClass);
10052     case 'w':
10053       if (VT == MVT::f32)
10054         return RCPair(0U, &ARM::SPRRegClass);
10055       if (VT.getSizeInBits() == 64)
10056         return RCPair(0U, &ARM::DPRRegClass);
10057       if (VT.getSizeInBits() == 128)
10058         return RCPair(0U, &ARM::QPRRegClass);
10059       break;
10060     case 'x':
10061       if (VT == MVT::f32)
10062         return RCPair(0U, &ARM::SPR_8RegClass);
10063       if (VT.getSizeInBits() == 64)
10064         return RCPair(0U, &ARM::DPR_8RegClass);
10065       if (VT.getSizeInBits() == 128)
10066         return RCPair(0U, &ARM::QPR_8RegClass);
10067       break;
10068     case 't':
10069       if (VT == MVT::f32)
10070         return RCPair(0U, &ARM::SPRRegClass);
10071       break;
10072     }
10073   }
10074   if (StringRef("{cc}").equals_lower(Constraint))
10075     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10076
10077   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10078 }
10079
10080 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10081 /// vector.  If it is invalid, don't add anything to Ops.
10082 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10083                                                      std::string &Constraint,
10084                                                      std::vector<SDValue>&Ops,
10085                                                      SelectionDAG &DAG) const {
10086   SDValue Result(0, 0);
10087
10088   // Currently only support length 1 constraints.
10089   if (Constraint.length() != 1) return;
10090
10091   char ConstraintLetter = Constraint[0];
10092   switch (ConstraintLetter) {
10093   default: break;
10094   case 'j':
10095   case 'I': case 'J': case 'K': case 'L':
10096   case 'M': case 'N': case 'O':
10097     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10098     if (!C)
10099       return;
10100
10101     int64_t CVal64 = C->getSExtValue();
10102     int CVal = (int) CVal64;
10103     // None of these constraints allow values larger than 32 bits.  Check
10104     // that the value fits in an int.
10105     if (CVal != CVal64)
10106       return;
10107
10108     switch (ConstraintLetter) {
10109       case 'j':
10110         // Constant suitable for movw, must be between 0 and
10111         // 65535.
10112         if (Subtarget->hasV6T2Ops())
10113           if (CVal >= 0 && CVal <= 65535)
10114             break;
10115         return;
10116       case 'I':
10117         if (Subtarget->isThumb1Only()) {
10118           // This must be a constant between 0 and 255, for ADD
10119           // immediates.
10120           if (CVal >= 0 && CVal <= 255)
10121             break;
10122         } else if (Subtarget->isThumb2()) {
10123           // A constant that can be used as an immediate value in a
10124           // data-processing instruction.
10125           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10126             break;
10127         } else {
10128           // A constant that can be used as an immediate value in a
10129           // data-processing instruction.
10130           if (ARM_AM::getSOImmVal(CVal) != -1)
10131             break;
10132         }
10133         return;
10134
10135       case 'J':
10136         if (Subtarget->isThumb()) {  // FIXME thumb2
10137           // This must be a constant between -255 and -1, for negated ADD
10138           // immediates. This can be used in GCC with an "n" modifier that
10139           // prints the negated value, for use with SUB instructions. It is
10140           // not useful otherwise but is implemented for compatibility.
10141           if (CVal >= -255 && CVal <= -1)
10142             break;
10143         } else {
10144           // This must be a constant between -4095 and 4095. It is not clear
10145           // what this constraint is intended for. Implemented for
10146           // compatibility with GCC.
10147           if (CVal >= -4095 && CVal <= 4095)
10148             break;
10149         }
10150         return;
10151
10152       case 'K':
10153         if (Subtarget->isThumb1Only()) {
10154           // A 32-bit value where only one byte has a nonzero value. Exclude
10155           // zero to match GCC. This constraint is used by GCC internally for
10156           // constants that can be loaded with a move/shift combination.
10157           // It is not useful otherwise but is implemented for compatibility.
10158           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10159             break;
10160         } else if (Subtarget->isThumb2()) {
10161           // A constant whose bitwise inverse can be used as an immediate
10162           // value in a data-processing instruction. This can be used in GCC
10163           // with a "B" modifier that prints the inverted value, for use with
10164           // BIC and MVN instructions. It is not useful otherwise but is
10165           // implemented for compatibility.
10166           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10167             break;
10168         } else {
10169           // A constant whose bitwise inverse can be used as an immediate
10170           // value in a data-processing instruction. This can be used in GCC
10171           // with a "B" modifier that prints the inverted value, for use with
10172           // BIC and MVN instructions. It is not useful otherwise but is
10173           // implemented for compatibility.
10174           if (ARM_AM::getSOImmVal(~CVal) != -1)
10175             break;
10176         }
10177         return;
10178
10179       case 'L':
10180         if (Subtarget->isThumb1Only()) {
10181           // This must be a constant between -7 and 7,
10182           // for 3-operand ADD/SUB immediate instructions.
10183           if (CVal >= -7 && CVal < 7)
10184             break;
10185         } else if (Subtarget->isThumb2()) {
10186           // A constant whose negation can be used as an immediate value in a
10187           // data-processing instruction. This can be used in GCC with an "n"
10188           // modifier that prints the negated value, for use with SUB
10189           // instructions. It is not useful otherwise but is implemented for
10190           // compatibility.
10191           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10192             break;
10193         } else {
10194           // A constant whose negation can be used as an immediate value in a
10195           // data-processing instruction. This can be used in GCC with an "n"
10196           // modifier that prints the negated value, for use with SUB
10197           // instructions. It is not useful otherwise but is implemented for
10198           // compatibility.
10199           if (ARM_AM::getSOImmVal(-CVal) != -1)
10200             break;
10201         }
10202         return;
10203
10204       case 'M':
10205         if (Subtarget->isThumb()) { // FIXME thumb2
10206           // This must be a multiple of 4 between 0 and 1020, for
10207           // ADD sp + immediate.
10208           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10209             break;
10210         } else {
10211           // A power of two or a constant between 0 and 32.  This is used in
10212           // GCC for the shift amount on shifted register operands, but it is
10213           // useful in general for any shift amounts.
10214           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10215             break;
10216         }
10217         return;
10218
10219       case 'N':
10220         if (Subtarget->isThumb()) {  // FIXME thumb2
10221           // This must be a constant between 0 and 31, for shift amounts.
10222           if (CVal >= 0 && CVal <= 31)
10223             break;
10224         }
10225         return;
10226
10227       case 'O':
10228         if (Subtarget->isThumb()) {  // FIXME thumb2
10229           // This must be a multiple of 4 between -508 and 508, for
10230           // ADD/SUB sp = sp + immediate.
10231           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10232             break;
10233         }
10234         return;
10235     }
10236     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10237     break;
10238   }
10239
10240   if (Result.getNode()) {
10241     Ops.push_back(Result);
10242     return;
10243   }
10244   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10245 }
10246
10247 bool
10248 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10249   // The ARM target isn't yet aware of offsets.
10250   return false;
10251 }
10252
10253 bool ARM::isBitFieldInvertedMask(unsigned v) {
10254   if (v == 0xffffffff)
10255     return 0;
10256   // there can be 1's on either or both "outsides", all the "inside"
10257   // bits must be 0's
10258   unsigned int lsb = 0, msb = 31;
10259   while (v & (1 << msb)) --msb;
10260   while (v & (1 << lsb)) ++lsb;
10261   for (unsigned int i = lsb; i <= msb; ++i) {
10262     if (v & (1 << i))
10263       return 0;
10264   }
10265   return 1;
10266 }
10267
10268 /// isFPImmLegal - Returns true if the target can instruction select the
10269 /// specified FP immediate natively. If false, the legalizer will
10270 /// materialize the FP immediate as a load from a constant pool.
10271 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10272   if (!Subtarget->hasVFP3())
10273     return false;
10274   if (VT == MVT::f32)
10275     return ARM_AM::getFP32Imm(Imm) != -1;
10276   if (VT == MVT::f64)
10277     return ARM_AM::getFP64Imm(Imm) != -1;
10278   return false;
10279 }
10280
10281 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10282 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10283 /// specified in the intrinsic calls.
10284 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10285                                            const CallInst &I,
10286                                            unsigned Intrinsic) const {
10287   switch (Intrinsic) {
10288   case Intrinsic::arm_neon_vld1:
10289   case Intrinsic::arm_neon_vld2:
10290   case Intrinsic::arm_neon_vld3:
10291   case Intrinsic::arm_neon_vld4:
10292   case Intrinsic::arm_neon_vld2lane:
10293   case Intrinsic::arm_neon_vld3lane:
10294   case Intrinsic::arm_neon_vld4lane: {
10295     Info.opc = ISD::INTRINSIC_W_CHAIN;
10296     // Conservatively set memVT to the entire set of vectors loaded.
10297     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10298     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10299     Info.ptrVal = I.getArgOperand(0);
10300     Info.offset = 0;
10301     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10302     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10303     Info.vol = false; // volatile loads with NEON intrinsics not supported
10304     Info.readMem = true;
10305     Info.writeMem = false;
10306     return true;
10307   }
10308   case Intrinsic::arm_neon_vst1:
10309   case Intrinsic::arm_neon_vst2:
10310   case Intrinsic::arm_neon_vst3:
10311   case Intrinsic::arm_neon_vst4:
10312   case Intrinsic::arm_neon_vst2lane:
10313   case Intrinsic::arm_neon_vst3lane:
10314   case Intrinsic::arm_neon_vst4lane: {
10315     Info.opc = ISD::INTRINSIC_VOID;
10316     // Conservatively set memVT to the entire set of vectors stored.
10317     unsigned NumElts = 0;
10318     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10319       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10320       if (!ArgTy->isVectorTy())
10321         break;
10322       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10323     }
10324     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10325     Info.ptrVal = I.getArgOperand(0);
10326     Info.offset = 0;
10327     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10328     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10329     Info.vol = false; // volatile stores with NEON intrinsics not supported
10330     Info.readMem = false;
10331     Info.writeMem = true;
10332     return true;
10333   }
10334   case Intrinsic::arm_strexd: {
10335     Info.opc = ISD::INTRINSIC_W_CHAIN;
10336     Info.memVT = MVT::i64;
10337     Info.ptrVal = I.getArgOperand(2);
10338     Info.offset = 0;
10339     Info.align = 8;
10340     Info.vol = true;
10341     Info.readMem = false;
10342     Info.writeMem = true;
10343     return true;
10344   }
10345   case Intrinsic::arm_ldrexd: {
10346     Info.opc = ISD::INTRINSIC_W_CHAIN;
10347     Info.memVT = MVT::i64;
10348     Info.ptrVal = I.getArgOperand(0);
10349     Info.offset = 0;
10350     Info.align = 8;
10351     Info.vol = true;
10352     Info.readMem = true;
10353     Info.writeMem = false;
10354     return true;
10355   }
10356   default:
10357     break;
10358   }
10359
10360   return false;
10361 }
10362
10363 unsigned
10364 ARMScalarTargetTransformImpl::getIntImmCost(const APInt &Imm, Type *Ty) const {
10365   assert(Ty->isIntegerTy());
10366
10367   unsigned Bits = Ty->getPrimitiveSizeInBits();
10368   if (Bits == 0 || Bits > 32)
10369     return 4;
10370
10371   int32_t SImmVal = Imm.getSExtValue();
10372   uint32_t ZImmVal = Imm.getZExtValue();
10373   if (!Subtarget->isThumb()) {
10374     if ((SImmVal >= 0 && SImmVal < 65536) ||
10375         (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
10376         (ARM_AM::getSOImmVal(~ZImmVal) != -1))
10377       return 1;
10378     return Subtarget->hasV6T2Ops() ? 2 : 3;
10379   } else if (Subtarget->isThumb2()) {
10380     if ((SImmVal >= 0 && SImmVal < 65536) ||
10381         (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
10382         (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
10383       return 1;
10384     return Subtarget->hasV6T2Ops() ? 2 : 3;
10385   } else /*Thumb1*/ {
10386     if (SImmVal >= 0 && SImmVal < 256)
10387       return 1;
10388     if ((~ZImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
10389       return 2;
10390     // Load from constantpool.
10391     return 3;
10392   }
10393   return 2;
10394 }