3b8d79be97bf21cede8ced823cb9c480600ee9ce
[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/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.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::FFLOOR, MVT::v4f32, Expand);
519
520     // Neon does not support some operations on v1i64 and v2i64 types.
521     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
522     // Custom handling for some quad-vector types to detect VMULL.
523     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
524     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
525     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
526     // Custom handling for some vector types to avoid expensive expansions
527     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
528     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
529     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
532     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
533     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
534     // a destination type that is wider than the source, and nor does
535     // it have a FP_TO_[SU]INT instruction with a narrower destination than
536     // source.
537     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
538     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
539     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
540     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
541
542     setTargetDAGCombine(ISD::INTRINSIC_VOID);
543     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
544     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
545     setTargetDAGCombine(ISD::SHL);
546     setTargetDAGCombine(ISD::SRL);
547     setTargetDAGCombine(ISD::SRA);
548     setTargetDAGCombine(ISD::SIGN_EXTEND);
549     setTargetDAGCombine(ISD::ZERO_EXTEND);
550     setTargetDAGCombine(ISD::ANY_EXTEND);
551     setTargetDAGCombine(ISD::SELECT_CC);
552     setTargetDAGCombine(ISD::BUILD_VECTOR);
553     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
554     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
555     setTargetDAGCombine(ISD::STORE);
556     setTargetDAGCombine(ISD::FP_TO_SINT);
557     setTargetDAGCombine(ISD::FP_TO_UINT);
558     setTargetDAGCombine(ISD::FDIV);
559
560     // It is legal to extload from v4i8 to v4i16 or v4i32.
561     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
562                   MVT::v4i16, MVT::v2i16,
563                   MVT::v2i32};
564     for (unsigned i = 0; i < 6; ++i) {
565       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
566       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
567       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
568     }
569   }
570
571   // ARM and Thumb2 support UMLAL/SMLAL.
572   if (!Subtarget->isThumb1Only())
573     setTargetDAGCombine(ISD::ADDC);
574
575
576   computeRegisterProperties();
577
578   // ARM does not have f32 extending load.
579   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
580
581   // ARM does not have i1 sign extending load.
582   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
583
584   // ARM supports all 4 flavors of integer indexed load / store.
585   if (!Subtarget->isThumb1Only()) {
586     for (unsigned im = (unsigned)ISD::PRE_INC;
587          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
588       setIndexedLoadAction(im,  MVT::i1,  Legal);
589       setIndexedLoadAction(im,  MVT::i8,  Legal);
590       setIndexedLoadAction(im,  MVT::i16, Legal);
591       setIndexedLoadAction(im,  MVT::i32, Legal);
592       setIndexedStoreAction(im, MVT::i1,  Legal);
593       setIndexedStoreAction(im, MVT::i8,  Legal);
594       setIndexedStoreAction(im, MVT::i16, Legal);
595       setIndexedStoreAction(im, MVT::i32, Legal);
596     }
597   }
598
599   // i64 operation support.
600   setOperationAction(ISD::MUL,     MVT::i64, Expand);
601   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
602   if (Subtarget->isThumb1Only()) {
603     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
604     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
605   }
606   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
607       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
608     setOperationAction(ISD::MULHS, MVT::i32, Expand);
609
610   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
611   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
612   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
613   setOperationAction(ISD::SRL,       MVT::i64, Custom);
614   setOperationAction(ISD::SRA,       MVT::i64, Custom);
615
616   if (!Subtarget->isThumb1Only()) {
617     // FIXME: We should do this for Thumb1 as well.
618     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
619     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
620     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
621     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
622   }
623
624   // ARM does not have ROTL.
625   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
626   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
627   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
628   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
629     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
630
631   // These just redirect to CTTZ and CTLZ on ARM.
632   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
633   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
634
635   // Only ARMv6 has BSWAP.
636   if (!Subtarget->hasV6Ops())
637     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
638
639   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
640       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
641     // These are expanded into libcalls if the cpu doesn't have HW divider.
642     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
643     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
644   }
645   setOperationAction(ISD::SREM,  MVT::i32, Expand);
646   setOperationAction(ISD::UREM,  MVT::i32, Expand);
647   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
648   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
649
650   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
651   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
652   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
653   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
654   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
655
656   setOperationAction(ISD::TRAP, MVT::Other, Legal);
657
658   // Use the default implementation.
659   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
660   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
661   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
662   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
663   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
664   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
665
666   if (!Subtarget->isTargetDarwin()) {
667     // Non-Darwin platforms may return values in these registers via the
668     // personality function.
669     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
670     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
671     setExceptionPointerRegister(ARM::R0);
672     setExceptionSelectorRegister(ARM::R1);
673   }
674
675   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
676   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
677   // the default expansion.
678   // FIXME: This should be checking for v6k, not just v6.
679   if (Subtarget->hasDataBarrier() ||
680       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
681     // membarrier needs custom lowering; the rest are legal and handled
682     // normally.
683     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
684     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
685     // Custom lowering for 64-bit ops
686     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
690     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
691     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
692     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
693     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
694     setInsertFencesForAtomic(true);
695   } else {
696     // Set them all for expansion, which will force libcalls.
697     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
698     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
699     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
710     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
711     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
712     // Unordered/Monotonic case.
713     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
714     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
715     // Since the libcalls include locking, fold in the fences
716     setShouldFoldAtomicFences(true);
717   }
718
719   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
720
721   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
722   if (!Subtarget->hasV6Ops()) {
723     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
725   }
726   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
727
728   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
729       !Subtarget->isThumb1Only()) {
730     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
731     // iff target supports vfp2.
732     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
733     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
734   }
735
736   // We want to custom lower some of our intrinsics.
737   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
738   if (Subtarget->isTargetDarwin()) {
739     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
740     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
741     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
742   }
743
744   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
745   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
746   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
747   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
748   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
749   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
750   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
751   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
752   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
753
754   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
755   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
756   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
757   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
758   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
759
760   // We don't support sin/cos/fmod/copysign/pow
761   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
762   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
763   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
764   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
765   setOperationAction(ISD::FREM,      MVT::f64, Expand);
766   setOperationAction(ISD::FREM,      MVT::f32, Expand);
767   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
768       !Subtarget->isThumb1Only()) {
769     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
770     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
771   }
772   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
773   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
774
775   if (!Subtarget->hasVFP4()) {
776     setOperationAction(ISD::FMA, MVT::f64, Expand);
777     setOperationAction(ISD::FMA, MVT::f32, Expand);
778   }
779
780   // Various VFP goodness
781   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
782     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
783     if (Subtarget->hasVFP2()) {
784       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
785       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
786       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
787       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
788     }
789     // Special handling for half-precision FP.
790     if (!Subtarget->hasFP16()) {
791       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
792       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
793     }
794   }
795
796   // We have target-specific dag combine patterns for the following nodes:
797   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
798   setTargetDAGCombine(ISD::ADD);
799   setTargetDAGCombine(ISD::SUB);
800   setTargetDAGCombine(ISD::MUL);
801   setTargetDAGCombine(ISD::AND);
802   setTargetDAGCombine(ISD::OR);
803   setTargetDAGCombine(ISD::XOR);
804
805   if (Subtarget->hasV6Ops())
806     setTargetDAGCombine(ISD::SRL);
807
808   setStackPointerRegisterToSaveRestore(ARM::SP);
809
810   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
811       !Subtarget->hasVFP2())
812     setSchedulingPreference(Sched::RegPressure);
813   else
814     setSchedulingPreference(Sched::Hybrid);
815
816   //// temporary - rewrite interface to use type
817   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
818   maxStoresPerMemset = 16;
819   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
820
821   // On ARM arguments smaller than 4 bytes are extended, so all arguments
822   // are at least 4 bytes aligned.
823   setMinStackArgumentAlignment(4);
824
825   benefitFromCodePlacementOpt = true;
826
827   // Prefer likely predicted branches to selects on out-of-order cores.
828   predictableSelectIsExpensive = Subtarget->isLikeA9();
829
830   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
831 }
832
833 // FIXME: It might make sense to define the representative register class as the
834 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
835 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
836 // SPR's representative would be DPR_VFP2. This should work well if register
837 // pressure tracking were modified such that a register use would increment the
838 // pressure of the register class's representative and all of it's super
839 // classes' representatives transitively. We have not implemented this because
840 // of the difficulty prior to coalescing of modeling operand register classes
841 // due to the common occurrence of cross class copies and subregister insertions
842 // and extractions.
843 std::pair<const TargetRegisterClass*, uint8_t>
844 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
845   const TargetRegisterClass *RRC = 0;
846   uint8_t Cost = 1;
847   switch (VT.getSimpleVT().SimpleTy) {
848   default:
849     return TargetLowering::findRepresentativeClass(VT);
850   // Use DPR as representative register class for all floating point
851   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
852   // the cost is 1 for both f32 and f64.
853   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
854   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
855     RRC = &ARM::DPRRegClass;
856     // When NEON is used for SP, only half of the register file is available
857     // because operations that define both SP and DP results will be constrained
858     // to the VFP2 class (D0-D15). We currently model this constraint prior to
859     // coalescing by double-counting the SP regs. See the FIXME above.
860     if (Subtarget->useNEONForSinglePrecisionFP())
861       Cost = 2;
862     break;
863   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
864   case MVT::v4f32: case MVT::v2f64:
865     RRC = &ARM::DPRRegClass;
866     Cost = 2;
867     break;
868   case MVT::v4i64:
869     RRC = &ARM::DPRRegClass;
870     Cost = 4;
871     break;
872   case MVT::v8i64:
873     RRC = &ARM::DPRRegClass;
874     Cost = 8;
875     break;
876   }
877   return std::make_pair(RRC, Cost);
878 }
879
880 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
881   switch (Opcode) {
882   default: return 0;
883   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
884   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
885   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
886   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
887   case ARMISD::CALL:          return "ARMISD::CALL";
888   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
889   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
890   case ARMISD::tCALL:         return "ARMISD::tCALL";
891   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
892   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
893   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
894   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
895   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
896   case ARMISD::CMP:           return "ARMISD::CMP";
897   case ARMISD::CMN:           return "ARMISD::CMN";
898   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
899   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
900   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
901   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
902   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
903
904   case ARMISD::CMOV:          return "ARMISD::CMOV";
905
906   case ARMISD::RBIT:          return "ARMISD::RBIT";
907
908   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
909   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
910   case ARMISD::SITOF:         return "ARMISD::SITOF";
911   case ARMISD::UITOF:         return "ARMISD::UITOF";
912
913   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
914   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
915   case ARMISD::RRX:           return "ARMISD::RRX";
916
917   case ARMISD::ADDC:          return "ARMISD::ADDC";
918   case ARMISD::ADDE:          return "ARMISD::ADDE";
919   case ARMISD::SUBC:          return "ARMISD::SUBC";
920   case ARMISD::SUBE:          return "ARMISD::SUBE";
921
922   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
923   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
924
925   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
926   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
927
928   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
929
930   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
931
932   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
933
934   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
935   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
936
937   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
938
939   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
940   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
941   case ARMISD::VCGE:          return "ARMISD::VCGE";
942   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
943   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
944   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
945   case ARMISD::VCGT:          return "ARMISD::VCGT";
946   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
947   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
948   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
949   case ARMISD::VTST:          return "ARMISD::VTST";
950
951   case ARMISD::VSHL:          return "ARMISD::VSHL";
952   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
953   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
954   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
955   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
956   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
957   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
958   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
959   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
960   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
961   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
962   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
963   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
964   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
965   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
966   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
967   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
968   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
969   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
970   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
971   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
972   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
973   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
974   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
975   case ARMISD::VDUP:          return "ARMISD::VDUP";
976   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
977   case ARMISD::VEXT:          return "ARMISD::VEXT";
978   case ARMISD::VREV64:        return "ARMISD::VREV64";
979   case ARMISD::VREV32:        return "ARMISD::VREV32";
980   case ARMISD::VREV16:        return "ARMISD::VREV16";
981   case ARMISD::VZIP:          return "ARMISD::VZIP";
982   case ARMISD::VUZP:          return "ARMISD::VUZP";
983   case ARMISD::VTRN:          return "ARMISD::VTRN";
984   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
985   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
986   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
987   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
988   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
989   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
990   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
991   case ARMISD::FMAX:          return "ARMISD::FMAX";
992   case ARMISD::FMIN:          return "ARMISD::FMIN";
993   case ARMISD::BFI:           return "ARMISD::BFI";
994   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
995   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
996   case ARMISD::VBSL:          return "ARMISD::VBSL";
997   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
998   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
999   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1000   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1001   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1002   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1003   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1004   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1005   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1006   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1007   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1008   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1009   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1010   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1011   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1012   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1013   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1014   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1015   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1016   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1017   }
1018 }
1019
1020 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1021   if (!VT.isVector()) return getPointerTy();
1022   return VT.changeVectorElementTypeToInteger();
1023 }
1024
1025 /// getRegClassFor - Return the register class that should be used for the
1026 /// specified value type.
1027 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1028   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1029   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1030   // load / store 4 to 8 consecutive D registers.
1031   if (Subtarget->hasNEON()) {
1032     if (VT == MVT::v4i64)
1033       return &ARM::QQPRRegClass;
1034     if (VT == MVT::v8i64)
1035       return &ARM::QQQQPRRegClass;
1036   }
1037   return TargetLowering::getRegClassFor(VT);
1038 }
1039
1040 // Create a fast isel object.
1041 FastISel *
1042 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1043                                   const TargetLibraryInfo *libInfo) const {
1044   return ARM::createFastISel(funcInfo, libInfo);
1045 }
1046
1047 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1048 /// be used for loads / stores from the global.
1049 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1050   return (Subtarget->isThumb1Only() ? 127 : 4095);
1051 }
1052
1053 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1054   unsigned NumVals = N->getNumValues();
1055   if (!NumVals)
1056     return Sched::RegPressure;
1057
1058   for (unsigned i = 0; i != NumVals; ++i) {
1059     EVT VT = N->getValueType(i);
1060     if (VT == MVT::Glue || VT == MVT::Other)
1061       continue;
1062     if (VT.isFloatingPoint() || VT.isVector())
1063       return Sched::ILP;
1064   }
1065
1066   if (!N->isMachineOpcode())
1067     return Sched::RegPressure;
1068
1069   // Load are scheduled for latency even if there instruction itinerary
1070   // is not available.
1071   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1072   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1073
1074   if (MCID.getNumDefs() == 0)
1075     return Sched::RegPressure;
1076   if (!Itins->isEmpty() &&
1077       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1078     return Sched::ILP;
1079
1080   return Sched::RegPressure;
1081 }
1082
1083 //===----------------------------------------------------------------------===//
1084 // Lowering Code
1085 //===----------------------------------------------------------------------===//
1086
1087 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1088 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1089   switch (CC) {
1090   default: llvm_unreachable("Unknown condition code!");
1091   case ISD::SETNE:  return ARMCC::NE;
1092   case ISD::SETEQ:  return ARMCC::EQ;
1093   case ISD::SETGT:  return ARMCC::GT;
1094   case ISD::SETGE:  return ARMCC::GE;
1095   case ISD::SETLT:  return ARMCC::LT;
1096   case ISD::SETLE:  return ARMCC::LE;
1097   case ISD::SETUGT: return ARMCC::HI;
1098   case ISD::SETUGE: return ARMCC::HS;
1099   case ISD::SETULT: return ARMCC::LO;
1100   case ISD::SETULE: return ARMCC::LS;
1101   }
1102 }
1103
1104 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1105 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1106                         ARMCC::CondCodes &CondCode2) {
1107   CondCode2 = ARMCC::AL;
1108   switch (CC) {
1109   default: llvm_unreachable("Unknown FP condition!");
1110   case ISD::SETEQ:
1111   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1112   case ISD::SETGT:
1113   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1114   case ISD::SETGE:
1115   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1116   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1117   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1118   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1119   case ISD::SETO:   CondCode = ARMCC::VC; break;
1120   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1121   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1122   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1123   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1124   case ISD::SETLT:
1125   case ISD::SETULT: CondCode = ARMCC::LT; break;
1126   case ISD::SETLE:
1127   case ISD::SETULE: CondCode = ARMCC::LE; break;
1128   case ISD::SETNE:
1129   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1130   }
1131 }
1132
1133 //===----------------------------------------------------------------------===//
1134 //                      Calling Convention Implementation
1135 //===----------------------------------------------------------------------===//
1136
1137 #include "ARMGenCallingConv.inc"
1138
1139 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1140 /// given CallingConvention value.
1141 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1142                                                  bool Return,
1143                                                  bool isVarArg) const {
1144   switch (CC) {
1145   default:
1146     llvm_unreachable("Unsupported calling convention");
1147   case CallingConv::Fast:
1148     if (Subtarget->hasVFP2() && !isVarArg) {
1149       if (!Subtarget->isAAPCS_ABI())
1150         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1151       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1152       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1153     }
1154     // Fallthrough
1155   case CallingConv::C: {
1156     // Use target triple & subtarget features to do actual dispatch.
1157     if (!Subtarget->isAAPCS_ABI())
1158       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1159     else if (Subtarget->hasVFP2() &&
1160              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1161              !isVarArg)
1162       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1163     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1164   }
1165   case CallingConv::ARM_AAPCS_VFP:
1166     if (!isVarArg)
1167       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1168     // Fallthrough
1169   case CallingConv::ARM_AAPCS:
1170     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1171   case CallingConv::ARM_APCS:
1172     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1173   case CallingConv::GHC:
1174     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1175   }
1176 }
1177
1178 /// LowerCallResult - Lower the result values of a call into the
1179 /// appropriate copies out of appropriate physical registers.
1180 SDValue
1181 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1182                                    CallingConv::ID CallConv, bool isVarArg,
1183                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1184                                    DebugLoc dl, SelectionDAG &DAG,
1185                                    SmallVectorImpl<SDValue> &InVals) const {
1186
1187   // Assign locations to each value returned by this call.
1188   SmallVector<CCValAssign, 16> RVLocs;
1189   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1190                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1191   CCInfo.AnalyzeCallResult(Ins,
1192                            CCAssignFnForNode(CallConv, /* Return*/ true,
1193                                              isVarArg));
1194
1195   // Copy all of the result registers out of their specified physreg.
1196   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1197     CCValAssign VA = RVLocs[i];
1198
1199     SDValue Val;
1200     if (VA.needsCustom()) {
1201       // Handle f64 or half of a v2f64.
1202       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1203                                       InFlag);
1204       Chain = Lo.getValue(1);
1205       InFlag = Lo.getValue(2);
1206       VA = RVLocs[++i]; // skip ahead to next loc
1207       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1208                                       InFlag);
1209       Chain = Hi.getValue(1);
1210       InFlag = Hi.getValue(2);
1211       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1212
1213       if (VA.getLocVT() == MVT::v2f64) {
1214         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1215         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1216                           DAG.getConstant(0, MVT::i32));
1217
1218         VA = RVLocs[++i]; // skip ahead to next loc
1219         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1220         Chain = Lo.getValue(1);
1221         InFlag = Lo.getValue(2);
1222         VA = RVLocs[++i]; // skip ahead to next loc
1223         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1224         Chain = Hi.getValue(1);
1225         InFlag = Hi.getValue(2);
1226         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1227         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1228                           DAG.getConstant(1, MVT::i32));
1229       }
1230     } else {
1231       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1232                                InFlag);
1233       Chain = Val.getValue(1);
1234       InFlag = Val.getValue(2);
1235     }
1236
1237     switch (VA.getLocInfo()) {
1238     default: llvm_unreachable("Unknown loc info!");
1239     case CCValAssign::Full: break;
1240     case CCValAssign::BCvt:
1241       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1242       break;
1243     }
1244
1245     InVals.push_back(Val);
1246   }
1247
1248   return Chain;
1249 }
1250
1251 /// LowerMemOpCallTo - Store the argument to the stack.
1252 SDValue
1253 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1254                                     SDValue StackPtr, SDValue Arg,
1255                                     DebugLoc dl, SelectionDAG &DAG,
1256                                     const CCValAssign &VA,
1257                                     ISD::ArgFlagsTy Flags) const {
1258   unsigned LocMemOffset = VA.getLocMemOffset();
1259   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1260   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1261   return DAG.getStore(Chain, dl, Arg, PtrOff,
1262                       MachinePointerInfo::getStack(LocMemOffset),
1263                       false, false, 0);
1264 }
1265
1266 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1267                                          SDValue Chain, SDValue &Arg,
1268                                          RegsToPassVector &RegsToPass,
1269                                          CCValAssign &VA, CCValAssign &NextVA,
1270                                          SDValue &StackPtr,
1271                                          SmallVector<SDValue, 8> &MemOpChains,
1272                                          ISD::ArgFlagsTy Flags) const {
1273
1274   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1275                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1276   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1277
1278   if (NextVA.isRegLoc())
1279     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1280   else {
1281     assert(NextVA.isMemLoc());
1282     if (StackPtr.getNode() == 0)
1283       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1284
1285     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1286                                            dl, DAG, NextVA,
1287                                            Flags));
1288   }
1289 }
1290
1291 /// LowerCall - Lowering a call into a callseq_start <-
1292 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1293 /// nodes.
1294 SDValue
1295 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1296                              SmallVectorImpl<SDValue> &InVals) const {
1297   SelectionDAG &DAG                     = CLI.DAG;
1298   DebugLoc &dl                          = CLI.DL;
1299   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1300   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1301   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1302   SDValue Chain                         = CLI.Chain;
1303   SDValue Callee                        = CLI.Callee;
1304   bool &isTailCall                      = CLI.IsTailCall;
1305   CallingConv::ID CallConv              = CLI.CallConv;
1306   bool doesNotRet                       = CLI.DoesNotReturn;
1307   bool isVarArg                         = CLI.IsVarArg;
1308
1309   MachineFunction &MF = DAG.getMachineFunction();
1310   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1311   bool IsSibCall = false;
1312   // Disable tail calls if they're not supported.
1313   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1314     isTailCall = false;
1315   if (isTailCall) {
1316     // Check if it's really possible to do a tail call.
1317     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1318                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1319                                                    Outs, OutVals, Ins, DAG);
1320     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1321     // detected sibcalls.
1322     if (isTailCall) {
1323       ++NumTailCalls;
1324       IsSibCall = true;
1325     }
1326   }
1327
1328   // Analyze operands of the call, assigning locations to each operand.
1329   SmallVector<CCValAssign, 16> ArgLocs;
1330   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1331                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1332   CCInfo.AnalyzeCallOperands(Outs,
1333                              CCAssignFnForNode(CallConv, /* Return*/ false,
1334                                                isVarArg));
1335
1336   // Get a count of how many bytes are to be pushed on the stack.
1337   unsigned NumBytes = CCInfo.getNextStackOffset();
1338
1339   // For tail calls, memory operands are available in our caller's stack.
1340   if (IsSibCall)
1341     NumBytes = 0;
1342
1343   // Adjust the stack pointer for the new arguments...
1344   // These operations are automatically eliminated by the prolog/epilog pass
1345   if (!IsSibCall)
1346     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1347
1348   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1349
1350   RegsToPassVector RegsToPass;
1351   SmallVector<SDValue, 8> MemOpChains;
1352
1353   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1354   // of tail call optimization, arguments are handled later.
1355   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1356        i != e;
1357        ++i, ++realArgIdx) {
1358     CCValAssign &VA = ArgLocs[i];
1359     SDValue Arg = OutVals[realArgIdx];
1360     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1361     bool isByVal = Flags.isByVal();
1362
1363     // Promote the value if needed.
1364     switch (VA.getLocInfo()) {
1365     default: llvm_unreachable("Unknown loc info!");
1366     case CCValAssign::Full: break;
1367     case CCValAssign::SExt:
1368       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1369       break;
1370     case CCValAssign::ZExt:
1371       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1372       break;
1373     case CCValAssign::AExt:
1374       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1375       break;
1376     case CCValAssign::BCvt:
1377       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1378       break;
1379     }
1380
1381     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1382     if (VA.needsCustom()) {
1383       if (VA.getLocVT() == MVT::v2f64) {
1384         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1385                                   DAG.getConstant(0, MVT::i32));
1386         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1387                                   DAG.getConstant(1, MVT::i32));
1388
1389         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1390                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1391
1392         VA = ArgLocs[++i]; // skip ahead to next loc
1393         if (VA.isRegLoc()) {
1394           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1395                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1396         } else {
1397           assert(VA.isMemLoc());
1398
1399           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1400                                                  dl, DAG, VA, Flags));
1401         }
1402       } else {
1403         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1404                          StackPtr, MemOpChains, Flags);
1405       }
1406     } else if (VA.isRegLoc()) {
1407       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1408     } else if (isByVal) {
1409       assert(VA.isMemLoc());
1410       unsigned offset = 0;
1411
1412       // True if this byval aggregate will be split between registers
1413       // and memory.
1414       if (CCInfo.isFirstByValRegValid()) {
1415         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1416         unsigned int i, j;
1417         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1418           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1419           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1420           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1421                                      MachinePointerInfo(),
1422                                      false, false, false, 0);
1423           MemOpChains.push_back(Load.getValue(1));
1424           RegsToPass.push_back(std::make_pair(j, Load));
1425         }
1426         offset = ARM::R4 - CCInfo.getFirstByValReg();
1427         CCInfo.clearFirstByValReg();
1428       }
1429
1430       if (Flags.getByValSize() - 4*offset > 0) {
1431         unsigned LocMemOffset = VA.getLocMemOffset();
1432         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1433         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1434                                   StkPtrOff);
1435         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1436         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1437         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1438                                            MVT::i32);
1439         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1440
1441         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1442         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1443         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1444                                           Ops, array_lengthof(Ops)));
1445       }
1446     } else if (!IsSibCall) {
1447       assert(VA.isMemLoc());
1448
1449       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1450                                              dl, DAG, VA, Flags));
1451     }
1452   }
1453
1454   if (!MemOpChains.empty())
1455     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1456                         &MemOpChains[0], MemOpChains.size());
1457
1458   // Build a sequence of copy-to-reg nodes chained together with token chain
1459   // and flag operands which copy the outgoing args into the appropriate regs.
1460   SDValue InFlag;
1461   // Tail call byval lowering might overwrite argument registers so in case of
1462   // tail call optimization the copies to registers are lowered later.
1463   if (!isTailCall)
1464     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1465       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1466                                RegsToPass[i].second, InFlag);
1467       InFlag = Chain.getValue(1);
1468     }
1469
1470   // For tail calls lower the arguments to the 'real' stack slot.
1471   if (isTailCall) {
1472     // Force all the incoming stack arguments to be loaded from the stack
1473     // before any new outgoing arguments are stored to the stack, because the
1474     // outgoing stack slots may alias the incoming argument stack slots, and
1475     // the alias isn't otherwise explicit. This is slightly more conservative
1476     // than necessary, because it means that each store effectively depends
1477     // on every argument instead of just those arguments it would clobber.
1478
1479     // Do not flag preceding copytoreg stuff together with the following stuff.
1480     InFlag = SDValue();
1481     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1482       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1483                                RegsToPass[i].second, InFlag);
1484       InFlag = Chain.getValue(1);
1485     }
1486     InFlag =SDValue();
1487   }
1488
1489   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1490   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1491   // node so that legalize doesn't hack it.
1492   bool isDirect = false;
1493   bool isARMFunc = false;
1494   bool isLocalARMFunc = false;
1495   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1496
1497   if (EnableARMLongCalls) {
1498     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1499             && "long-calls with non-static relocation model!");
1500     // Handle a global address or an external symbol. If it's not one of
1501     // those, the target's already in a register, so we don't need to do
1502     // anything extra.
1503     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1504       const GlobalValue *GV = G->getGlobal();
1505       // Create a constant pool entry for the callee address
1506       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1507       ARMConstantPoolValue *CPV =
1508         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1509
1510       // Get the address of the callee into a register
1511       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1512       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1513       Callee = DAG.getLoad(getPointerTy(), dl,
1514                            DAG.getEntryNode(), CPAddr,
1515                            MachinePointerInfo::getConstantPool(),
1516                            false, false, false, 0);
1517     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1518       const char *Sym = S->getSymbol();
1519
1520       // Create a constant pool entry for the callee address
1521       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1522       ARMConstantPoolValue *CPV =
1523         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1524                                       ARMPCLabelIndex, 0);
1525       // Get the address of the callee into a register
1526       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1527       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1528       Callee = DAG.getLoad(getPointerTy(), dl,
1529                            DAG.getEntryNode(), CPAddr,
1530                            MachinePointerInfo::getConstantPool(),
1531                            false, false, false, 0);
1532     }
1533   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1534     const GlobalValue *GV = G->getGlobal();
1535     isDirect = true;
1536     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1537     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1538                    getTargetMachine().getRelocationModel() != Reloc::Static;
1539     isARMFunc = !Subtarget->isThumb() || isStub;
1540     // ARM call to a local ARM function is predicable.
1541     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1542     // tBX takes a register source operand.
1543     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1544       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1545       ARMConstantPoolValue *CPV =
1546         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1547       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1548       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1549       Callee = DAG.getLoad(getPointerTy(), dl,
1550                            DAG.getEntryNode(), CPAddr,
1551                            MachinePointerInfo::getConstantPool(),
1552                            false, false, false, 0);
1553       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1554       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1555                            getPointerTy(), Callee, PICLabel);
1556     } else {
1557       // On ELF targets for PIC code, direct calls should go through the PLT
1558       unsigned OpFlags = 0;
1559       if (Subtarget->isTargetELF() &&
1560                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1561         OpFlags = ARMII::MO_PLT;
1562       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1563     }
1564   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1565     isDirect = true;
1566     bool isStub = Subtarget->isTargetDarwin() &&
1567                   getTargetMachine().getRelocationModel() != Reloc::Static;
1568     isARMFunc = !Subtarget->isThumb() || isStub;
1569     // tBX takes a register source operand.
1570     const char *Sym = S->getSymbol();
1571     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1572       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1573       ARMConstantPoolValue *CPV =
1574         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1575                                       ARMPCLabelIndex, 4);
1576       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1577       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1578       Callee = DAG.getLoad(getPointerTy(), dl,
1579                            DAG.getEntryNode(), CPAddr,
1580                            MachinePointerInfo::getConstantPool(),
1581                            false, false, false, 0);
1582       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1583       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1584                            getPointerTy(), Callee, PICLabel);
1585     } else {
1586       unsigned OpFlags = 0;
1587       // On ELF targets for PIC code, direct calls should go through the PLT
1588       if (Subtarget->isTargetELF() &&
1589                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1590         OpFlags = ARMII::MO_PLT;
1591       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1592     }
1593   }
1594
1595   // FIXME: handle tail calls differently.
1596   unsigned CallOpc;
1597   bool HasMinSizeAttr = MF.getFunction()->getFnAttributes().
1598     hasAttribute(Attributes::MinSize);
1599   if (Subtarget->isThumb()) {
1600     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1601       CallOpc = ARMISD::CALL_NOLINK;
1602     else if (doesNotRet && isDirect && !isARMFunc &&
1603              Subtarget->hasRAS() && !Subtarget->isThumb1Only() &&
1604              // Emit regular call when code size is the priority
1605              !HasMinSizeAttr)
1606       // "mov lr, pc; b _foo" to avoid confusing the RSP
1607       CallOpc = ARMISD::CALL_NOLINK;
1608     else
1609       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1610   } else {
1611     if (!isDirect && !Subtarget->hasV5TOps()) {
1612       CallOpc = ARMISD::CALL_NOLINK;
1613     } else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1614                // Emit regular call when code size is the priority
1615                !HasMinSizeAttr)
1616       // "mov lr, pc; b _foo" to avoid confusing the RSP
1617       CallOpc = ARMISD::CALL_NOLINK;
1618     else
1619       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1620   }
1621
1622   std::vector<SDValue> Ops;
1623   Ops.push_back(Chain);
1624   Ops.push_back(Callee);
1625
1626   // Add argument registers to the end of the list so that they are known live
1627   // into the call.
1628   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1629     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1630                                   RegsToPass[i].second.getValueType()));
1631
1632   // Add a register mask operand representing the call-preserved registers.
1633   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1634   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1635   assert(Mask && "Missing call preserved mask for calling convention");
1636   Ops.push_back(DAG.getRegisterMask(Mask));
1637
1638   if (InFlag.getNode())
1639     Ops.push_back(InFlag);
1640
1641   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1642   if (isTailCall)
1643     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1644
1645   // Returns a chain and a flag for retval copy to use.
1646   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1647   InFlag = Chain.getValue(1);
1648
1649   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1650                              DAG.getIntPtrConstant(0, true), InFlag);
1651   if (!Ins.empty())
1652     InFlag = Chain.getValue(1);
1653
1654   // Handle result values, copying them out of physregs into vregs that we
1655   // return.
1656   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1657                          dl, DAG, InVals);
1658 }
1659
1660 /// HandleByVal - Every parameter *after* a byval parameter is passed
1661 /// on the stack.  Remember the next parameter register to allocate,
1662 /// and then confiscate the rest of the parameter registers to insure
1663 /// this.
1664 void
1665 ARMTargetLowering::HandleByVal(
1666     CCState *State, unsigned &size, unsigned Align) const {
1667   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1668   assert((State->getCallOrPrologue() == Prologue ||
1669           State->getCallOrPrologue() == Call) &&
1670          "unhandled ParmContext");
1671   if ((!State->isFirstByValRegValid()) &&
1672       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1673     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1674       unsigned AlignInRegs = Align / 4;
1675       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1676       for (unsigned i = 0; i < Waste; ++i)
1677         reg = State->AllocateReg(GPRArgRegs, 4);
1678     }
1679     if (reg != 0) {
1680       State->setFirstByValReg(reg);
1681       // At a call site, a byval parameter that is split between
1682       // registers and memory needs its size truncated here.  In a
1683       // function prologue, such byval parameters are reassembled in
1684       // memory, and are not truncated.
1685       if (State->getCallOrPrologue() == Call) {
1686         unsigned excess = 4 * (ARM::R4 - reg);
1687         assert(size >= excess && "expected larger existing stack allocation");
1688         size -= excess;
1689       }
1690     }
1691   }
1692   // Confiscate any remaining parameter registers to preclude their
1693   // assignment to subsequent parameters.
1694   while (State->AllocateReg(GPRArgRegs, 4))
1695     ;
1696 }
1697
1698 /// MatchingStackOffset - Return true if the given stack call argument is
1699 /// already available in the same position (relatively) of the caller's
1700 /// incoming argument stack.
1701 static
1702 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1703                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1704                          const TargetInstrInfo *TII) {
1705   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1706   int FI = INT_MAX;
1707   if (Arg.getOpcode() == ISD::CopyFromReg) {
1708     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1709     if (!TargetRegisterInfo::isVirtualRegister(VR))
1710       return false;
1711     MachineInstr *Def = MRI->getVRegDef(VR);
1712     if (!Def)
1713       return false;
1714     if (!Flags.isByVal()) {
1715       if (!TII->isLoadFromStackSlot(Def, FI))
1716         return false;
1717     } else {
1718       return false;
1719     }
1720   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1721     if (Flags.isByVal())
1722       // ByVal argument is passed in as a pointer but it's now being
1723       // dereferenced. e.g.
1724       // define @foo(%struct.X* %A) {
1725       //   tail call @bar(%struct.X* byval %A)
1726       // }
1727       return false;
1728     SDValue Ptr = Ld->getBasePtr();
1729     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1730     if (!FINode)
1731       return false;
1732     FI = FINode->getIndex();
1733   } else
1734     return false;
1735
1736   assert(FI != INT_MAX);
1737   if (!MFI->isFixedObjectIndex(FI))
1738     return false;
1739   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1740 }
1741
1742 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1743 /// for tail call optimization. Targets which want to do tail call
1744 /// optimization should implement this function.
1745 bool
1746 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1747                                                      CallingConv::ID CalleeCC,
1748                                                      bool isVarArg,
1749                                                      bool isCalleeStructRet,
1750                                                      bool isCallerStructRet,
1751                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1752                                     const SmallVectorImpl<SDValue> &OutVals,
1753                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1754                                                      SelectionDAG& DAG) const {
1755   const Function *CallerF = DAG.getMachineFunction().getFunction();
1756   CallingConv::ID CallerCC = CallerF->getCallingConv();
1757   bool CCMatch = CallerCC == CalleeCC;
1758
1759   // Look for obvious safe cases to perform tail call optimization that do not
1760   // require ABI changes. This is what gcc calls sibcall.
1761
1762   // Do not sibcall optimize vararg calls unless the call site is not passing
1763   // any arguments.
1764   if (isVarArg && !Outs.empty())
1765     return false;
1766
1767   // Also avoid sibcall optimization if either caller or callee uses struct
1768   // return semantics.
1769   if (isCalleeStructRet || isCallerStructRet)
1770     return false;
1771
1772   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1773   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1774   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1775   // support in the assembler and linker to be used. This would need to be
1776   // fixed to fully support tail calls in Thumb1.
1777   //
1778   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1779   // LR.  This means if we need to reload LR, it takes an extra instructions,
1780   // which outweighs the value of the tail call; but here we don't know yet
1781   // whether LR is going to be used.  Probably the right approach is to
1782   // generate the tail call here and turn it back into CALL/RET in
1783   // emitEpilogue if LR is used.
1784
1785   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1786   // but we need to make sure there are enough registers; the only valid
1787   // registers are the 4 used for parameters.  We don't currently do this
1788   // case.
1789   if (Subtarget->isThumb1Only())
1790     return false;
1791
1792   // If the calling conventions do not match, then we'd better make sure the
1793   // results are returned in the same way as what the caller expects.
1794   if (!CCMatch) {
1795     SmallVector<CCValAssign, 16> RVLocs1;
1796     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1797                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1798     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1799
1800     SmallVector<CCValAssign, 16> RVLocs2;
1801     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1802                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1803     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1804
1805     if (RVLocs1.size() != RVLocs2.size())
1806       return false;
1807     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1808       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1809         return false;
1810       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1811         return false;
1812       if (RVLocs1[i].isRegLoc()) {
1813         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1814           return false;
1815       } else {
1816         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1817           return false;
1818       }
1819     }
1820   }
1821
1822   // If Caller's vararg or byval argument has been split between registers and
1823   // stack, do not perform tail call, since part of the argument is in caller's
1824   // local frame.
1825   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1826                                       getInfo<ARMFunctionInfo>();
1827   if (AFI_Caller->getVarArgsRegSaveSize())
1828     return false;
1829
1830   // If the callee takes no arguments then go on to check the results of the
1831   // call.
1832   if (!Outs.empty()) {
1833     // Check if stack adjustment is needed. For now, do not do this if any
1834     // argument is passed on the stack.
1835     SmallVector<CCValAssign, 16> ArgLocs;
1836     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1837                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1838     CCInfo.AnalyzeCallOperands(Outs,
1839                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1840     if (CCInfo.getNextStackOffset()) {
1841       MachineFunction &MF = DAG.getMachineFunction();
1842
1843       // Check if the arguments are already laid out in the right way as
1844       // the caller's fixed stack objects.
1845       MachineFrameInfo *MFI = MF.getFrameInfo();
1846       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1847       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1848       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1849            i != e;
1850            ++i, ++realArgIdx) {
1851         CCValAssign &VA = ArgLocs[i];
1852         EVT RegVT = VA.getLocVT();
1853         SDValue Arg = OutVals[realArgIdx];
1854         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1855         if (VA.getLocInfo() == CCValAssign::Indirect)
1856           return false;
1857         if (VA.needsCustom()) {
1858           // f64 and vector types are split into multiple registers or
1859           // register/stack-slot combinations.  The types will not match
1860           // the registers; give up on memory f64 refs until we figure
1861           // out what to do about this.
1862           if (!VA.isRegLoc())
1863             return false;
1864           if (!ArgLocs[++i].isRegLoc())
1865             return false;
1866           if (RegVT == MVT::v2f64) {
1867             if (!ArgLocs[++i].isRegLoc())
1868               return false;
1869             if (!ArgLocs[++i].isRegLoc())
1870               return false;
1871           }
1872         } else if (!VA.isRegLoc()) {
1873           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1874                                    MFI, MRI, TII))
1875             return false;
1876         }
1877       }
1878     }
1879   }
1880
1881   return true;
1882 }
1883
1884 SDValue
1885 ARMTargetLowering::LowerReturn(SDValue Chain,
1886                                CallingConv::ID CallConv, bool isVarArg,
1887                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1888                                const SmallVectorImpl<SDValue> &OutVals,
1889                                DebugLoc dl, SelectionDAG &DAG) const {
1890
1891   // CCValAssign - represent the assignment of the return value to a location.
1892   SmallVector<CCValAssign, 16> RVLocs;
1893
1894   // CCState - Info about the registers and stack slots.
1895   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1896                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1897
1898   // Analyze outgoing return values.
1899   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1900                                                isVarArg));
1901
1902   // If this is the first return lowered for this function, add
1903   // the regs to the liveout set for the function.
1904   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1905     for (unsigned i = 0; i != RVLocs.size(); ++i)
1906       if (RVLocs[i].isRegLoc())
1907         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1908   }
1909
1910   SDValue Flag;
1911
1912   // Copy the result values into the output registers.
1913   for (unsigned i = 0, realRVLocIdx = 0;
1914        i != RVLocs.size();
1915        ++i, ++realRVLocIdx) {
1916     CCValAssign &VA = RVLocs[i];
1917     assert(VA.isRegLoc() && "Can only return in registers!");
1918
1919     SDValue Arg = OutVals[realRVLocIdx];
1920
1921     switch (VA.getLocInfo()) {
1922     default: llvm_unreachable("Unknown loc info!");
1923     case CCValAssign::Full: break;
1924     case CCValAssign::BCvt:
1925       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1926       break;
1927     }
1928
1929     if (VA.needsCustom()) {
1930       if (VA.getLocVT() == MVT::v2f64) {
1931         // Extract the first half and return it in two registers.
1932         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1933                                    DAG.getConstant(0, MVT::i32));
1934         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1935                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1936
1937         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1938         Flag = Chain.getValue(1);
1939         VA = RVLocs[++i]; // skip ahead to next loc
1940         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1941                                  HalfGPRs.getValue(1), Flag);
1942         Flag = Chain.getValue(1);
1943         VA = RVLocs[++i]; // skip ahead to next loc
1944
1945         // Extract the 2nd half and fall through to handle it as an f64 value.
1946         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1947                           DAG.getConstant(1, MVT::i32));
1948       }
1949       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1950       // available.
1951       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1952                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1953       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1954       Flag = Chain.getValue(1);
1955       VA = RVLocs[++i]; // skip ahead to next loc
1956       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1957                                Flag);
1958     } else
1959       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1960
1961     // Guarantee that all emitted copies are
1962     // stuck together, avoiding something bad.
1963     Flag = Chain.getValue(1);
1964   }
1965
1966   SDValue result;
1967   if (Flag.getNode())
1968     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1969   else // Return Void
1970     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1971
1972   return result;
1973 }
1974
1975 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1976   if (N->getNumValues() != 1)
1977     return false;
1978   if (!N->hasNUsesOfValue(1, 0))
1979     return false;
1980
1981   SDValue TCChain = Chain;
1982   SDNode *Copy = *N->use_begin();
1983   if (Copy->getOpcode() == ISD::CopyToReg) {
1984     // If the copy has a glue operand, we conservatively assume it isn't safe to
1985     // perform a tail call.
1986     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1987       return false;
1988     TCChain = Copy->getOperand(0);
1989   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1990     SDNode *VMov = Copy;
1991     // f64 returned in a pair of GPRs.
1992     SmallPtrSet<SDNode*, 2> Copies;
1993     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1994          UI != UE; ++UI) {
1995       if (UI->getOpcode() != ISD::CopyToReg)
1996         return false;
1997       Copies.insert(*UI);
1998     }
1999     if (Copies.size() > 2)
2000       return false;
2001
2002     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2003          UI != UE; ++UI) {
2004       SDValue UseChain = UI->getOperand(0);
2005       if (Copies.count(UseChain.getNode()))
2006         // Second CopyToReg
2007         Copy = *UI;
2008       else
2009         // First CopyToReg
2010         TCChain = UseChain;
2011     }
2012   } else if (Copy->getOpcode() == ISD::BITCAST) {
2013     // f32 returned in a single GPR.
2014     if (!Copy->hasOneUse())
2015       return false;
2016     Copy = *Copy->use_begin();
2017     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2018       return false;
2019     Chain = Copy->getOperand(0);
2020   } else {
2021     return false;
2022   }
2023
2024   bool HasRet = false;
2025   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2026        UI != UE; ++UI) {
2027     if (UI->getOpcode() != ARMISD::RET_FLAG)
2028       return false;
2029     HasRet = true;
2030   }
2031
2032   if (!HasRet)
2033     return false;
2034
2035   Chain = TCChain;
2036   return true;
2037 }
2038
2039 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2040   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2041     return false;
2042
2043   if (!CI->isTailCall())
2044     return false;
2045
2046   return !Subtarget->isThumb1Only();
2047 }
2048
2049 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2050 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2051 // one of the above mentioned nodes. It has to be wrapped because otherwise
2052 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2053 // be used to form addressing mode. These wrapped nodes will be selected
2054 // into MOVi.
2055 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2056   EVT PtrVT = Op.getValueType();
2057   // FIXME there is no actual debug info here
2058   DebugLoc dl = Op.getDebugLoc();
2059   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2060   SDValue Res;
2061   if (CP->isMachineConstantPoolEntry())
2062     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2063                                     CP->getAlignment());
2064   else
2065     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2066                                     CP->getAlignment());
2067   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2068 }
2069
2070 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2071   return MachineJumpTableInfo::EK_Inline;
2072 }
2073
2074 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2075                                              SelectionDAG &DAG) const {
2076   MachineFunction &MF = DAG.getMachineFunction();
2077   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2078   unsigned ARMPCLabelIndex = 0;
2079   DebugLoc DL = Op.getDebugLoc();
2080   EVT PtrVT = getPointerTy();
2081   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2082   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2083   SDValue CPAddr;
2084   if (RelocM == Reloc::Static) {
2085     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2086   } else {
2087     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2088     ARMPCLabelIndex = AFI->createPICLabelUId();
2089     ARMConstantPoolValue *CPV =
2090       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2091                                       ARMCP::CPBlockAddress, PCAdj);
2092     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2093   }
2094   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2095   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2096                                MachinePointerInfo::getConstantPool(),
2097                                false, false, false, 0);
2098   if (RelocM == Reloc::Static)
2099     return Result;
2100   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2101   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2102 }
2103
2104 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2105 SDValue
2106 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2107                                                  SelectionDAG &DAG) const {
2108   DebugLoc dl = GA->getDebugLoc();
2109   EVT PtrVT = getPointerTy();
2110   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2111   MachineFunction &MF = DAG.getMachineFunction();
2112   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2113   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2114   ARMConstantPoolValue *CPV =
2115     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2116                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2117   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2118   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2119   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2120                          MachinePointerInfo::getConstantPool(),
2121                          false, false, false, 0);
2122   SDValue Chain = Argument.getValue(1);
2123
2124   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2125   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2126
2127   // call __tls_get_addr.
2128   ArgListTy Args;
2129   ArgListEntry Entry;
2130   Entry.Node = Argument;
2131   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2132   Args.push_back(Entry);
2133   // FIXME: is there useful debug info available here?
2134   TargetLowering::CallLoweringInfo CLI(Chain,
2135                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2136                 false, false, false, false,
2137                 0, CallingConv::C, /*isTailCall=*/false,
2138                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2139                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2140   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2141   return CallResult.first;
2142 }
2143
2144 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2145 // "local exec" model.
2146 SDValue
2147 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2148                                         SelectionDAG &DAG,
2149                                         TLSModel::Model model) const {
2150   const GlobalValue *GV = GA->getGlobal();
2151   DebugLoc dl = GA->getDebugLoc();
2152   SDValue Offset;
2153   SDValue Chain = DAG.getEntryNode();
2154   EVT PtrVT = getPointerTy();
2155   // Get the Thread Pointer
2156   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2157
2158   if (model == TLSModel::InitialExec) {
2159     MachineFunction &MF = DAG.getMachineFunction();
2160     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2161     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2162     // Initial exec model.
2163     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2164     ARMConstantPoolValue *CPV =
2165       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2166                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2167                                       true);
2168     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2169     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2170     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2171                          MachinePointerInfo::getConstantPool(),
2172                          false, false, false, 0);
2173     Chain = Offset.getValue(1);
2174
2175     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2176     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2177
2178     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2179                          MachinePointerInfo::getConstantPool(),
2180                          false, false, false, 0);
2181   } else {
2182     // local exec model
2183     assert(model == TLSModel::LocalExec);
2184     ARMConstantPoolValue *CPV =
2185       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2186     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2187     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2188     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2189                          MachinePointerInfo::getConstantPool(),
2190                          false, false, false, 0);
2191   }
2192
2193   // The address of the thread local variable is the add of the thread
2194   // pointer with the offset of the variable.
2195   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2196 }
2197
2198 SDValue
2199 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2200   // TODO: implement the "local dynamic" model
2201   assert(Subtarget->isTargetELF() &&
2202          "TLS not implemented for non-ELF targets");
2203   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2204
2205   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2206
2207   switch (model) {
2208     case TLSModel::GeneralDynamic:
2209     case TLSModel::LocalDynamic:
2210       return LowerToTLSGeneralDynamicModel(GA, DAG);
2211     case TLSModel::InitialExec:
2212     case TLSModel::LocalExec:
2213       return LowerToTLSExecModels(GA, DAG, model);
2214   }
2215   llvm_unreachable("bogus TLS model");
2216 }
2217
2218 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2219                                                  SelectionDAG &DAG) const {
2220   EVT PtrVT = getPointerTy();
2221   DebugLoc dl = Op.getDebugLoc();
2222   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2223   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2224   if (RelocM == Reloc::PIC_) {
2225     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2226     ARMConstantPoolValue *CPV =
2227       ARMConstantPoolConstant::Create(GV,
2228                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2229     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2230     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2231     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2232                                  CPAddr,
2233                                  MachinePointerInfo::getConstantPool(),
2234                                  false, false, false, 0);
2235     SDValue Chain = Result.getValue(1);
2236     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2237     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2238     if (!UseGOTOFF)
2239       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2240                            MachinePointerInfo::getGOT(),
2241                            false, false, false, 0);
2242     return Result;
2243   }
2244
2245   // If we have T2 ops, we can materialize the address directly via movt/movw
2246   // pair. This is always cheaper.
2247   if (Subtarget->useMovt()) {
2248     ++NumMovwMovt;
2249     // FIXME: Once remat is capable of dealing with instructions with register
2250     // operands, expand this into two nodes.
2251     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2252                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2253   } else {
2254     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2255     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2256     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2257                        MachinePointerInfo::getConstantPool(),
2258                        false, false, false, 0);
2259   }
2260 }
2261
2262 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2263                                                     SelectionDAG &DAG) const {
2264   EVT PtrVT = getPointerTy();
2265   DebugLoc dl = Op.getDebugLoc();
2266   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2267   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2268   MachineFunction &MF = DAG.getMachineFunction();
2269   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2270
2271   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2272   // update ARMFastISel::ARMMaterializeGV.
2273   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2274     ++NumMovwMovt;
2275     // FIXME: Once remat is capable of dealing with instructions with register
2276     // operands, expand this into two nodes.
2277     if (RelocM == Reloc::Static)
2278       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2279                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2280
2281     unsigned Wrapper = (RelocM == Reloc::PIC_)
2282       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2283     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2284                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2285     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2286       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2287                            MachinePointerInfo::getGOT(),
2288                            false, false, false, 0);
2289     return Result;
2290   }
2291
2292   unsigned ARMPCLabelIndex = 0;
2293   SDValue CPAddr;
2294   if (RelocM == Reloc::Static) {
2295     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2296   } else {
2297     ARMPCLabelIndex = AFI->createPICLabelUId();
2298     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2299     ARMConstantPoolValue *CPV =
2300       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2301                                       PCAdj);
2302     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2303   }
2304   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2305
2306   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2307                                MachinePointerInfo::getConstantPool(),
2308                                false, false, false, 0);
2309   SDValue Chain = Result.getValue(1);
2310
2311   if (RelocM == Reloc::PIC_) {
2312     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2313     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2314   }
2315
2316   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2317     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2318                          false, false, false, 0);
2319
2320   return Result;
2321 }
2322
2323 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2324                                                     SelectionDAG &DAG) const {
2325   assert(Subtarget->isTargetELF() &&
2326          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2327   MachineFunction &MF = DAG.getMachineFunction();
2328   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2329   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2330   EVT PtrVT = getPointerTy();
2331   DebugLoc dl = Op.getDebugLoc();
2332   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2333   ARMConstantPoolValue *CPV =
2334     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2335                                   ARMPCLabelIndex, PCAdj);
2336   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2337   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2338   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2339                                MachinePointerInfo::getConstantPool(),
2340                                false, false, false, 0);
2341   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2342   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2343 }
2344
2345 SDValue
2346 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2347   DebugLoc dl = Op.getDebugLoc();
2348   SDValue Val = DAG.getConstant(0, MVT::i32);
2349   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2350                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2351                      Op.getOperand(1), Val);
2352 }
2353
2354 SDValue
2355 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2356   DebugLoc dl = Op.getDebugLoc();
2357   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2358                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2359 }
2360
2361 SDValue
2362 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2363                                           const ARMSubtarget *Subtarget) const {
2364   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2365   DebugLoc dl = Op.getDebugLoc();
2366   switch (IntNo) {
2367   default: return SDValue();    // Don't custom lower most intrinsics.
2368   case Intrinsic::arm_thread_pointer: {
2369     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2370     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2371   }
2372   case Intrinsic::eh_sjlj_lsda: {
2373     MachineFunction &MF = DAG.getMachineFunction();
2374     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2375     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2376     EVT PtrVT = getPointerTy();
2377     DebugLoc dl = Op.getDebugLoc();
2378     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2379     SDValue CPAddr;
2380     unsigned PCAdj = (RelocM != Reloc::PIC_)
2381       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2382     ARMConstantPoolValue *CPV =
2383       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2384                                       ARMCP::CPLSDA, PCAdj);
2385     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2386     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2387     SDValue Result =
2388       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2389                   MachinePointerInfo::getConstantPool(),
2390                   false, false, false, 0);
2391
2392     if (RelocM == Reloc::PIC_) {
2393       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2394       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2395     }
2396     return Result;
2397   }
2398   case Intrinsic::arm_neon_vmulls:
2399   case Intrinsic::arm_neon_vmullu: {
2400     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2401       ? ARMISD::VMULLs : ARMISD::VMULLu;
2402     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2403                        Op.getOperand(1), Op.getOperand(2));
2404   }
2405   }
2406 }
2407
2408 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2409                                const ARMSubtarget *Subtarget) {
2410   DebugLoc dl = Op.getDebugLoc();
2411   if (!Subtarget->hasDataBarrier()) {
2412     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2413     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2414     // here.
2415     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2416            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2417     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2418                        DAG.getConstant(0, MVT::i32));
2419   }
2420
2421   SDValue Op5 = Op.getOperand(5);
2422   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2423   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2424   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2425   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2426
2427   ARM_MB::MemBOpt DMBOpt;
2428   if (isDeviceBarrier)
2429     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2430   else
2431     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2432   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2433                      DAG.getConstant(DMBOpt, MVT::i32));
2434 }
2435
2436
2437 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2438                                  const ARMSubtarget *Subtarget) {
2439   // FIXME: handle "fence singlethread" more efficiently.
2440   DebugLoc dl = Op.getDebugLoc();
2441   if (!Subtarget->hasDataBarrier()) {
2442     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2443     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2444     // here.
2445     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2446            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2447     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2448                        DAG.getConstant(0, MVT::i32));
2449   }
2450
2451   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2452                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2453 }
2454
2455 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2456                              const ARMSubtarget *Subtarget) {
2457   // ARM pre v5TE and Thumb1 does not have preload instructions.
2458   if (!(Subtarget->isThumb2() ||
2459         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2460     // Just preserve the chain.
2461     return Op.getOperand(0);
2462
2463   DebugLoc dl = Op.getDebugLoc();
2464   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2465   if (!isRead &&
2466       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2467     // ARMv7 with MP extension has PLDW.
2468     return Op.getOperand(0);
2469
2470   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2471   if (Subtarget->isThumb()) {
2472     // Invert the bits.
2473     isRead = ~isRead & 1;
2474     isData = ~isData & 1;
2475   }
2476
2477   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2478                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2479                      DAG.getConstant(isData, MVT::i32));
2480 }
2481
2482 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2483   MachineFunction &MF = DAG.getMachineFunction();
2484   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2485
2486   // vastart just stores the address of the VarArgsFrameIndex slot into the
2487   // memory location argument.
2488   DebugLoc dl = Op.getDebugLoc();
2489   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2490   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2491   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2492   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2493                       MachinePointerInfo(SV), false, false, 0);
2494 }
2495
2496 SDValue
2497 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2498                                         SDValue &Root, SelectionDAG &DAG,
2499                                         DebugLoc dl) const {
2500   MachineFunction &MF = DAG.getMachineFunction();
2501   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2502
2503   const TargetRegisterClass *RC;
2504   if (AFI->isThumb1OnlyFunction())
2505     RC = &ARM::tGPRRegClass;
2506   else
2507     RC = &ARM::GPRRegClass;
2508
2509   // Transform the arguments stored in physical registers into virtual ones.
2510   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2511   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2512
2513   SDValue ArgValue2;
2514   if (NextVA.isMemLoc()) {
2515     MachineFrameInfo *MFI = MF.getFrameInfo();
2516     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2517
2518     // Create load node to retrieve arguments from the stack.
2519     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2520     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2521                             MachinePointerInfo::getFixedStack(FI),
2522                             false, false, false, 0);
2523   } else {
2524     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2525     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2526   }
2527
2528   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2529 }
2530
2531 void
2532 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2533                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2534   const {
2535   unsigned NumGPRs;
2536   if (CCInfo.isFirstByValRegValid())
2537     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2538   else {
2539     unsigned int firstUnalloced;
2540     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2541                                                 sizeof(GPRArgRegs) /
2542                                                 sizeof(GPRArgRegs[0]));
2543     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2544   }
2545
2546   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2547   VARegSize = NumGPRs * 4;
2548   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2549 }
2550
2551 // The remaining GPRs hold either the beginning of variable-argument
2552 // data, or the beginning of an aggregate passed by value (usuall
2553 // byval).  Either way, we allocate stack slots adjacent to the data
2554 // provided by our caller, and store the unallocated registers there.
2555 // If this is a variadic function, the va_list pointer will begin with
2556 // these values; otherwise, this reassembles a (byval) structure that
2557 // was split between registers and memory.
2558 void
2559 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2560                                         DebugLoc dl, SDValue &Chain,
2561                                         const Value *OrigArg,
2562                                         unsigned OffsetFromOrigArg,
2563                                         unsigned ArgOffset,
2564                                         bool ForceMutable) const {
2565   MachineFunction &MF = DAG.getMachineFunction();
2566   MachineFrameInfo *MFI = MF.getFrameInfo();
2567   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2568   unsigned firstRegToSaveIndex;
2569   if (CCInfo.isFirstByValRegValid())
2570     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2571   else {
2572     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2573       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2574   }
2575
2576   unsigned VARegSize, VARegSaveSize;
2577   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2578   if (VARegSaveSize) {
2579     // If this function is vararg, store any remaining integer argument regs
2580     // to their spots on the stack so that they may be loaded by deferencing
2581     // the result of va_next.
2582     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2583     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2584                                                      ArgOffset + VARegSaveSize
2585                                                      - VARegSize,
2586                                                      false));
2587     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2588                                     getPointerTy());
2589
2590     SmallVector<SDValue, 4> MemOps;
2591     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2592       const TargetRegisterClass *RC;
2593       if (AFI->isThumb1OnlyFunction())
2594         RC = &ARM::tGPRRegClass;
2595       else
2596         RC = &ARM::GPRRegClass;
2597
2598       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2599       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2600       SDValue Store =
2601         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2602                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2603                      false, false, 0);
2604       MemOps.push_back(Store);
2605       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2606                         DAG.getConstant(4, getPointerTy()));
2607     }
2608     if (!MemOps.empty())
2609       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2610                           &MemOps[0], MemOps.size());
2611   } else
2612     // This will point to the next argument passed via stack.
2613     AFI->setVarArgsFrameIndex(
2614         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2615 }
2616
2617 SDValue
2618 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2619                                         CallingConv::ID CallConv, bool isVarArg,
2620                                         const SmallVectorImpl<ISD::InputArg>
2621                                           &Ins,
2622                                         DebugLoc dl, SelectionDAG &DAG,
2623                                         SmallVectorImpl<SDValue> &InVals)
2624                                           const {
2625   MachineFunction &MF = DAG.getMachineFunction();
2626   MachineFrameInfo *MFI = MF.getFrameInfo();
2627
2628   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2629
2630   // Assign locations to all of the incoming arguments.
2631   SmallVector<CCValAssign, 16> ArgLocs;
2632   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2633                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2634   CCInfo.AnalyzeFormalArguments(Ins,
2635                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2636                                                   isVarArg));
2637   
2638   SmallVector<SDValue, 16> ArgValues;
2639   int lastInsIndex = -1;
2640   SDValue ArgValue;
2641   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2642   unsigned CurArgIdx = 0;
2643   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2644     CCValAssign &VA = ArgLocs[i];
2645     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2646     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2647     // Arguments stored in registers.
2648     if (VA.isRegLoc()) {
2649       EVT RegVT = VA.getLocVT();
2650
2651       if (VA.needsCustom()) {
2652         // f64 and vector types are split up into multiple registers or
2653         // combinations of registers and stack slots.
2654         if (VA.getLocVT() == MVT::v2f64) {
2655           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2656                                                    Chain, DAG, dl);
2657           VA = ArgLocs[++i]; // skip ahead to next loc
2658           SDValue ArgValue2;
2659           if (VA.isMemLoc()) {
2660             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2661             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2662             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2663                                     MachinePointerInfo::getFixedStack(FI),
2664                                     false, false, false, 0);
2665           } else {
2666             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2667                                              Chain, DAG, dl);
2668           }
2669           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2670           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2671                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2672           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2673                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2674         } else
2675           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2676
2677       } else {
2678         const TargetRegisterClass *RC;
2679
2680         if (RegVT == MVT::f32)
2681           RC = &ARM::SPRRegClass;
2682         else if (RegVT == MVT::f64)
2683           RC = &ARM::DPRRegClass;
2684         else if (RegVT == MVT::v2f64)
2685           RC = &ARM::QPRRegClass;
2686         else if (RegVT == MVT::i32)
2687           RC = AFI->isThumb1OnlyFunction() ?
2688             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2689             (const TargetRegisterClass*)&ARM::GPRRegClass;
2690         else
2691           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2692
2693         // Transform the arguments in physical registers into virtual ones.
2694         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2695         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2696       }
2697
2698       // If this is an 8 or 16-bit value, it is really passed promoted
2699       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2700       // truncate to the right size.
2701       switch (VA.getLocInfo()) {
2702       default: llvm_unreachable("Unknown loc info!");
2703       case CCValAssign::Full: break;
2704       case CCValAssign::BCvt:
2705         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2706         break;
2707       case CCValAssign::SExt:
2708         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2709                                DAG.getValueType(VA.getValVT()));
2710         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2711         break;
2712       case CCValAssign::ZExt:
2713         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2714                                DAG.getValueType(VA.getValVT()));
2715         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2716         break;
2717       }
2718
2719       InVals.push_back(ArgValue);
2720
2721     } else { // VA.isRegLoc()
2722
2723       // sanity check
2724       assert(VA.isMemLoc());
2725       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2726
2727       int index = ArgLocs[i].getValNo();
2728
2729       // Some Ins[] entries become multiple ArgLoc[] entries.
2730       // Process them only once.
2731       if (index != lastInsIndex)
2732         {
2733           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2734           // FIXME: For now, all byval parameter objects are marked mutable.
2735           // This can be changed with more analysis.
2736           // In case of tail call optimization mark all arguments mutable.
2737           // Since they could be overwritten by lowering of arguments in case of
2738           // a tail call.
2739           if (Flags.isByVal()) {
2740             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2741             if (!AFI->getVarArgsFrameIndex()) {
2742               VarArgStyleRegisters(CCInfo, DAG,
2743                                    dl, Chain, CurOrigArg,
2744                                    Ins[VA.getValNo()].PartOffset,
2745                                    VA.getLocMemOffset(),
2746                                    true /*force mutable frames*/);
2747               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2748               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2749             } else {
2750               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2751                                               VA.getLocMemOffset(), false);
2752               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2753             }
2754           } else {
2755             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2756                                             VA.getLocMemOffset(), true);
2757
2758             // Create load nodes to retrieve arguments from the stack.
2759             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2760             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2761                                          MachinePointerInfo::getFixedStack(FI),
2762                                          false, false, false, 0));
2763           }
2764           lastInsIndex = index;
2765         }
2766     }
2767   }
2768
2769   // varargs
2770   if (isVarArg)
2771     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2772                          CCInfo.getNextStackOffset());
2773
2774   return Chain;
2775 }
2776
2777 /// isFloatingPointZero - Return true if this is +0.0.
2778 static bool isFloatingPointZero(SDValue Op) {
2779   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2780     return CFP->getValueAPF().isPosZero();
2781   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2782     // Maybe this has already been legalized into the constant pool?
2783     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2784       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2785       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2786         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2787           return CFP->getValueAPF().isPosZero();
2788     }
2789   }
2790   return false;
2791 }
2792
2793 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2794 /// the given operands.
2795 SDValue
2796 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2797                              SDValue &ARMcc, SelectionDAG &DAG,
2798                              DebugLoc dl) const {
2799   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2800     unsigned C = RHSC->getZExtValue();
2801     if (!isLegalICmpImmediate(C)) {
2802       // Constant does not fit, try adjusting it by one?
2803       switch (CC) {
2804       default: break;
2805       case ISD::SETLT:
2806       case ISD::SETGE:
2807         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2808           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2809           RHS = DAG.getConstant(C-1, MVT::i32);
2810         }
2811         break;
2812       case ISD::SETULT:
2813       case ISD::SETUGE:
2814         if (C != 0 && isLegalICmpImmediate(C-1)) {
2815           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2816           RHS = DAG.getConstant(C-1, MVT::i32);
2817         }
2818         break;
2819       case ISD::SETLE:
2820       case ISD::SETGT:
2821         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2822           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2823           RHS = DAG.getConstant(C+1, MVT::i32);
2824         }
2825         break;
2826       case ISD::SETULE:
2827       case ISD::SETUGT:
2828         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2829           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2830           RHS = DAG.getConstant(C+1, MVT::i32);
2831         }
2832         break;
2833       }
2834     }
2835   }
2836
2837   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2838   ARMISD::NodeType CompareType;
2839   switch (CondCode) {
2840   default:
2841     CompareType = ARMISD::CMP;
2842     break;
2843   case ARMCC::EQ:
2844   case ARMCC::NE:
2845     // Uses only Z Flag
2846     CompareType = ARMISD::CMPZ;
2847     break;
2848   }
2849   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2850   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2851 }
2852
2853 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2854 SDValue
2855 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2856                              DebugLoc dl) const {
2857   SDValue Cmp;
2858   if (!isFloatingPointZero(RHS))
2859     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2860   else
2861     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2862   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2863 }
2864
2865 /// duplicateCmp - Glue values can have only one use, so this function
2866 /// duplicates a comparison node.
2867 SDValue
2868 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2869   unsigned Opc = Cmp.getOpcode();
2870   DebugLoc DL = Cmp.getDebugLoc();
2871   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2872     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2873
2874   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2875   Cmp = Cmp.getOperand(0);
2876   Opc = Cmp.getOpcode();
2877   if (Opc == ARMISD::CMPFP)
2878     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2879   else {
2880     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2881     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2882   }
2883   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2884 }
2885
2886 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2887   SDValue Cond = Op.getOperand(0);
2888   SDValue SelectTrue = Op.getOperand(1);
2889   SDValue SelectFalse = Op.getOperand(2);
2890   DebugLoc dl = Op.getDebugLoc();
2891
2892   // Convert:
2893   //
2894   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2895   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2896   //
2897   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2898     const ConstantSDNode *CMOVTrue =
2899       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2900     const ConstantSDNode *CMOVFalse =
2901       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2902
2903     if (CMOVTrue && CMOVFalse) {
2904       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2905       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2906
2907       SDValue True;
2908       SDValue False;
2909       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2910         True = SelectTrue;
2911         False = SelectFalse;
2912       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2913         True = SelectFalse;
2914         False = SelectTrue;
2915       }
2916
2917       if (True.getNode() && False.getNode()) {
2918         EVT VT = Op.getValueType();
2919         SDValue ARMcc = Cond.getOperand(2);
2920         SDValue CCR = Cond.getOperand(3);
2921         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2922         assert(True.getValueType() == VT);
2923         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2924       }
2925     }
2926   }
2927
2928   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2929   // undefined bits before doing a full-word comparison with zero.
2930   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2931                      DAG.getConstant(1, Cond.getValueType()));
2932
2933   return DAG.getSelectCC(dl, Cond,
2934                          DAG.getConstant(0, Cond.getValueType()),
2935                          SelectTrue, SelectFalse, ISD::SETNE);
2936 }
2937
2938 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2939   EVT VT = Op.getValueType();
2940   SDValue LHS = Op.getOperand(0);
2941   SDValue RHS = Op.getOperand(1);
2942   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2943   SDValue TrueVal = Op.getOperand(2);
2944   SDValue FalseVal = Op.getOperand(3);
2945   DebugLoc dl = Op.getDebugLoc();
2946
2947   if (LHS.getValueType() == MVT::i32) {
2948     SDValue ARMcc;
2949     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2950     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2951     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2952   }
2953
2954   ARMCC::CondCodes CondCode, CondCode2;
2955   FPCCToARMCC(CC, CondCode, CondCode2);
2956
2957   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2958   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2959   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2960   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2961                                ARMcc, CCR, Cmp);
2962   if (CondCode2 != ARMCC::AL) {
2963     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2964     // FIXME: Needs another CMP because flag can have but one use.
2965     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2966     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2967                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2968   }
2969   return Result;
2970 }
2971
2972 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2973 /// to morph to an integer compare sequence.
2974 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2975                            const ARMSubtarget *Subtarget) {
2976   SDNode *N = Op.getNode();
2977   if (!N->hasOneUse())
2978     // Otherwise it requires moving the value from fp to integer registers.
2979     return false;
2980   if (!N->getNumValues())
2981     return false;
2982   EVT VT = Op.getValueType();
2983   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2984     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2985     // vmrs are very slow, e.g. cortex-a8.
2986     return false;
2987
2988   if (isFloatingPointZero(Op)) {
2989     SeenZero = true;
2990     return true;
2991   }
2992   return ISD::isNormalLoad(N);
2993 }
2994
2995 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2996   if (isFloatingPointZero(Op))
2997     return DAG.getConstant(0, MVT::i32);
2998
2999   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3000     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3001                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3002                        Ld->isVolatile(), Ld->isNonTemporal(),
3003                        Ld->isInvariant(), Ld->getAlignment());
3004
3005   llvm_unreachable("Unknown VFP cmp argument!");
3006 }
3007
3008 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3009                            SDValue &RetVal1, SDValue &RetVal2) {
3010   if (isFloatingPointZero(Op)) {
3011     RetVal1 = DAG.getConstant(0, MVT::i32);
3012     RetVal2 = DAG.getConstant(0, MVT::i32);
3013     return;
3014   }
3015
3016   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3017     SDValue Ptr = Ld->getBasePtr();
3018     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3019                           Ld->getChain(), Ptr,
3020                           Ld->getPointerInfo(),
3021                           Ld->isVolatile(), Ld->isNonTemporal(),
3022                           Ld->isInvariant(), Ld->getAlignment());
3023
3024     EVT PtrType = Ptr.getValueType();
3025     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3026     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3027                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3028     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3029                           Ld->getChain(), NewPtr,
3030                           Ld->getPointerInfo().getWithOffset(4),
3031                           Ld->isVolatile(), Ld->isNonTemporal(),
3032                           Ld->isInvariant(), NewAlign);
3033     return;
3034   }
3035
3036   llvm_unreachable("Unknown VFP cmp argument!");
3037 }
3038
3039 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3040 /// f32 and even f64 comparisons to integer ones.
3041 SDValue
3042 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3043   SDValue Chain = Op.getOperand(0);
3044   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3045   SDValue LHS = Op.getOperand(2);
3046   SDValue RHS = Op.getOperand(3);
3047   SDValue Dest = Op.getOperand(4);
3048   DebugLoc dl = Op.getDebugLoc();
3049
3050   bool LHSSeenZero = false;
3051   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3052   bool RHSSeenZero = false;
3053   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3054   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3055     // If unsafe fp math optimization is enabled and there are no other uses of
3056     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3057     // to an integer comparison.
3058     if (CC == ISD::SETOEQ)
3059       CC = ISD::SETEQ;
3060     else if (CC == ISD::SETUNE)
3061       CC = ISD::SETNE;
3062
3063     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3064     SDValue ARMcc;
3065     if (LHS.getValueType() == MVT::f32) {
3066       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3067                         bitcastf32Toi32(LHS, DAG), Mask);
3068       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3069                         bitcastf32Toi32(RHS, DAG), Mask);
3070       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3071       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3072       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3073                          Chain, Dest, ARMcc, CCR, Cmp);
3074     }
3075
3076     SDValue LHS1, LHS2;
3077     SDValue RHS1, RHS2;
3078     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3079     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3080     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3081     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3082     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3083     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3084     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3085     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3086     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3087   }
3088
3089   return SDValue();
3090 }
3091
3092 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3093   SDValue Chain = Op.getOperand(0);
3094   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3095   SDValue LHS = Op.getOperand(2);
3096   SDValue RHS = Op.getOperand(3);
3097   SDValue Dest = Op.getOperand(4);
3098   DebugLoc dl = Op.getDebugLoc();
3099
3100   if (LHS.getValueType() == MVT::i32) {
3101     SDValue ARMcc;
3102     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3103     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3104     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3105                        Chain, Dest, ARMcc, CCR, Cmp);
3106   }
3107
3108   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3109
3110   if (getTargetMachine().Options.UnsafeFPMath &&
3111       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3112        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3113     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3114     if (Result.getNode())
3115       return Result;
3116   }
3117
3118   ARMCC::CondCodes CondCode, CondCode2;
3119   FPCCToARMCC(CC, CondCode, CondCode2);
3120
3121   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3122   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3123   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3124   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3125   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3126   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3127   if (CondCode2 != ARMCC::AL) {
3128     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3129     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3130     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3131   }
3132   return Res;
3133 }
3134
3135 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3136   SDValue Chain = Op.getOperand(0);
3137   SDValue Table = Op.getOperand(1);
3138   SDValue Index = Op.getOperand(2);
3139   DebugLoc dl = Op.getDebugLoc();
3140
3141   EVT PTy = getPointerTy();
3142   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3143   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3144   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3145   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3146   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3147   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3148   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3149   if (Subtarget->isThumb2()) {
3150     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3151     // which does another jump to the destination. This also makes it easier
3152     // to translate it to TBB / TBH later.
3153     // FIXME: This might not work if the function is extremely large.
3154     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3155                        Addr, Op.getOperand(2), JTI, UId);
3156   }
3157   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3158     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3159                        MachinePointerInfo::getJumpTable(),
3160                        false, false, false, 0);
3161     Chain = Addr.getValue(1);
3162     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3163     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3164   } else {
3165     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3166                        MachinePointerInfo::getJumpTable(),
3167                        false, false, false, 0);
3168     Chain = Addr.getValue(1);
3169     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3170   }
3171 }
3172
3173 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3174   EVT VT = Op.getValueType();
3175   DebugLoc dl = Op.getDebugLoc();
3176
3177   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3178     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3179       return Op;
3180     return DAG.UnrollVectorOp(Op.getNode());
3181   }
3182
3183   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3184          "Invalid type for custom lowering!");
3185   if (VT != MVT::v4i16)
3186     return DAG.UnrollVectorOp(Op.getNode());
3187
3188   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3189   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3190 }
3191
3192 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3193   EVT VT = Op.getValueType();
3194   if (VT.isVector())
3195     return LowerVectorFP_TO_INT(Op, DAG);
3196
3197   DebugLoc dl = Op.getDebugLoc();
3198   unsigned Opc;
3199
3200   switch (Op.getOpcode()) {
3201   default: llvm_unreachable("Invalid opcode!");
3202   case ISD::FP_TO_SINT:
3203     Opc = ARMISD::FTOSI;
3204     break;
3205   case ISD::FP_TO_UINT:
3206     Opc = ARMISD::FTOUI;
3207     break;
3208   }
3209   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3210   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3211 }
3212
3213 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3214   EVT VT = Op.getValueType();
3215   DebugLoc dl = Op.getDebugLoc();
3216
3217   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3218     if (VT.getVectorElementType() == MVT::f32)
3219       return Op;
3220     return DAG.UnrollVectorOp(Op.getNode());
3221   }
3222
3223   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3224          "Invalid type for custom lowering!");
3225   if (VT != MVT::v4f32)
3226     return DAG.UnrollVectorOp(Op.getNode());
3227
3228   unsigned CastOpc;
3229   unsigned Opc;
3230   switch (Op.getOpcode()) {
3231   default: llvm_unreachable("Invalid opcode!");
3232   case ISD::SINT_TO_FP:
3233     CastOpc = ISD::SIGN_EXTEND;
3234     Opc = ISD::SINT_TO_FP;
3235     break;
3236   case ISD::UINT_TO_FP:
3237     CastOpc = ISD::ZERO_EXTEND;
3238     Opc = ISD::UINT_TO_FP;
3239     break;
3240   }
3241
3242   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3243   return DAG.getNode(Opc, dl, VT, Op);
3244 }
3245
3246 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3247   EVT VT = Op.getValueType();
3248   if (VT.isVector())
3249     return LowerVectorINT_TO_FP(Op, DAG);
3250
3251   DebugLoc dl = Op.getDebugLoc();
3252   unsigned Opc;
3253
3254   switch (Op.getOpcode()) {
3255   default: llvm_unreachable("Invalid opcode!");
3256   case ISD::SINT_TO_FP:
3257     Opc = ARMISD::SITOF;
3258     break;
3259   case ISD::UINT_TO_FP:
3260     Opc = ARMISD::UITOF;
3261     break;
3262   }
3263
3264   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3265   return DAG.getNode(Opc, dl, VT, Op);
3266 }
3267
3268 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3269   // Implement fcopysign with a fabs and a conditional fneg.
3270   SDValue Tmp0 = Op.getOperand(0);
3271   SDValue Tmp1 = Op.getOperand(1);
3272   DebugLoc dl = Op.getDebugLoc();
3273   EVT VT = Op.getValueType();
3274   EVT SrcVT = Tmp1.getValueType();
3275   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3276     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3277   bool UseNEON = !InGPR && Subtarget->hasNEON();
3278
3279   if (UseNEON) {
3280     // Use VBSL to copy the sign bit.
3281     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3282     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3283                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3284     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3285     if (VT == MVT::f64)
3286       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3287                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3288                          DAG.getConstant(32, MVT::i32));
3289     else /*if (VT == MVT::f32)*/
3290       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3291     if (SrcVT == MVT::f32) {
3292       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3293       if (VT == MVT::f64)
3294         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3295                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3296                            DAG.getConstant(32, MVT::i32));
3297     } else if (VT == MVT::f32)
3298       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3299                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3300                          DAG.getConstant(32, MVT::i32));
3301     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3302     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3303
3304     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3305                                             MVT::i32);
3306     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3307     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3308                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3309
3310     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3311                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3312                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3313     if (VT == MVT::f32) {
3314       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3315       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3316                         DAG.getConstant(0, MVT::i32));
3317     } else {
3318       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3319     }
3320
3321     return Res;
3322   }
3323
3324   // Bitcast operand 1 to i32.
3325   if (SrcVT == MVT::f64)
3326     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3327                        &Tmp1, 1).getValue(1);
3328   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3329
3330   // Or in the signbit with integer operations.
3331   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3332   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3333   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3334   if (VT == MVT::f32) {
3335     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3336                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3337     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3338                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3339   }
3340
3341   // f64: Or the high part with signbit and then combine two parts.
3342   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3343                      &Tmp0, 1);
3344   SDValue Lo = Tmp0.getValue(0);
3345   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3346   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3347   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3348 }
3349
3350 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3351   MachineFunction &MF = DAG.getMachineFunction();
3352   MachineFrameInfo *MFI = MF.getFrameInfo();
3353   MFI->setReturnAddressIsTaken(true);
3354
3355   EVT VT = Op.getValueType();
3356   DebugLoc dl = Op.getDebugLoc();
3357   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3358   if (Depth) {
3359     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3360     SDValue Offset = DAG.getConstant(4, MVT::i32);
3361     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3362                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3363                        MachinePointerInfo(), false, false, false, 0);
3364   }
3365
3366   // Return LR, which contains the return address. Mark it an implicit live-in.
3367   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3368   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3369 }
3370
3371 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3372   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3373   MFI->setFrameAddressIsTaken(true);
3374
3375   EVT VT = Op.getValueType();
3376   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3377   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3378   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3379     ? ARM::R7 : ARM::R11;
3380   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3381   while (Depth--)
3382     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3383                             MachinePointerInfo(),
3384                             false, false, false, 0);
3385   return FrameAddr;
3386 }
3387
3388 /// ExpandBITCAST - If the target supports VFP, this function is called to
3389 /// expand a bit convert where either the source or destination type is i64 to
3390 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3391 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3392 /// vectors), since the legalizer won't know what to do with that.
3393 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3395   DebugLoc dl = N->getDebugLoc();
3396   SDValue Op = N->getOperand(0);
3397
3398   // This function is only supposed to be called for i64 types, either as the
3399   // source or destination of the bit convert.
3400   EVT SrcVT = Op.getValueType();
3401   EVT DstVT = N->getValueType(0);
3402   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3403          "ExpandBITCAST called for non-i64 type");
3404
3405   // Turn i64->f64 into VMOVDRR.
3406   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3407     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3408                              DAG.getConstant(0, MVT::i32));
3409     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3410                              DAG.getConstant(1, MVT::i32));
3411     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3412                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3413   }
3414
3415   // Turn f64->i64 into VMOVRRD.
3416   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3417     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3418                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3419     // Merge the pieces into a single i64 value.
3420     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3421   }
3422
3423   return SDValue();
3424 }
3425
3426 /// getZeroVector - Returns a vector of specified type with all zero elements.
3427 /// Zero vectors are used to represent vector negation and in those cases
3428 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3429 /// not support i64 elements, so sometimes the zero vectors will need to be
3430 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3431 /// zero vector.
3432 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3433   assert(VT.isVector() && "Expected a vector type");
3434   // The canonical modified immediate encoding of a zero vector is....0!
3435   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3436   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3437   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3438   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3439 }
3440
3441 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3442 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3443 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3444                                                 SelectionDAG &DAG) const {
3445   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3446   EVT VT = Op.getValueType();
3447   unsigned VTBits = VT.getSizeInBits();
3448   DebugLoc dl = Op.getDebugLoc();
3449   SDValue ShOpLo = Op.getOperand(0);
3450   SDValue ShOpHi = Op.getOperand(1);
3451   SDValue ShAmt  = Op.getOperand(2);
3452   SDValue ARMcc;
3453   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3454
3455   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3456
3457   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3458                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3459   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3460   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3461                                    DAG.getConstant(VTBits, MVT::i32));
3462   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3463   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3464   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3465
3466   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3467   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3468                           ARMcc, DAG, dl);
3469   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3470   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3471                            CCR, Cmp);
3472
3473   SDValue Ops[2] = { Lo, Hi };
3474   return DAG.getMergeValues(Ops, 2, dl);
3475 }
3476
3477 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3478 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3479 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3480                                                SelectionDAG &DAG) const {
3481   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3482   EVT VT = Op.getValueType();
3483   unsigned VTBits = VT.getSizeInBits();
3484   DebugLoc dl = Op.getDebugLoc();
3485   SDValue ShOpLo = Op.getOperand(0);
3486   SDValue ShOpHi = Op.getOperand(1);
3487   SDValue ShAmt  = Op.getOperand(2);
3488   SDValue ARMcc;
3489
3490   assert(Op.getOpcode() == ISD::SHL_PARTS);
3491   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3492                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3493   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3494   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3495                                    DAG.getConstant(VTBits, MVT::i32));
3496   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3497   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3498
3499   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3500   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3501   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3502                           ARMcc, DAG, dl);
3503   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3504   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3505                            CCR, Cmp);
3506
3507   SDValue Ops[2] = { Lo, Hi };
3508   return DAG.getMergeValues(Ops, 2, dl);
3509 }
3510
3511 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3512                                             SelectionDAG &DAG) const {
3513   // The rounding mode is in bits 23:22 of the FPSCR.
3514   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3515   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3516   // so that the shift + and get folded into a bitfield extract.
3517   DebugLoc dl = Op.getDebugLoc();
3518   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3519                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3520                                               MVT::i32));
3521   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3522                                   DAG.getConstant(1U << 22, MVT::i32));
3523   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3524                               DAG.getConstant(22, MVT::i32));
3525   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3526                      DAG.getConstant(3, MVT::i32));
3527 }
3528
3529 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3530                          const ARMSubtarget *ST) {
3531   EVT VT = N->getValueType(0);
3532   DebugLoc dl = N->getDebugLoc();
3533
3534   if (!ST->hasV6T2Ops())
3535     return SDValue();
3536
3537   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3538   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3539 }
3540
3541 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3542                           const ARMSubtarget *ST) {
3543   EVT VT = N->getValueType(0);
3544   DebugLoc dl = N->getDebugLoc();
3545
3546   if (!VT.isVector())
3547     return SDValue();
3548
3549   // Lower vector shifts on NEON to use VSHL.
3550   assert(ST->hasNEON() && "unexpected vector shift");
3551
3552   // Left shifts translate directly to the vshiftu intrinsic.
3553   if (N->getOpcode() == ISD::SHL)
3554     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3555                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3556                        N->getOperand(0), N->getOperand(1));
3557
3558   assert((N->getOpcode() == ISD::SRA ||
3559           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3560
3561   // NEON uses the same intrinsics for both left and right shifts.  For
3562   // right shifts, the shift amounts are negative, so negate the vector of
3563   // shift amounts.
3564   EVT ShiftVT = N->getOperand(1).getValueType();
3565   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3566                                      getZeroVector(ShiftVT, DAG, dl),
3567                                      N->getOperand(1));
3568   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3569                              Intrinsic::arm_neon_vshifts :
3570                              Intrinsic::arm_neon_vshiftu);
3571   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3572                      DAG.getConstant(vshiftInt, MVT::i32),
3573                      N->getOperand(0), NegatedCount);
3574 }
3575
3576 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3577                                 const ARMSubtarget *ST) {
3578   EVT VT = N->getValueType(0);
3579   DebugLoc dl = N->getDebugLoc();
3580
3581   // We can get here for a node like i32 = ISD::SHL i32, i64
3582   if (VT != MVT::i64)
3583     return SDValue();
3584
3585   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3586          "Unknown shift to lower!");
3587
3588   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3589   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3590       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3591     return SDValue();
3592
3593   // If we are in thumb mode, we don't have RRX.
3594   if (ST->isThumb1Only()) return SDValue();
3595
3596   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3597   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3598                            DAG.getConstant(0, MVT::i32));
3599   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3600                            DAG.getConstant(1, MVT::i32));
3601
3602   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3603   // captures the result into a carry flag.
3604   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3605   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3606
3607   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3608   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3609
3610   // Merge the pieces into a single i64 value.
3611  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3612 }
3613
3614 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3615   SDValue TmpOp0, TmpOp1;
3616   bool Invert = false;
3617   bool Swap = false;
3618   unsigned Opc = 0;
3619
3620   SDValue Op0 = Op.getOperand(0);
3621   SDValue Op1 = Op.getOperand(1);
3622   SDValue CC = Op.getOperand(2);
3623   EVT VT = Op.getValueType();
3624   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3625   DebugLoc dl = Op.getDebugLoc();
3626
3627   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3628     switch (SetCCOpcode) {
3629     default: llvm_unreachable("Illegal FP comparison");
3630     case ISD::SETUNE:
3631     case ISD::SETNE:  Invert = true; // Fallthrough
3632     case ISD::SETOEQ:
3633     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3634     case ISD::SETOLT:
3635     case ISD::SETLT: Swap = true; // Fallthrough
3636     case ISD::SETOGT:
3637     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3638     case ISD::SETOLE:
3639     case ISD::SETLE:  Swap = true; // Fallthrough
3640     case ISD::SETOGE:
3641     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3642     case ISD::SETUGE: Swap = true; // Fallthrough
3643     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3644     case ISD::SETUGT: Swap = true; // Fallthrough
3645     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3646     case ISD::SETUEQ: Invert = true; // Fallthrough
3647     case ISD::SETONE:
3648       // Expand this to (OLT | OGT).
3649       TmpOp0 = Op0;
3650       TmpOp1 = Op1;
3651       Opc = ISD::OR;
3652       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3653       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3654       break;
3655     case ISD::SETUO: Invert = true; // Fallthrough
3656     case ISD::SETO:
3657       // Expand this to (OLT | OGE).
3658       TmpOp0 = Op0;
3659       TmpOp1 = Op1;
3660       Opc = ISD::OR;
3661       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3662       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3663       break;
3664     }
3665   } else {
3666     // Integer comparisons.
3667     switch (SetCCOpcode) {
3668     default: llvm_unreachable("Illegal integer comparison");
3669     case ISD::SETNE:  Invert = true;
3670     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3671     case ISD::SETLT:  Swap = true;
3672     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3673     case ISD::SETLE:  Swap = true;
3674     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3675     case ISD::SETULT: Swap = true;
3676     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3677     case ISD::SETULE: Swap = true;
3678     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3679     }
3680
3681     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3682     if (Opc == ARMISD::VCEQ) {
3683
3684       SDValue AndOp;
3685       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3686         AndOp = Op0;
3687       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3688         AndOp = Op1;
3689
3690       // Ignore bitconvert.
3691       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3692         AndOp = AndOp.getOperand(0);
3693
3694       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3695         Opc = ARMISD::VTST;
3696         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3697         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3698         Invert = !Invert;
3699       }
3700     }
3701   }
3702
3703   if (Swap)
3704     std::swap(Op0, Op1);
3705
3706   // If one of the operands is a constant vector zero, attempt to fold the
3707   // comparison to a specialized compare-against-zero form.
3708   SDValue SingleOp;
3709   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3710     SingleOp = Op0;
3711   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3712     if (Opc == ARMISD::VCGE)
3713       Opc = ARMISD::VCLEZ;
3714     else if (Opc == ARMISD::VCGT)
3715       Opc = ARMISD::VCLTZ;
3716     SingleOp = Op1;
3717   }
3718
3719   SDValue Result;
3720   if (SingleOp.getNode()) {
3721     switch (Opc) {
3722     case ARMISD::VCEQ:
3723       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3724     case ARMISD::VCGE:
3725       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3726     case ARMISD::VCLEZ:
3727       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3728     case ARMISD::VCGT:
3729       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3730     case ARMISD::VCLTZ:
3731       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3732     default:
3733       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3734     }
3735   } else {
3736      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3737   }
3738
3739   if (Invert)
3740     Result = DAG.getNOT(dl, Result, VT);
3741
3742   return Result;
3743 }
3744
3745 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3746 /// valid vector constant for a NEON instruction with a "modified immediate"
3747 /// operand (e.g., VMOV).  If so, return the encoded value.
3748 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3749                                  unsigned SplatBitSize, SelectionDAG &DAG,
3750                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3751   unsigned OpCmode, Imm;
3752
3753   // SplatBitSize is set to the smallest size that splats the vector, so a
3754   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3755   // immediate instructions others than VMOV do not support the 8-bit encoding
3756   // of a zero vector, and the default encoding of zero is supposed to be the
3757   // 32-bit version.
3758   if (SplatBits == 0)
3759     SplatBitSize = 32;
3760
3761   switch (SplatBitSize) {
3762   case 8:
3763     if (type != VMOVModImm)
3764       return SDValue();
3765     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3766     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3767     OpCmode = 0xe;
3768     Imm = SplatBits;
3769     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3770     break;
3771
3772   case 16:
3773     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3774     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3775     if ((SplatBits & ~0xff) == 0) {
3776       // Value = 0x00nn: Op=x, Cmode=100x.
3777       OpCmode = 0x8;
3778       Imm = SplatBits;
3779       break;
3780     }
3781     if ((SplatBits & ~0xff00) == 0) {
3782       // Value = 0xnn00: Op=x, Cmode=101x.
3783       OpCmode = 0xa;
3784       Imm = SplatBits >> 8;
3785       break;
3786     }
3787     return SDValue();
3788
3789   case 32:
3790     // NEON's 32-bit VMOV supports splat values where:
3791     // * only one byte is nonzero, or
3792     // * the least significant byte is 0xff and the second byte is nonzero, or
3793     // * the least significant 2 bytes are 0xff and the third is nonzero.
3794     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3795     if ((SplatBits & ~0xff) == 0) {
3796       // Value = 0x000000nn: Op=x, Cmode=000x.
3797       OpCmode = 0;
3798       Imm = SplatBits;
3799       break;
3800     }
3801     if ((SplatBits & ~0xff00) == 0) {
3802       // Value = 0x0000nn00: Op=x, Cmode=001x.
3803       OpCmode = 0x2;
3804       Imm = SplatBits >> 8;
3805       break;
3806     }
3807     if ((SplatBits & ~0xff0000) == 0) {
3808       // Value = 0x00nn0000: Op=x, Cmode=010x.
3809       OpCmode = 0x4;
3810       Imm = SplatBits >> 16;
3811       break;
3812     }
3813     if ((SplatBits & ~0xff000000) == 0) {
3814       // Value = 0xnn000000: Op=x, Cmode=011x.
3815       OpCmode = 0x6;
3816       Imm = SplatBits >> 24;
3817       break;
3818     }
3819
3820     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3821     if (type == OtherModImm) return SDValue();
3822
3823     if ((SplatBits & ~0xffff) == 0 &&
3824         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3825       // Value = 0x0000nnff: Op=x, Cmode=1100.
3826       OpCmode = 0xc;
3827       Imm = SplatBits >> 8;
3828       SplatBits |= 0xff;
3829       break;
3830     }
3831
3832     if ((SplatBits & ~0xffffff) == 0 &&
3833         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3834       // Value = 0x00nnffff: Op=x, Cmode=1101.
3835       OpCmode = 0xd;
3836       Imm = SplatBits >> 16;
3837       SplatBits |= 0xffff;
3838       break;
3839     }
3840
3841     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3842     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3843     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3844     // and fall through here to test for a valid 64-bit splat.  But, then the
3845     // caller would also need to check and handle the change in size.
3846     return SDValue();
3847
3848   case 64: {
3849     if (type != VMOVModImm)
3850       return SDValue();
3851     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3852     uint64_t BitMask = 0xff;
3853     uint64_t Val = 0;
3854     unsigned ImmMask = 1;
3855     Imm = 0;
3856     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3857       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3858         Val |= BitMask;
3859         Imm |= ImmMask;
3860       } else if ((SplatBits & BitMask) != 0) {
3861         return SDValue();
3862       }
3863       BitMask <<= 8;
3864       ImmMask <<= 1;
3865     }
3866     // Op=1, Cmode=1110.
3867     OpCmode = 0x1e;
3868     SplatBits = Val;
3869     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3870     break;
3871   }
3872
3873   default:
3874     llvm_unreachable("unexpected size for isNEONModifiedImm");
3875   }
3876
3877   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3878   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3879 }
3880
3881 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3882                                            const ARMSubtarget *ST) const {
3883   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3884     return SDValue();
3885
3886   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3887   assert(Op.getValueType() == MVT::f32 &&
3888          "ConstantFP custom lowering should only occur for f32.");
3889
3890   // Try splatting with a VMOV.f32...
3891   APFloat FPVal = CFP->getValueAPF();
3892   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3893   if (ImmVal != -1) {
3894     DebugLoc DL = Op.getDebugLoc();
3895     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3896     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3897                                       NewVal);
3898     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3899                        DAG.getConstant(0, MVT::i32));
3900   }
3901
3902   // If that fails, try a VMOV.i32
3903   EVT VMovVT;
3904   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3905   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3906                                      VMOVModImm);
3907   if (NewVal != SDValue()) {
3908     DebugLoc DL = Op.getDebugLoc();
3909     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3910                                       NewVal);
3911     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3912                                        VecConstant);
3913     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3914                        DAG.getConstant(0, MVT::i32));
3915   }
3916
3917   // Finally, try a VMVN.i32
3918   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3919                              VMVNModImm);
3920   if (NewVal != SDValue()) {
3921     DebugLoc DL = Op.getDebugLoc();
3922     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3923     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3924                                        VecConstant);
3925     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3926                        DAG.getConstant(0, MVT::i32));
3927   }
3928
3929   return SDValue();
3930 }
3931
3932
3933 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3934                        bool &ReverseVEXT, unsigned &Imm) {
3935   unsigned NumElts = VT.getVectorNumElements();
3936   ReverseVEXT = false;
3937
3938   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3939   if (M[0] < 0)
3940     return false;
3941
3942   Imm = M[0];
3943
3944   // If this is a VEXT shuffle, the immediate value is the index of the first
3945   // element.  The other shuffle indices must be the successive elements after
3946   // the first one.
3947   unsigned ExpectedElt = Imm;
3948   for (unsigned i = 1; i < NumElts; ++i) {
3949     // Increment the expected index.  If it wraps around, it may still be
3950     // a VEXT but the source vectors must be swapped.
3951     ExpectedElt += 1;
3952     if (ExpectedElt == NumElts * 2) {
3953       ExpectedElt = 0;
3954       ReverseVEXT = true;
3955     }
3956
3957     if (M[i] < 0) continue; // ignore UNDEF indices
3958     if (ExpectedElt != static_cast<unsigned>(M[i]))
3959       return false;
3960   }
3961
3962   // Adjust the index value if the source operands will be swapped.
3963   if (ReverseVEXT)
3964     Imm -= NumElts;
3965
3966   return true;
3967 }
3968
3969 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3970 /// instruction with the specified blocksize.  (The order of the elements
3971 /// within each block of the vector is reversed.)
3972 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3973   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3974          "Only possible block sizes for VREV are: 16, 32, 64");
3975
3976   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3977   if (EltSz == 64)
3978     return false;
3979
3980   unsigned NumElts = VT.getVectorNumElements();
3981   unsigned BlockElts = M[0] + 1;
3982   // If the first shuffle index is UNDEF, be optimistic.
3983   if (M[0] < 0)
3984     BlockElts = BlockSize / EltSz;
3985
3986   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3987     return false;
3988
3989   for (unsigned i = 0; i < NumElts; ++i) {
3990     if (M[i] < 0) continue; // ignore UNDEF indices
3991     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3992       return false;
3993   }
3994
3995   return true;
3996 }
3997
3998 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3999   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4000   // range, then 0 is placed into the resulting vector. So pretty much any mask
4001   // of 8 elements can work here.
4002   return VT == MVT::v8i8 && M.size() == 8;
4003 }
4004
4005 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4006   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4007   if (EltSz == 64)
4008     return false;
4009
4010   unsigned NumElts = VT.getVectorNumElements();
4011   WhichResult = (M[0] == 0 ? 0 : 1);
4012   for (unsigned i = 0; i < NumElts; i += 2) {
4013     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4014         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4015       return false;
4016   }
4017   return true;
4018 }
4019
4020 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4021 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4022 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4023 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4024   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4025   if (EltSz == 64)
4026     return false;
4027
4028   unsigned NumElts = VT.getVectorNumElements();
4029   WhichResult = (M[0] == 0 ? 0 : 1);
4030   for (unsigned i = 0; i < NumElts; i += 2) {
4031     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4032         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4033       return false;
4034   }
4035   return true;
4036 }
4037
4038 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4039   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4040   if (EltSz == 64)
4041     return false;
4042
4043   unsigned NumElts = VT.getVectorNumElements();
4044   WhichResult = (M[0] == 0 ? 0 : 1);
4045   for (unsigned i = 0; i != NumElts; ++i) {
4046     if (M[i] < 0) continue; // ignore UNDEF indices
4047     if ((unsigned) M[i] != 2 * i + WhichResult)
4048       return false;
4049   }
4050
4051   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4052   if (VT.is64BitVector() && EltSz == 32)
4053     return false;
4054
4055   return true;
4056 }
4057
4058 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4059 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4060 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4061 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4062   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4063   if (EltSz == 64)
4064     return false;
4065
4066   unsigned Half = VT.getVectorNumElements() / 2;
4067   WhichResult = (M[0] == 0 ? 0 : 1);
4068   for (unsigned j = 0; j != 2; ++j) {
4069     unsigned Idx = WhichResult;
4070     for (unsigned i = 0; i != Half; ++i) {
4071       int MIdx = M[i + j * Half];
4072       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4073         return false;
4074       Idx += 2;
4075     }
4076   }
4077
4078   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4079   if (VT.is64BitVector() && EltSz == 32)
4080     return false;
4081
4082   return true;
4083 }
4084
4085 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4086   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4087   if (EltSz == 64)
4088     return false;
4089
4090   unsigned NumElts = VT.getVectorNumElements();
4091   WhichResult = (M[0] == 0 ? 0 : 1);
4092   unsigned Idx = WhichResult * NumElts / 2;
4093   for (unsigned i = 0; i != NumElts; i += 2) {
4094     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4095         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4096       return false;
4097     Idx += 1;
4098   }
4099
4100   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4101   if (VT.is64BitVector() && EltSz == 32)
4102     return false;
4103
4104   return true;
4105 }
4106
4107 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4108 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4109 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4110 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4111   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4112   if (EltSz == 64)
4113     return false;
4114
4115   unsigned NumElts = VT.getVectorNumElements();
4116   WhichResult = (M[0] == 0 ? 0 : 1);
4117   unsigned Idx = WhichResult * NumElts / 2;
4118   for (unsigned i = 0; i != NumElts; i += 2) {
4119     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4120         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4121       return false;
4122     Idx += 1;
4123   }
4124
4125   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4126   if (VT.is64BitVector() && EltSz == 32)
4127     return false;
4128
4129   return true;
4130 }
4131
4132 // If N is an integer constant that can be moved into a register in one
4133 // instruction, return an SDValue of such a constant (will become a MOV
4134 // instruction).  Otherwise return null.
4135 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4136                                      const ARMSubtarget *ST, DebugLoc dl) {
4137   uint64_t Val;
4138   if (!isa<ConstantSDNode>(N))
4139     return SDValue();
4140   Val = cast<ConstantSDNode>(N)->getZExtValue();
4141
4142   if (ST->isThumb1Only()) {
4143     if (Val <= 255 || ~Val <= 255)
4144       return DAG.getConstant(Val, MVT::i32);
4145   } else {
4146     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4147       return DAG.getConstant(Val, MVT::i32);
4148   }
4149   return SDValue();
4150 }
4151
4152 // If this is a case we can't handle, return null and let the default
4153 // expansion code take care of it.
4154 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4155                                              const ARMSubtarget *ST) const {
4156   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4157   DebugLoc dl = Op.getDebugLoc();
4158   EVT VT = Op.getValueType();
4159
4160   APInt SplatBits, SplatUndef;
4161   unsigned SplatBitSize;
4162   bool HasAnyUndefs;
4163   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4164     if (SplatBitSize <= 64) {
4165       // Check if an immediate VMOV works.
4166       EVT VmovVT;
4167       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4168                                       SplatUndef.getZExtValue(), SplatBitSize,
4169                                       DAG, VmovVT, VT.is128BitVector(),
4170                                       VMOVModImm);
4171       if (Val.getNode()) {
4172         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4173         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4174       }
4175
4176       // Try an immediate VMVN.
4177       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4178       Val = isNEONModifiedImm(NegatedImm,
4179                                       SplatUndef.getZExtValue(), SplatBitSize,
4180                                       DAG, VmovVT, VT.is128BitVector(),
4181                                       VMVNModImm);
4182       if (Val.getNode()) {
4183         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4184         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4185       }
4186
4187       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4188       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4189         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4190         if (ImmVal != -1) {
4191           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4192           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4193         }
4194       }
4195     }
4196   }
4197
4198   // Scan through the operands to see if only one value is used.
4199   //
4200   // As an optimisation, even if more than one value is used it may be more
4201   // profitable to splat with one value then change some lanes.
4202   //
4203   // Heuristically we decide to do this if the vector has a "dominant" value,
4204   // defined as splatted to more than half of the lanes.
4205   unsigned NumElts = VT.getVectorNumElements();
4206   bool isOnlyLowElement = true;
4207   bool usesOnlyOneValue = true;
4208   bool hasDominantValue = false;
4209   bool isConstant = true;
4210
4211   // Map of the number of times a particular SDValue appears in the
4212   // element list.
4213   DenseMap<SDValue, unsigned> ValueCounts;
4214   SDValue Value;
4215   for (unsigned i = 0; i < NumElts; ++i) {
4216     SDValue V = Op.getOperand(i);
4217     if (V.getOpcode() == ISD::UNDEF)
4218       continue;
4219     if (i > 0)
4220       isOnlyLowElement = false;
4221     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4222       isConstant = false;
4223
4224     ValueCounts.insert(std::make_pair(V, 0));
4225     unsigned &Count = ValueCounts[V];
4226     
4227     // Is this value dominant? (takes up more than half of the lanes)
4228     if (++Count > (NumElts / 2)) {
4229       hasDominantValue = true;
4230       Value = V;
4231     }
4232   }
4233   if (ValueCounts.size() != 1)
4234     usesOnlyOneValue = false;
4235   if (!Value.getNode() && ValueCounts.size() > 0)
4236     Value = ValueCounts.begin()->first;
4237
4238   if (ValueCounts.size() == 0)
4239     return DAG.getUNDEF(VT);
4240
4241   if (isOnlyLowElement)
4242     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4243
4244   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4245
4246   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4247   // i32 and try again.
4248   if (hasDominantValue && EltSize <= 32) {
4249     if (!isConstant) {
4250       SDValue N;
4251
4252       // If we are VDUPing a value that comes directly from a vector, that will
4253       // cause an unnecessary move to and from a GPR, where instead we could
4254       // just use VDUPLANE.
4255       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4256         // We need to create a new undef vector to use for the VDUPLANE if the
4257         // size of the vector from which we get the value is different than the
4258         // size of the vector that we need to create. We will insert the element
4259         // such that the register coalescer will remove unnecessary copies.
4260         if (VT != Value->getOperand(0).getValueType()) {
4261           ConstantSDNode *constIndex;
4262           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4263           assert(constIndex && "The index is not a constant!");
4264           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4265                              VT.getVectorNumElements();
4266           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4267                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4268                         Value, DAG.getConstant(index, MVT::i32)),
4269                            DAG.getConstant(index, MVT::i32));
4270         } else {
4271           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4272                         Value->getOperand(0), Value->getOperand(1));
4273         }
4274       }
4275       else
4276         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4277
4278       if (!usesOnlyOneValue) {
4279         // The dominant value was splatted as 'N', but we now have to insert
4280         // all differing elements.
4281         for (unsigned I = 0; I < NumElts; ++I) {
4282           if (Op.getOperand(I) == Value)
4283             continue;
4284           SmallVector<SDValue, 3> Ops;
4285           Ops.push_back(N);
4286           Ops.push_back(Op.getOperand(I));
4287           Ops.push_back(DAG.getConstant(I, MVT::i32));
4288           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4289         }
4290       }
4291       return N;
4292     }
4293     if (VT.getVectorElementType().isFloatingPoint()) {
4294       SmallVector<SDValue, 8> Ops;
4295       for (unsigned i = 0; i < NumElts; ++i)
4296         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4297                                   Op.getOperand(i)));
4298       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4299       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4300       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4301       if (Val.getNode())
4302         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4303     }
4304     if (usesOnlyOneValue) {
4305       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4306       if (isConstant && Val.getNode())
4307         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4308     }
4309   }
4310
4311   // If all elements are constants and the case above didn't get hit, fall back
4312   // to the default expansion, which will generate a load from the constant
4313   // pool.
4314   if (isConstant)
4315     return SDValue();
4316
4317   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4318   if (NumElts >= 4) {
4319     SDValue shuffle = ReconstructShuffle(Op, DAG);
4320     if (shuffle != SDValue())
4321       return shuffle;
4322   }
4323
4324   // Vectors with 32- or 64-bit elements can be built by directly assigning
4325   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4326   // will be legalized.
4327   if (EltSize >= 32) {
4328     // Do the expansion with floating-point types, since that is what the VFP
4329     // registers are defined to use, and since i64 is not legal.
4330     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4331     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4332     SmallVector<SDValue, 8> Ops;
4333     for (unsigned i = 0; i < NumElts; ++i)
4334       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4335     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4336     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4337   }
4338
4339   return SDValue();
4340 }
4341
4342 // Gather data to see if the operation can be modelled as a
4343 // shuffle in combination with VEXTs.
4344 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4345                                               SelectionDAG &DAG) const {
4346   DebugLoc dl = Op.getDebugLoc();
4347   EVT VT = Op.getValueType();
4348   unsigned NumElts = VT.getVectorNumElements();
4349
4350   SmallVector<SDValue, 2> SourceVecs;
4351   SmallVector<unsigned, 2> MinElts;
4352   SmallVector<unsigned, 2> MaxElts;
4353
4354   for (unsigned i = 0; i < NumElts; ++i) {
4355     SDValue V = Op.getOperand(i);
4356     if (V.getOpcode() == ISD::UNDEF)
4357       continue;
4358     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4359       // A shuffle can only come from building a vector from various
4360       // elements of other vectors.
4361       return SDValue();
4362     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4363                VT.getVectorElementType()) {
4364       // This code doesn't know how to handle shuffles where the vector
4365       // element types do not match (this happens because type legalization
4366       // promotes the return type of EXTRACT_VECTOR_ELT).
4367       // FIXME: It might be appropriate to extend this code to handle
4368       // mismatched types.
4369       return SDValue();
4370     }
4371
4372     // Record this extraction against the appropriate vector if possible...
4373     SDValue SourceVec = V.getOperand(0);
4374     // If the element number isn't a constant, we can't effectively
4375     // analyze what's going on.
4376     if (!isa<ConstantSDNode>(V.getOperand(1)))
4377       return SDValue();
4378     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4379     bool FoundSource = false;
4380     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4381       if (SourceVecs[j] == SourceVec) {
4382         if (MinElts[j] > EltNo)
4383           MinElts[j] = EltNo;
4384         if (MaxElts[j] < EltNo)
4385           MaxElts[j] = EltNo;
4386         FoundSource = true;
4387         break;
4388       }
4389     }
4390
4391     // Or record a new source if not...
4392     if (!FoundSource) {
4393       SourceVecs.push_back(SourceVec);
4394       MinElts.push_back(EltNo);
4395       MaxElts.push_back(EltNo);
4396     }
4397   }
4398
4399   // Currently only do something sane when at most two source vectors
4400   // involved.
4401   if (SourceVecs.size() > 2)
4402     return SDValue();
4403
4404   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4405   int VEXTOffsets[2] = {0, 0};
4406
4407   // This loop extracts the usage patterns of the source vectors
4408   // and prepares appropriate SDValues for a shuffle if possible.
4409   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4410     if (SourceVecs[i].getValueType() == VT) {
4411       // No VEXT necessary
4412       ShuffleSrcs[i] = SourceVecs[i];
4413       VEXTOffsets[i] = 0;
4414       continue;
4415     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4416       // It probably isn't worth padding out a smaller vector just to
4417       // break it down again in a shuffle.
4418       return SDValue();
4419     }
4420
4421     // Since only 64-bit and 128-bit vectors are legal on ARM and
4422     // we've eliminated the other cases...
4423     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4424            "unexpected vector sizes in ReconstructShuffle");
4425
4426     if (MaxElts[i] - MinElts[i] >= NumElts) {
4427       // Span too large for a VEXT to cope
4428       return SDValue();
4429     }
4430
4431     if (MinElts[i] >= NumElts) {
4432       // The extraction can just take the second half
4433       VEXTOffsets[i] = NumElts;
4434       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4435                                    SourceVecs[i],
4436                                    DAG.getIntPtrConstant(NumElts));
4437     } else if (MaxElts[i] < NumElts) {
4438       // The extraction can just take the first half
4439       VEXTOffsets[i] = 0;
4440       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4441                                    SourceVecs[i],
4442                                    DAG.getIntPtrConstant(0));
4443     } else {
4444       // An actual VEXT is needed
4445       VEXTOffsets[i] = MinElts[i];
4446       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4447                                      SourceVecs[i],
4448                                      DAG.getIntPtrConstant(0));
4449       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4450                                      SourceVecs[i],
4451                                      DAG.getIntPtrConstant(NumElts));
4452       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4453                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4454     }
4455   }
4456
4457   SmallVector<int, 8> Mask;
4458
4459   for (unsigned i = 0; i < NumElts; ++i) {
4460     SDValue Entry = Op.getOperand(i);
4461     if (Entry.getOpcode() == ISD::UNDEF) {
4462       Mask.push_back(-1);
4463       continue;
4464     }
4465
4466     SDValue ExtractVec = Entry.getOperand(0);
4467     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4468                                           .getOperand(1))->getSExtValue();
4469     if (ExtractVec == SourceVecs[0]) {
4470       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4471     } else {
4472       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4473     }
4474   }
4475
4476   // Final check before we try to produce nonsense...
4477   if (isShuffleMaskLegal(Mask, VT))
4478     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4479                                 &Mask[0]);
4480
4481   return SDValue();
4482 }
4483
4484 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4485 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4486 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4487 /// are assumed to be legal.
4488 bool
4489 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4490                                       EVT VT) const {
4491   if (VT.getVectorNumElements() == 4 &&
4492       (VT.is128BitVector() || VT.is64BitVector())) {
4493     unsigned PFIndexes[4];
4494     for (unsigned i = 0; i != 4; ++i) {
4495       if (M[i] < 0)
4496         PFIndexes[i] = 8;
4497       else
4498         PFIndexes[i] = M[i];
4499     }
4500
4501     // Compute the index in the perfect shuffle table.
4502     unsigned PFTableIndex =
4503       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4504     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4505     unsigned Cost = (PFEntry >> 30);
4506
4507     if (Cost <= 4)
4508       return true;
4509   }
4510
4511   bool ReverseVEXT;
4512   unsigned Imm, WhichResult;
4513
4514   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4515   return (EltSize >= 32 ||
4516           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4517           isVREVMask(M, VT, 64) ||
4518           isVREVMask(M, VT, 32) ||
4519           isVREVMask(M, VT, 16) ||
4520           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4521           isVTBLMask(M, VT) ||
4522           isVTRNMask(M, VT, WhichResult) ||
4523           isVUZPMask(M, VT, WhichResult) ||
4524           isVZIPMask(M, VT, WhichResult) ||
4525           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4526           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4527           isVZIP_v_undef_Mask(M, VT, WhichResult));
4528 }
4529
4530 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4531 /// the specified operations to build the shuffle.
4532 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4533                                       SDValue RHS, SelectionDAG &DAG,
4534                                       DebugLoc dl) {
4535   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4536   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4537   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4538
4539   enum {
4540     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4541     OP_VREV,
4542     OP_VDUP0,
4543     OP_VDUP1,
4544     OP_VDUP2,
4545     OP_VDUP3,
4546     OP_VEXT1,
4547     OP_VEXT2,
4548     OP_VEXT3,
4549     OP_VUZPL, // VUZP, left result
4550     OP_VUZPR, // VUZP, right result
4551     OP_VZIPL, // VZIP, left result
4552     OP_VZIPR, // VZIP, right result
4553     OP_VTRNL, // VTRN, left result
4554     OP_VTRNR  // VTRN, right result
4555   };
4556
4557   if (OpNum == OP_COPY) {
4558     if (LHSID == (1*9+2)*9+3) return LHS;
4559     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4560     return RHS;
4561   }
4562
4563   SDValue OpLHS, OpRHS;
4564   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4565   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4566   EVT VT = OpLHS.getValueType();
4567
4568   switch (OpNum) {
4569   default: llvm_unreachable("Unknown shuffle opcode!");
4570   case OP_VREV:
4571     // VREV divides the vector in half and swaps within the half.
4572     if (VT.getVectorElementType() == MVT::i32 ||
4573         VT.getVectorElementType() == MVT::f32)
4574       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4575     // vrev <4 x i16> -> VREV32
4576     if (VT.getVectorElementType() == MVT::i16)
4577       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4578     // vrev <4 x i8> -> VREV16
4579     assert(VT.getVectorElementType() == MVT::i8);
4580     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4581   case OP_VDUP0:
4582   case OP_VDUP1:
4583   case OP_VDUP2:
4584   case OP_VDUP3:
4585     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4586                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4587   case OP_VEXT1:
4588   case OP_VEXT2:
4589   case OP_VEXT3:
4590     return DAG.getNode(ARMISD::VEXT, dl, VT,
4591                        OpLHS, OpRHS,
4592                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4593   case OP_VUZPL:
4594   case OP_VUZPR:
4595     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4596                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4597   case OP_VZIPL:
4598   case OP_VZIPR:
4599     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4600                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4601   case OP_VTRNL:
4602   case OP_VTRNR:
4603     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4604                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4605   }
4606 }
4607
4608 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4609                                        ArrayRef<int> ShuffleMask,
4610                                        SelectionDAG &DAG) {
4611   // Check to see if we can use the VTBL instruction.
4612   SDValue V1 = Op.getOperand(0);
4613   SDValue V2 = Op.getOperand(1);
4614   DebugLoc DL = Op.getDebugLoc();
4615
4616   SmallVector<SDValue, 8> VTBLMask;
4617   for (ArrayRef<int>::iterator
4618          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4619     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4620
4621   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4622     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4623                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4624                                    &VTBLMask[0], 8));
4625
4626   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4627                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4628                                  &VTBLMask[0], 8));
4629 }
4630
4631 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4632   SDValue V1 = Op.getOperand(0);
4633   SDValue V2 = Op.getOperand(1);
4634   DebugLoc dl = Op.getDebugLoc();
4635   EVT VT = Op.getValueType();
4636   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4637
4638   // Convert shuffles that are directly supported on NEON to target-specific
4639   // DAG nodes, instead of keeping them as shuffles and matching them again
4640   // during code selection.  This is more efficient and avoids the possibility
4641   // of inconsistencies between legalization and selection.
4642   // FIXME: floating-point vectors should be canonicalized to integer vectors
4643   // of the same time so that they get CSEd properly.
4644   ArrayRef<int> ShuffleMask = SVN->getMask();
4645
4646   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4647   if (EltSize <= 32) {
4648     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4649       int Lane = SVN->getSplatIndex();
4650       // If this is undef splat, generate it via "just" vdup, if possible.
4651       if (Lane == -1) Lane = 0;
4652
4653       // Test if V1 is a SCALAR_TO_VECTOR.
4654       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4655         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4656       }
4657       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4658       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4659       // reaches it).
4660       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4661           !isa<ConstantSDNode>(V1.getOperand(0))) {
4662         bool IsScalarToVector = true;
4663         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4664           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4665             IsScalarToVector = false;
4666             break;
4667           }
4668         if (IsScalarToVector)
4669           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4670       }
4671       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4672                          DAG.getConstant(Lane, MVT::i32));
4673     }
4674
4675     bool ReverseVEXT;
4676     unsigned Imm;
4677     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4678       if (ReverseVEXT)
4679         std::swap(V1, V2);
4680       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4681                          DAG.getConstant(Imm, MVT::i32));
4682     }
4683
4684     if (isVREVMask(ShuffleMask, VT, 64))
4685       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4686     if (isVREVMask(ShuffleMask, VT, 32))
4687       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4688     if (isVREVMask(ShuffleMask, VT, 16))
4689       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4690
4691     // Check for Neon shuffles that modify both input vectors in place.
4692     // If both results are used, i.e., if there are two shuffles with the same
4693     // source operands and with masks corresponding to both results of one of
4694     // these operations, DAG memoization will ensure that a single node is
4695     // used for both shuffles.
4696     unsigned WhichResult;
4697     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4698       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4699                          V1, V2).getValue(WhichResult);
4700     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4701       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4702                          V1, V2).getValue(WhichResult);
4703     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4704       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4705                          V1, V2).getValue(WhichResult);
4706
4707     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4708       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4709                          V1, V1).getValue(WhichResult);
4710     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4711       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4712                          V1, V1).getValue(WhichResult);
4713     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4714       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4715                          V1, V1).getValue(WhichResult);
4716   }
4717
4718   // If the shuffle is not directly supported and it has 4 elements, use
4719   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4720   unsigned NumElts = VT.getVectorNumElements();
4721   if (NumElts == 4) {
4722     unsigned PFIndexes[4];
4723     for (unsigned i = 0; i != 4; ++i) {
4724       if (ShuffleMask[i] < 0)
4725         PFIndexes[i] = 8;
4726       else
4727         PFIndexes[i] = ShuffleMask[i];
4728     }
4729
4730     // Compute the index in the perfect shuffle table.
4731     unsigned PFTableIndex =
4732       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4733     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4734     unsigned Cost = (PFEntry >> 30);
4735
4736     if (Cost <= 4)
4737       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4738   }
4739
4740   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4741   if (EltSize >= 32) {
4742     // Do the expansion with floating-point types, since that is what the VFP
4743     // registers are defined to use, and since i64 is not legal.
4744     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4745     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4746     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4747     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4748     SmallVector<SDValue, 8> Ops;
4749     for (unsigned i = 0; i < NumElts; ++i) {
4750       if (ShuffleMask[i] < 0)
4751         Ops.push_back(DAG.getUNDEF(EltVT));
4752       else
4753         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4754                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4755                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4756                                                   MVT::i32)));
4757     }
4758     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4759     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4760   }
4761
4762   if (VT == MVT::v8i8) {
4763     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4764     if (NewOp.getNode())
4765       return NewOp;
4766   }
4767
4768   return SDValue();
4769 }
4770
4771 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4772   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4773   SDValue Lane = Op.getOperand(2);
4774   if (!isa<ConstantSDNode>(Lane))
4775     return SDValue();
4776
4777   return Op;
4778 }
4779
4780 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4781   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4782   SDValue Lane = Op.getOperand(1);
4783   if (!isa<ConstantSDNode>(Lane))
4784     return SDValue();
4785
4786   SDValue Vec = Op.getOperand(0);
4787   if (Op.getValueType() == MVT::i32 &&
4788       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4789     DebugLoc dl = Op.getDebugLoc();
4790     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4791   }
4792
4793   return Op;
4794 }
4795
4796 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4797   // The only time a CONCAT_VECTORS operation can have legal types is when
4798   // two 64-bit vectors are concatenated to a 128-bit vector.
4799   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4800          "unexpected CONCAT_VECTORS");
4801   DebugLoc dl = Op.getDebugLoc();
4802   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4803   SDValue Op0 = Op.getOperand(0);
4804   SDValue Op1 = Op.getOperand(1);
4805   if (Op0.getOpcode() != ISD::UNDEF)
4806     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4807                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4808                       DAG.getIntPtrConstant(0));
4809   if (Op1.getOpcode() != ISD::UNDEF)
4810     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4811                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4812                       DAG.getIntPtrConstant(1));
4813   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4814 }
4815
4816 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4817 /// element has been zero/sign-extended, depending on the isSigned parameter,
4818 /// from an integer type half its size.
4819 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4820                                    bool isSigned) {
4821   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4822   EVT VT = N->getValueType(0);
4823   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4824     SDNode *BVN = N->getOperand(0).getNode();
4825     if (BVN->getValueType(0) != MVT::v4i32 ||
4826         BVN->getOpcode() != ISD::BUILD_VECTOR)
4827       return false;
4828     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4829     unsigned HiElt = 1 - LoElt;
4830     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4831     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4832     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4833     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4834     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4835       return false;
4836     if (isSigned) {
4837       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4838           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4839         return true;
4840     } else {
4841       if (Hi0->isNullValue() && Hi1->isNullValue())
4842         return true;
4843     }
4844     return false;
4845   }
4846
4847   if (N->getOpcode() != ISD::BUILD_VECTOR)
4848     return false;
4849
4850   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4851     SDNode *Elt = N->getOperand(i).getNode();
4852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4853       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4854       unsigned HalfSize = EltSize / 2;
4855       if (isSigned) {
4856         if (!isIntN(HalfSize, C->getSExtValue()))
4857           return false;
4858       } else {
4859         if (!isUIntN(HalfSize, C->getZExtValue()))
4860           return false;
4861       }
4862       continue;
4863     }
4864     return false;
4865   }
4866
4867   return true;
4868 }
4869
4870 /// isSignExtended - Check if a node is a vector value that is sign-extended
4871 /// or a constant BUILD_VECTOR with sign-extended elements.
4872 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4873   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4874     return true;
4875   if (isExtendedBUILD_VECTOR(N, DAG, true))
4876     return true;
4877   return false;
4878 }
4879
4880 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4881 /// or a constant BUILD_VECTOR with zero-extended elements.
4882 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4883   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4884     return true;
4885   if (isExtendedBUILD_VECTOR(N, DAG, false))
4886     return true;
4887   return false;
4888 }
4889
4890 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4891 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4892 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4893   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4894     return N->getOperand(0);
4895   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4896     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4897                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4898                        LD->isNonTemporal(), LD->isInvariant(),
4899                        LD->getAlignment());
4900   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4901   // have been legalized as a BITCAST from v4i32.
4902   if (N->getOpcode() == ISD::BITCAST) {
4903     SDNode *BVN = N->getOperand(0).getNode();
4904     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4905            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4906     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4907     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4908                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4909   }
4910   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4911   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4912   EVT VT = N->getValueType(0);
4913   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4914   unsigned NumElts = VT.getVectorNumElements();
4915   MVT TruncVT = MVT::getIntegerVT(EltSize);
4916   SmallVector<SDValue, 8> Ops;
4917   for (unsigned i = 0; i != NumElts; ++i) {
4918     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4919     const APInt &CInt = C->getAPIntValue();
4920     // Element types smaller than 32 bits are not legal, so use i32 elements.
4921     // The values are implicitly truncated so sext vs. zext doesn't matter.
4922     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4923   }
4924   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4925                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4926 }
4927
4928 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4929   unsigned Opcode = N->getOpcode();
4930   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4931     SDNode *N0 = N->getOperand(0).getNode();
4932     SDNode *N1 = N->getOperand(1).getNode();
4933     return N0->hasOneUse() && N1->hasOneUse() &&
4934       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4935   }
4936   return false;
4937 }
4938
4939 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4940   unsigned Opcode = N->getOpcode();
4941   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4942     SDNode *N0 = N->getOperand(0).getNode();
4943     SDNode *N1 = N->getOperand(1).getNode();
4944     return N0->hasOneUse() && N1->hasOneUse() &&
4945       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4946   }
4947   return false;
4948 }
4949
4950 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4951   // Multiplications are only custom-lowered for 128-bit vectors so that
4952   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4953   EVT VT = Op.getValueType();
4954   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4955   SDNode *N0 = Op.getOperand(0).getNode();
4956   SDNode *N1 = Op.getOperand(1).getNode();
4957   unsigned NewOpc = 0;
4958   bool isMLA = false;
4959   bool isN0SExt = isSignExtended(N0, DAG);
4960   bool isN1SExt = isSignExtended(N1, DAG);
4961   if (isN0SExt && isN1SExt)
4962     NewOpc = ARMISD::VMULLs;
4963   else {
4964     bool isN0ZExt = isZeroExtended(N0, DAG);
4965     bool isN1ZExt = isZeroExtended(N1, DAG);
4966     if (isN0ZExt && isN1ZExt)
4967       NewOpc = ARMISD::VMULLu;
4968     else if (isN1SExt || isN1ZExt) {
4969       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4970       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4971       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4972         NewOpc = ARMISD::VMULLs;
4973         isMLA = true;
4974       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4975         NewOpc = ARMISD::VMULLu;
4976         isMLA = true;
4977       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4978         std::swap(N0, N1);
4979         NewOpc = ARMISD::VMULLu;
4980         isMLA = true;
4981       }
4982     }
4983
4984     if (!NewOpc) {
4985       if (VT == MVT::v2i64)
4986         // Fall through to expand this.  It is not legal.
4987         return SDValue();
4988       else
4989         // Other vector multiplications are legal.
4990         return Op;
4991     }
4992   }
4993
4994   // Legalize to a VMULL instruction.
4995   DebugLoc DL = Op.getDebugLoc();
4996   SDValue Op0;
4997   SDValue Op1 = SkipExtension(N1, DAG);
4998   if (!isMLA) {
4999     Op0 = SkipExtension(N0, DAG);
5000     assert(Op0.getValueType().is64BitVector() &&
5001            Op1.getValueType().is64BitVector() &&
5002            "unexpected types for extended operands to VMULL");
5003     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5004   }
5005
5006   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5007   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5008   //   vmull q0, d4, d6
5009   //   vmlal q0, d5, d6
5010   // is faster than
5011   //   vaddl q0, d4, d5
5012   //   vmovl q1, d6
5013   //   vmul  q0, q0, q1
5014   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
5015   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
5016   EVT Op1VT = Op1.getValueType();
5017   return DAG.getNode(N0->getOpcode(), DL, VT,
5018                      DAG.getNode(NewOpc, DL, VT,
5019                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5020                      DAG.getNode(NewOpc, DL, VT,
5021                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5022 }
5023
5024 static SDValue
5025 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5026   // Convert to float
5027   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5028   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5029   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5030   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5031   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5032   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5033   // Get reciprocal estimate.
5034   // float4 recip = vrecpeq_f32(yf);
5035   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5036                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5037   // Because char has a smaller range than uchar, we can actually get away
5038   // without any newton steps.  This requires that we use a weird bias
5039   // of 0xb000, however (again, this has been exhaustively tested).
5040   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5041   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5042   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5043   Y = DAG.getConstant(0xb000, MVT::i32);
5044   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5045   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5046   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5047   // Convert back to short.
5048   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5049   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5050   return X;
5051 }
5052
5053 static SDValue
5054 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5055   SDValue N2;
5056   // Convert to float.
5057   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5058   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5059   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5060   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5061   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5062   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5063
5064   // Use reciprocal estimate and one refinement step.
5065   // float4 recip = vrecpeq_f32(yf);
5066   // recip *= vrecpsq_f32(yf, recip);
5067   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5068                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5069   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5070                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5071                    N1, N2);
5072   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5073   // Because short has a smaller range than ushort, we can actually get away
5074   // with only a single newton step.  This requires that we use a weird bias
5075   // of 89, however (again, this has been exhaustively tested).
5076   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5077   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5078   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5079   N1 = DAG.getConstant(0x89, MVT::i32);
5080   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5081   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5082   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5083   // Convert back to integer and return.
5084   // return vmovn_s32(vcvt_s32_f32(result));
5085   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5086   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5087   return N0;
5088 }
5089
5090 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5091   EVT VT = Op.getValueType();
5092   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5093          "unexpected type for custom-lowering ISD::SDIV");
5094
5095   DebugLoc dl = Op.getDebugLoc();
5096   SDValue N0 = Op.getOperand(0);
5097   SDValue N1 = Op.getOperand(1);
5098   SDValue N2, N3;
5099
5100   if (VT == MVT::v8i8) {
5101     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5102     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5103
5104     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5105                      DAG.getIntPtrConstant(4));
5106     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5107                      DAG.getIntPtrConstant(4));
5108     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5109                      DAG.getIntPtrConstant(0));
5110     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5111                      DAG.getIntPtrConstant(0));
5112
5113     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5114     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5115
5116     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5117     N0 = LowerCONCAT_VECTORS(N0, DAG);
5118
5119     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5120     return N0;
5121   }
5122   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5123 }
5124
5125 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5126   EVT VT = Op.getValueType();
5127   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5128          "unexpected type for custom-lowering ISD::UDIV");
5129
5130   DebugLoc dl = Op.getDebugLoc();
5131   SDValue N0 = Op.getOperand(0);
5132   SDValue N1 = Op.getOperand(1);
5133   SDValue N2, N3;
5134
5135   if (VT == MVT::v8i8) {
5136     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5137     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5138
5139     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5140                      DAG.getIntPtrConstant(4));
5141     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5142                      DAG.getIntPtrConstant(4));
5143     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5144                      DAG.getIntPtrConstant(0));
5145     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5146                      DAG.getIntPtrConstant(0));
5147
5148     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5149     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5150
5151     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5152     N0 = LowerCONCAT_VECTORS(N0, DAG);
5153
5154     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5155                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5156                      N0);
5157     return N0;
5158   }
5159
5160   // v4i16 sdiv ... Convert to float.
5161   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5162   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5163   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5164   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5165   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5166   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5167
5168   // Use reciprocal estimate and two refinement steps.
5169   // float4 recip = vrecpeq_f32(yf);
5170   // recip *= vrecpsq_f32(yf, recip);
5171   // recip *= vrecpsq_f32(yf, recip);
5172   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5173                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5174   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5175                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5176                    BN1, N2);
5177   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5178   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5179                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5180                    BN1, N2);
5181   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5182   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5183   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5184   // and that it will never cause us to return an answer too large).
5185   // float4 result = as_float4(as_int4(xf*recip) + 2);
5186   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5187   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5188   N1 = DAG.getConstant(2, MVT::i32);
5189   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5190   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5191   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5192   // Convert back to integer and return.
5193   // return vmovn_u32(vcvt_s32_f32(result));
5194   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5195   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5196   return N0;
5197 }
5198
5199 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5200   EVT VT = Op.getNode()->getValueType(0);
5201   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5202
5203   unsigned Opc;
5204   bool ExtraOp = false;
5205   switch (Op.getOpcode()) {
5206   default: llvm_unreachable("Invalid code");
5207   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5208   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5209   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5210   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5211   }
5212
5213   if (!ExtraOp)
5214     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5215                        Op.getOperand(1));
5216   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5217                      Op.getOperand(1), Op.getOperand(2));
5218 }
5219
5220 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5221   // Monotonic load/store is legal for all targets
5222   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5223     return Op;
5224
5225   // Aquire/Release load/store is not legal for targets without a
5226   // dmb or equivalent available.
5227   return SDValue();
5228 }
5229
5230
5231 static void
5232 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5233                     SelectionDAG &DAG, unsigned NewOp) {
5234   DebugLoc dl = Node->getDebugLoc();
5235   assert (Node->getValueType(0) == MVT::i64 &&
5236           "Only know how to expand i64 atomics");
5237
5238   SmallVector<SDValue, 6> Ops;
5239   Ops.push_back(Node->getOperand(0)); // Chain
5240   Ops.push_back(Node->getOperand(1)); // Ptr
5241   // Low part of Val1
5242   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5243                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5244   // High part of Val1
5245   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5246                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5247   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5248     // High part of Val1
5249     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5250                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5251     // High part of Val2
5252     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5253                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5254   }
5255   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5256   SDValue Result =
5257     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5258                             cast<MemSDNode>(Node)->getMemOperand());
5259   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5260   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5261   Results.push_back(Result.getValue(2));
5262 }
5263
5264 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5265   switch (Op.getOpcode()) {
5266   default: llvm_unreachable("Don't know how to custom lower this!");
5267   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5268   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5269   case ISD::GlobalAddress:
5270     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5271       LowerGlobalAddressELF(Op, DAG);
5272   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5273   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5274   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5275   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5276   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5277   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5278   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5279   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5280   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5281   case ISD::SINT_TO_FP:
5282   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5283   case ISD::FP_TO_SINT:
5284   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5285   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5286   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5287   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5288   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5289   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5290   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5291   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5292                                                                Subtarget);
5293   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5294   case ISD::SHL:
5295   case ISD::SRL:
5296   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5297   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5298   case ISD::SRL_PARTS:
5299   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5300   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5301   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5302   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5303   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5304   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5305   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5306   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5307   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5308   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5309   case ISD::MUL:           return LowerMUL(Op, DAG);
5310   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5311   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5312   case ISD::ADDC:
5313   case ISD::ADDE:
5314   case ISD::SUBC:
5315   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5316   case ISD::ATOMIC_LOAD:
5317   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5318   }
5319 }
5320
5321 /// ReplaceNodeResults - Replace the results of node with an illegal result
5322 /// type with new values built out of custom code.
5323 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5324                                            SmallVectorImpl<SDValue>&Results,
5325                                            SelectionDAG &DAG) const {
5326   SDValue Res;
5327   switch (N->getOpcode()) {
5328   default:
5329     llvm_unreachable("Don't know how to custom expand this!");
5330   case ISD::BITCAST:
5331     Res = ExpandBITCAST(N, DAG);
5332     break;
5333   case ISD::SRL:
5334   case ISD::SRA:
5335     Res = Expand64BitShift(N, DAG, Subtarget);
5336     break;
5337   case ISD::ATOMIC_LOAD_ADD:
5338     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5339     return;
5340   case ISD::ATOMIC_LOAD_AND:
5341     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5342     return;
5343   case ISD::ATOMIC_LOAD_NAND:
5344     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5345     return;
5346   case ISD::ATOMIC_LOAD_OR:
5347     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5348     return;
5349   case ISD::ATOMIC_LOAD_SUB:
5350     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5351     return;
5352   case ISD::ATOMIC_LOAD_XOR:
5353     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5354     return;
5355   case ISD::ATOMIC_SWAP:
5356     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5357     return;
5358   case ISD::ATOMIC_CMP_SWAP:
5359     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5360     return;
5361   }
5362   if (Res.getNode())
5363     Results.push_back(Res);
5364 }
5365
5366 //===----------------------------------------------------------------------===//
5367 //                           ARM Scheduler Hooks
5368 //===----------------------------------------------------------------------===//
5369
5370 MachineBasicBlock *
5371 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5372                                      MachineBasicBlock *BB,
5373                                      unsigned Size) const {
5374   unsigned dest    = MI->getOperand(0).getReg();
5375   unsigned ptr     = MI->getOperand(1).getReg();
5376   unsigned oldval  = MI->getOperand(2).getReg();
5377   unsigned newval  = MI->getOperand(3).getReg();
5378   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5379   DebugLoc dl = MI->getDebugLoc();
5380   bool isThumb2 = Subtarget->isThumb2();
5381
5382   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5383   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5384     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5385     (const TargetRegisterClass*)&ARM::GPRRegClass);
5386
5387   if (isThumb2) {
5388     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5389     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5390     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5391   }
5392
5393   unsigned ldrOpc, strOpc;
5394   switch (Size) {
5395   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5396   case 1:
5397     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5398     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5399     break;
5400   case 2:
5401     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5402     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5403     break;
5404   case 4:
5405     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5406     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5407     break;
5408   }
5409
5410   MachineFunction *MF = BB->getParent();
5411   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5412   MachineFunction::iterator It = BB;
5413   ++It; // insert the new blocks after the current block
5414
5415   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5416   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5417   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5418   MF->insert(It, loop1MBB);
5419   MF->insert(It, loop2MBB);
5420   MF->insert(It, exitMBB);
5421
5422   // Transfer the remainder of BB and its successor edges to exitMBB.
5423   exitMBB->splice(exitMBB->begin(), BB,
5424                   llvm::next(MachineBasicBlock::iterator(MI)),
5425                   BB->end());
5426   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5427
5428   //  thisMBB:
5429   //   ...
5430   //   fallthrough --> loop1MBB
5431   BB->addSuccessor(loop1MBB);
5432
5433   // loop1MBB:
5434   //   ldrex dest, [ptr]
5435   //   cmp dest, oldval
5436   //   bne exitMBB
5437   BB = loop1MBB;
5438   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5439   if (ldrOpc == ARM::t2LDREX)
5440     MIB.addImm(0);
5441   AddDefaultPred(MIB);
5442   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5443                  .addReg(dest).addReg(oldval));
5444   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5445     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5446   BB->addSuccessor(loop2MBB);
5447   BB->addSuccessor(exitMBB);
5448
5449   // loop2MBB:
5450   //   strex scratch, newval, [ptr]
5451   //   cmp scratch, #0
5452   //   bne loop1MBB
5453   BB = loop2MBB;
5454   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5455   if (strOpc == ARM::t2STREX)
5456     MIB.addImm(0);
5457   AddDefaultPred(MIB);
5458   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5459                  .addReg(scratch).addImm(0));
5460   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5461     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5462   BB->addSuccessor(loop1MBB);
5463   BB->addSuccessor(exitMBB);
5464
5465   //  exitMBB:
5466   //   ...
5467   BB = exitMBB;
5468
5469   MI->eraseFromParent();   // The instruction is gone now.
5470
5471   return BB;
5472 }
5473
5474 MachineBasicBlock *
5475 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5476                                     unsigned Size, unsigned BinOpcode) const {
5477   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5478   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5479
5480   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5481   MachineFunction *MF = BB->getParent();
5482   MachineFunction::iterator It = BB;
5483   ++It;
5484
5485   unsigned dest = MI->getOperand(0).getReg();
5486   unsigned ptr = MI->getOperand(1).getReg();
5487   unsigned incr = MI->getOperand(2).getReg();
5488   DebugLoc dl = MI->getDebugLoc();
5489   bool isThumb2 = Subtarget->isThumb2();
5490
5491   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5492   if (isThumb2) {
5493     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5494     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5495   }
5496
5497   unsigned ldrOpc, strOpc;
5498   switch (Size) {
5499   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5500   case 1:
5501     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5502     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5503     break;
5504   case 2:
5505     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5506     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5507     break;
5508   case 4:
5509     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5510     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5511     break;
5512   }
5513
5514   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5515   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5516   MF->insert(It, loopMBB);
5517   MF->insert(It, exitMBB);
5518
5519   // Transfer the remainder of BB and its successor edges to exitMBB.
5520   exitMBB->splice(exitMBB->begin(), BB,
5521                   llvm::next(MachineBasicBlock::iterator(MI)),
5522                   BB->end());
5523   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5524
5525   const TargetRegisterClass *TRC = isThumb2 ?
5526     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5527     (const TargetRegisterClass*)&ARM::GPRRegClass;
5528   unsigned scratch = MRI.createVirtualRegister(TRC);
5529   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5530
5531   //  thisMBB:
5532   //   ...
5533   //   fallthrough --> loopMBB
5534   BB->addSuccessor(loopMBB);
5535
5536   //  loopMBB:
5537   //   ldrex dest, ptr
5538   //   <binop> scratch2, dest, incr
5539   //   strex scratch, scratch2, ptr
5540   //   cmp scratch, #0
5541   //   bne- loopMBB
5542   //   fallthrough --> exitMBB
5543   BB = loopMBB;
5544   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5545   if (ldrOpc == ARM::t2LDREX)
5546     MIB.addImm(0);
5547   AddDefaultPred(MIB);
5548   if (BinOpcode) {
5549     // operand order needs to go the other way for NAND
5550     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5551       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5552                      addReg(incr).addReg(dest)).addReg(0);
5553     else
5554       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5555                      addReg(dest).addReg(incr)).addReg(0);
5556   }
5557
5558   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5559   if (strOpc == ARM::t2STREX)
5560     MIB.addImm(0);
5561   AddDefaultPred(MIB);
5562   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5563                  .addReg(scratch).addImm(0));
5564   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5565     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5566
5567   BB->addSuccessor(loopMBB);
5568   BB->addSuccessor(exitMBB);
5569
5570   //  exitMBB:
5571   //   ...
5572   BB = exitMBB;
5573
5574   MI->eraseFromParent();   // The instruction is gone now.
5575
5576   return BB;
5577 }
5578
5579 MachineBasicBlock *
5580 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5581                                           MachineBasicBlock *BB,
5582                                           unsigned Size,
5583                                           bool signExtend,
5584                                           ARMCC::CondCodes Cond) const {
5585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5586
5587   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5588   MachineFunction *MF = BB->getParent();
5589   MachineFunction::iterator It = BB;
5590   ++It;
5591
5592   unsigned dest = MI->getOperand(0).getReg();
5593   unsigned ptr = MI->getOperand(1).getReg();
5594   unsigned incr = MI->getOperand(2).getReg();
5595   unsigned oldval = dest;
5596   DebugLoc dl = MI->getDebugLoc();
5597   bool isThumb2 = Subtarget->isThumb2();
5598
5599   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5600   if (isThumb2) {
5601     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5602     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5603   }
5604
5605   unsigned ldrOpc, strOpc, extendOpc;
5606   switch (Size) {
5607   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5608   case 1:
5609     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5610     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5611     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5612     break;
5613   case 2:
5614     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5615     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5616     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5617     break;
5618   case 4:
5619     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5620     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5621     extendOpc = 0;
5622     break;
5623   }
5624
5625   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5626   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5627   MF->insert(It, loopMBB);
5628   MF->insert(It, exitMBB);
5629
5630   // Transfer the remainder of BB and its successor edges to exitMBB.
5631   exitMBB->splice(exitMBB->begin(), BB,
5632                   llvm::next(MachineBasicBlock::iterator(MI)),
5633                   BB->end());
5634   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5635
5636   const TargetRegisterClass *TRC = isThumb2 ?
5637     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5638     (const TargetRegisterClass*)&ARM::GPRRegClass;
5639   unsigned scratch = MRI.createVirtualRegister(TRC);
5640   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5641
5642   //  thisMBB:
5643   //   ...
5644   //   fallthrough --> loopMBB
5645   BB->addSuccessor(loopMBB);
5646
5647   //  loopMBB:
5648   //   ldrex dest, ptr
5649   //   (sign extend dest, if required)
5650   //   cmp dest, incr
5651   //   cmov.cond scratch2, incr, dest
5652   //   strex scratch, scratch2, ptr
5653   //   cmp scratch, #0
5654   //   bne- loopMBB
5655   //   fallthrough --> exitMBB
5656   BB = loopMBB;
5657   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5658   if (ldrOpc == ARM::t2LDREX)
5659     MIB.addImm(0);
5660   AddDefaultPred(MIB);
5661
5662   // Sign extend the value, if necessary.
5663   if (signExtend && extendOpc) {
5664     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5665     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5666                      .addReg(dest)
5667                      .addImm(0));
5668   }
5669
5670   // Build compare and cmov instructions.
5671   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5672                  .addReg(oldval).addReg(incr));
5673   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5674          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5675
5676   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5677   if (strOpc == ARM::t2STREX)
5678     MIB.addImm(0);
5679   AddDefaultPred(MIB);
5680   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5681                  .addReg(scratch).addImm(0));
5682   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5683     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5684
5685   BB->addSuccessor(loopMBB);
5686   BB->addSuccessor(exitMBB);
5687
5688   //  exitMBB:
5689   //   ...
5690   BB = exitMBB;
5691
5692   MI->eraseFromParent();   // The instruction is gone now.
5693
5694   return BB;
5695 }
5696
5697 MachineBasicBlock *
5698 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5699                                       unsigned Op1, unsigned Op2,
5700                                       bool NeedsCarry, bool IsCmpxchg) const {
5701   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5702   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5703
5704   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5705   MachineFunction *MF = BB->getParent();
5706   MachineFunction::iterator It = BB;
5707   ++It;
5708
5709   unsigned destlo = MI->getOperand(0).getReg();
5710   unsigned desthi = MI->getOperand(1).getReg();
5711   unsigned ptr = MI->getOperand(2).getReg();
5712   unsigned vallo = MI->getOperand(3).getReg();
5713   unsigned valhi = MI->getOperand(4).getReg();
5714   DebugLoc dl = MI->getDebugLoc();
5715   bool isThumb2 = Subtarget->isThumb2();
5716
5717   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5718   if (isThumb2) {
5719     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5720     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5721     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5722   }
5723
5724   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5725   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5726
5727   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5728   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5729   if (IsCmpxchg) {
5730     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5731     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5732   }
5733   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5734   MF->insert(It, loopMBB);
5735   if (IsCmpxchg) {
5736     MF->insert(It, contBB);
5737     MF->insert(It, cont2BB);
5738   }
5739   MF->insert(It, exitMBB);
5740
5741   // Transfer the remainder of BB and its successor edges to exitMBB.
5742   exitMBB->splice(exitMBB->begin(), BB,
5743                   llvm::next(MachineBasicBlock::iterator(MI)),
5744                   BB->end());
5745   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5746
5747   const TargetRegisterClass *TRC = isThumb2 ?
5748     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5749     (const TargetRegisterClass*)&ARM::GPRRegClass;
5750   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5751
5752   //  thisMBB:
5753   //   ...
5754   //   fallthrough --> loopMBB
5755   BB->addSuccessor(loopMBB);
5756
5757   //  loopMBB:
5758   //   ldrexd r2, r3, ptr
5759   //   <binopa> r0, r2, incr
5760   //   <binopb> r1, r3, incr
5761   //   strexd storesuccess, r0, r1, ptr
5762   //   cmp storesuccess, #0
5763   //   bne- loopMBB
5764   //   fallthrough --> exitMBB
5765   //
5766   // Note that the registers are explicitly specified because there is not any
5767   // way to force the register allocator to allocate a register pair.
5768   //
5769   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5770   // need to properly enforce the restriction that the two output registers
5771   // for ldrexd must be different.
5772   BB = loopMBB;
5773   // Load
5774   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5775                  .addReg(ARM::R2, RegState::Define)
5776                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5777   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5778   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5779   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5780
5781   if (IsCmpxchg) {
5782     // Add early exit
5783     for (unsigned i = 0; i < 2; i++) {
5784       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5785                                                          ARM::CMPrr))
5786                      .addReg(i == 0 ? destlo : desthi)
5787                      .addReg(i == 0 ? vallo : valhi));
5788       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5789         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5790       BB->addSuccessor(exitMBB);
5791       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5792       BB = (i == 0 ? contBB : cont2BB);
5793     }
5794
5795     // Copy to physregs for strexd
5796     unsigned setlo = MI->getOperand(5).getReg();
5797     unsigned sethi = MI->getOperand(6).getReg();
5798     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5799     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5800   } else if (Op1) {
5801     // Perform binary operation
5802     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5803                    .addReg(destlo).addReg(vallo))
5804         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5805     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5806                    .addReg(desthi).addReg(valhi)).addReg(0);
5807   } else {
5808     // Copy to physregs for strexd
5809     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5810     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5811   }
5812
5813   // Store
5814   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5815                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5816   // Cmp+jump
5817   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5818                  .addReg(storesuccess).addImm(0));
5819   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5820     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5821
5822   BB->addSuccessor(loopMBB);
5823   BB->addSuccessor(exitMBB);
5824
5825   //  exitMBB:
5826   //   ...
5827   BB = exitMBB;
5828
5829   MI->eraseFromParent();   // The instruction is gone now.
5830
5831   return BB;
5832 }
5833
5834 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5835 /// registers the function context.
5836 void ARMTargetLowering::
5837 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5838                        MachineBasicBlock *DispatchBB, int FI) const {
5839   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5840   DebugLoc dl = MI->getDebugLoc();
5841   MachineFunction *MF = MBB->getParent();
5842   MachineRegisterInfo *MRI = &MF->getRegInfo();
5843   MachineConstantPool *MCP = MF->getConstantPool();
5844   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5845   const Function *F = MF->getFunction();
5846
5847   bool isThumb = Subtarget->isThumb();
5848   bool isThumb2 = Subtarget->isThumb2();
5849
5850   unsigned PCLabelId = AFI->createPICLabelUId();
5851   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5852   ARMConstantPoolValue *CPV =
5853     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5854   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5855
5856   const TargetRegisterClass *TRC = isThumb ?
5857     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5858     (const TargetRegisterClass*)&ARM::GPRRegClass;
5859
5860   // Grab constant pool and fixed stack memory operands.
5861   MachineMemOperand *CPMMO =
5862     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5863                              MachineMemOperand::MOLoad, 4, 4);
5864
5865   MachineMemOperand *FIMMOSt =
5866     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5867                              MachineMemOperand::MOStore, 4, 4);
5868
5869   // Load the address of the dispatch MBB into the jump buffer.
5870   if (isThumb2) {
5871     // Incoming value: jbuf
5872     //   ldr.n  r5, LCPI1_1
5873     //   orr    r5, r5, #1
5874     //   add    r5, pc
5875     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5876     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5877     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5878                    .addConstantPoolIndex(CPI)
5879                    .addMemOperand(CPMMO));
5880     // Set the low bit because of thumb mode.
5881     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5882     AddDefaultCC(
5883       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5884                      .addReg(NewVReg1, RegState::Kill)
5885                      .addImm(0x01)));
5886     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5887     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5888       .addReg(NewVReg2, RegState::Kill)
5889       .addImm(PCLabelId);
5890     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5891                    .addReg(NewVReg3, RegState::Kill)
5892                    .addFrameIndex(FI)
5893                    .addImm(36)  // &jbuf[1] :: pc
5894                    .addMemOperand(FIMMOSt));
5895   } else if (isThumb) {
5896     // Incoming value: jbuf
5897     //   ldr.n  r1, LCPI1_4
5898     //   add    r1, pc
5899     //   mov    r2, #1
5900     //   orrs   r1, r2
5901     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5902     //   str    r1, [r2]
5903     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5904     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5905                    .addConstantPoolIndex(CPI)
5906                    .addMemOperand(CPMMO));
5907     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5908     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5909       .addReg(NewVReg1, RegState::Kill)
5910       .addImm(PCLabelId);
5911     // Set the low bit because of thumb mode.
5912     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5913     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5914                    .addReg(ARM::CPSR, RegState::Define)
5915                    .addImm(1));
5916     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5917     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5918                    .addReg(ARM::CPSR, RegState::Define)
5919                    .addReg(NewVReg2, RegState::Kill)
5920                    .addReg(NewVReg3, RegState::Kill));
5921     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5922     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5923                    .addFrameIndex(FI)
5924                    .addImm(36)); // &jbuf[1] :: pc
5925     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5926                    .addReg(NewVReg4, RegState::Kill)
5927                    .addReg(NewVReg5, RegState::Kill)
5928                    .addImm(0)
5929                    .addMemOperand(FIMMOSt));
5930   } else {
5931     // Incoming value: jbuf
5932     //   ldr  r1, LCPI1_1
5933     //   add  r1, pc, r1
5934     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5935     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5936     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5937                    .addConstantPoolIndex(CPI)
5938                    .addImm(0)
5939                    .addMemOperand(CPMMO));
5940     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5941     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5942                    .addReg(NewVReg1, RegState::Kill)
5943                    .addImm(PCLabelId));
5944     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5945                    .addReg(NewVReg2, RegState::Kill)
5946                    .addFrameIndex(FI)
5947                    .addImm(36)  // &jbuf[1] :: pc
5948                    .addMemOperand(FIMMOSt));
5949   }
5950 }
5951
5952 MachineBasicBlock *ARMTargetLowering::
5953 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5954   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5955   DebugLoc dl = MI->getDebugLoc();
5956   MachineFunction *MF = MBB->getParent();
5957   MachineRegisterInfo *MRI = &MF->getRegInfo();
5958   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5959   MachineFrameInfo *MFI = MF->getFrameInfo();
5960   int FI = MFI->getFunctionContextIndex();
5961
5962   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5963     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5964     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5965
5966   // Get a mapping of the call site numbers to all of the landing pads they're
5967   // associated with.
5968   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5969   unsigned MaxCSNum = 0;
5970   MachineModuleInfo &MMI = MF->getMMI();
5971   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5972        ++BB) {
5973     if (!BB->isLandingPad()) continue;
5974
5975     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5976     // pad.
5977     for (MachineBasicBlock::iterator
5978            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5979       if (!II->isEHLabel()) continue;
5980
5981       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5982       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5983
5984       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5985       for (SmallVectorImpl<unsigned>::iterator
5986              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5987            CSI != CSE; ++CSI) {
5988         CallSiteNumToLPad[*CSI].push_back(BB);
5989         MaxCSNum = std::max(MaxCSNum, *CSI);
5990       }
5991       break;
5992     }
5993   }
5994
5995   // Get an ordered list of the machine basic blocks for the jump table.
5996   std::vector<MachineBasicBlock*> LPadList;
5997   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5998   LPadList.reserve(CallSiteNumToLPad.size());
5999   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6000     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6001     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6002            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6003       LPadList.push_back(*II);
6004       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6005     }
6006   }
6007
6008   assert(!LPadList.empty() &&
6009          "No landing pad destinations for the dispatch jump table!");
6010
6011   // Create the jump table and associated information.
6012   MachineJumpTableInfo *JTI =
6013     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6014   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6015   unsigned UId = AFI->createJumpTableUId();
6016
6017   // Create the MBBs for the dispatch code.
6018
6019   // Shove the dispatch's address into the return slot in the function context.
6020   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6021   DispatchBB->setIsLandingPad();
6022
6023   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6024   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6025   DispatchBB->addSuccessor(TrapBB);
6026
6027   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6028   DispatchBB->addSuccessor(DispContBB);
6029
6030   // Insert and MBBs.
6031   MF->insert(MF->end(), DispatchBB);
6032   MF->insert(MF->end(), DispContBB);
6033   MF->insert(MF->end(), TrapBB);
6034
6035   // Insert code into the entry block that creates and registers the function
6036   // context.
6037   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6038
6039   MachineMemOperand *FIMMOLd =
6040     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6041                              MachineMemOperand::MOLoad |
6042                              MachineMemOperand::MOVolatile, 4, 4);
6043
6044   if (AFI->isThumb1OnlyFunction())
6045     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
6046   else if (!Subtarget->hasVFP2())
6047     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
6048   else
6049     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6050
6051   unsigned NumLPads = LPadList.size();
6052   if (Subtarget->isThumb2()) {
6053     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6054     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6055                    .addFrameIndex(FI)
6056                    .addImm(4)
6057                    .addMemOperand(FIMMOLd));
6058
6059     if (NumLPads < 256) {
6060       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6061                      .addReg(NewVReg1)
6062                      .addImm(LPadList.size()));
6063     } else {
6064       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6065       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6066                      .addImm(NumLPads & 0xFFFF));
6067
6068       unsigned VReg2 = VReg1;
6069       if ((NumLPads & 0xFFFF0000) != 0) {
6070         VReg2 = MRI->createVirtualRegister(TRC);
6071         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6072                        .addReg(VReg1)
6073                        .addImm(NumLPads >> 16));
6074       }
6075
6076       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6077                      .addReg(NewVReg1)
6078                      .addReg(VReg2));
6079     }
6080
6081     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6082       .addMBB(TrapBB)
6083       .addImm(ARMCC::HI)
6084       .addReg(ARM::CPSR);
6085
6086     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6087     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6088                    .addJumpTableIndex(MJTI)
6089                    .addImm(UId));
6090
6091     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6092     AddDefaultCC(
6093       AddDefaultPred(
6094         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6095         .addReg(NewVReg3, RegState::Kill)
6096         .addReg(NewVReg1)
6097         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6098
6099     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6100       .addReg(NewVReg4, RegState::Kill)
6101       .addReg(NewVReg1)
6102       .addJumpTableIndex(MJTI)
6103       .addImm(UId);
6104   } else if (Subtarget->isThumb()) {
6105     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6106     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6107                    .addFrameIndex(FI)
6108                    .addImm(1)
6109                    .addMemOperand(FIMMOLd));
6110
6111     if (NumLPads < 256) {
6112       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6113                      .addReg(NewVReg1)
6114                      .addImm(NumLPads));
6115     } else {
6116       MachineConstantPool *ConstantPool = MF->getConstantPool();
6117       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6118       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6119
6120       // MachineConstantPool wants an explicit alignment.
6121       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6122       if (Align == 0)
6123         Align = getDataLayout()->getTypeAllocSize(C->getType());
6124       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6125
6126       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6127       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6128                      .addReg(VReg1, RegState::Define)
6129                      .addConstantPoolIndex(Idx));
6130       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6131                      .addReg(NewVReg1)
6132                      .addReg(VReg1));
6133     }
6134
6135     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6136       .addMBB(TrapBB)
6137       .addImm(ARMCC::HI)
6138       .addReg(ARM::CPSR);
6139
6140     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6141     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6142                    .addReg(ARM::CPSR, RegState::Define)
6143                    .addReg(NewVReg1)
6144                    .addImm(2));
6145
6146     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6147     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6148                    .addJumpTableIndex(MJTI)
6149                    .addImm(UId));
6150
6151     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6152     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6153                    .addReg(ARM::CPSR, RegState::Define)
6154                    .addReg(NewVReg2, RegState::Kill)
6155                    .addReg(NewVReg3));
6156
6157     MachineMemOperand *JTMMOLd =
6158       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6159                                MachineMemOperand::MOLoad, 4, 4);
6160
6161     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6162     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6163                    .addReg(NewVReg4, RegState::Kill)
6164                    .addImm(0)
6165                    .addMemOperand(JTMMOLd));
6166
6167     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6168     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6169                    .addReg(ARM::CPSR, RegState::Define)
6170                    .addReg(NewVReg5, RegState::Kill)
6171                    .addReg(NewVReg3));
6172
6173     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6174       .addReg(NewVReg6, RegState::Kill)
6175       .addJumpTableIndex(MJTI)
6176       .addImm(UId);
6177   } else {
6178     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6179     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6180                    .addFrameIndex(FI)
6181                    .addImm(4)
6182                    .addMemOperand(FIMMOLd));
6183
6184     if (NumLPads < 256) {
6185       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6186                      .addReg(NewVReg1)
6187                      .addImm(NumLPads));
6188     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6189       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6190       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6191                      .addImm(NumLPads & 0xFFFF));
6192
6193       unsigned VReg2 = VReg1;
6194       if ((NumLPads & 0xFFFF0000) != 0) {
6195         VReg2 = MRI->createVirtualRegister(TRC);
6196         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6197                        .addReg(VReg1)
6198                        .addImm(NumLPads >> 16));
6199       }
6200
6201       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6202                      .addReg(NewVReg1)
6203                      .addReg(VReg2));
6204     } else {
6205       MachineConstantPool *ConstantPool = MF->getConstantPool();
6206       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6207       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6208
6209       // MachineConstantPool wants an explicit alignment.
6210       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6211       if (Align == 0)
6212         Align = getDataLayout()->getTypeAllocSize(C->getType());
6213       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6214
6215       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6216       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6217                      .addReg(VReg1, RegState::Define)
6218                      .addConstantPoolIndex(Idx)
6219                      .addImm(0));
6220       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6221                      .addReg(NewVReg1)
6222                      .addReg(VReg1, RegState::Kill));
6223     }
6224
6225     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6226       .addMBB(TrapBB)
6227       .addImm(ARMCC::HI)
6228       .addReg(ARM::CPSR);
6229
6230     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6231     AddDefaultCC(
6232       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6233                      .addReg(NewVReg1)
6234                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6235     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6236     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6237                    .addJumpTableIndex(MJTI)
6238                    .addImm(UId));
6239
6240     MachineMemOperand *JTMMOLd =
6241       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6242                                MachineMemOperand::MOLoad, 4, 4);
6243     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6244     AddDefaultPred(
6245       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6246       .addReg(NewVReg3, RegState::Kill)
6247       .addReg(NewVReg4)
6248       .addImm(0)
6249       .addMemOperand(JTMMOLd));
6250
6251     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6252       .addReg(NewVReg5, RegState::Kill)
6253       .addReg(NewVReg4)
6254       .addJumpTableIndex(MJTI)
6255       .addImm(UId);
6256   }
6257
6258   // Add the jump table entries as successors to the MBB.
6259   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6260   for (std::vector<MachineBasicBlock*>::iterator
6261          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6262     MachineBasicBlock *CurMBB = *I;
6263     if (SeenMBBs.insert(CurMBB))
6264       DispContBB->addSuccessor(CurMBB);
6265   }
6266
6267   // N.B. the order the invoke BBs are processed in doesn't matter here.
6268   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6269   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6270   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6271   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6272   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6273          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6274     MachineBasicBlock *BB = *I;
6275
6276     // Remove the landing pad successor from the invoke block and replace it
6277     // with the new dispatch block.
6278     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6279                                                   BB->succ_end());
6280     while (!Successors.empty()) {
6281       MachineBasicBlock *SMBB = Successors.pop_back_val();
6282       if (SMBB->isLandingPad()) {
6283         BB->removeSuccessor(SMBB);
6284         MBBLPads.push_back(SMBB);
6285       }
6286     }
6287
6288     BB->addSuccessor(DispatchBB);
6289
6290     // Find the invoke call and mark all of the callee-saved registers as
6291     // 'implicit defined' so that they're spilled. This prevents code from
6292     // moving instructions to before the EH block, where they will never be
6293     // executed.
6294     for (MachineBasicBlock::reverse_iterator
6295            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6296       if (!II->isCall()) continue;
6297
6298       DenseMap<unsigned, bool> DefRegs;
6299       for (MachineInstr::mop_iterator
6300              OI = II->operands_begin(), OE = II->operands_end();
6301            OI != OE; ++OI) {
6302         if (!OI->isReg()) continue;
6303         DefRegs[OI->getReg()] = true;
6304       }
6305
6306       MachineInstrBuilder MIB(&*II);
6307
6308       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6309         unsigned Reg = SavedRegs[i];
6310         if (Subtarget->isThumb2() &&
6311             !ARM::tGPRRegClass.contains(Reg) &&
6312             !ARM::hGPRRegClass.contains(Reg))
6313           continue;
6314         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6315           continue;
6316         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6317           continue;
6318         if (!DefRegs[Reg])
6319           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6320       }
6321
6322       break;
6323     }
6324   }
6325
6326   // Mark all former landing pads as non-landing pads. The dispatch is the only
6327   // landing pad now.
6328   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6329          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6330     (*I)->setIsLandingPad(false);
6331
6332   // The instruction is gone now.
6333   MI->eraseFromParent();
6334
6335   return MBB;
6336 }
6337
6338 static
6339 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6340   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6341        E = MBB->succ_end(); I != E; ++I)
6342     if (*I != Succ)
6343       return *I;
6344   llvm_unreachable("Expecting a BB with two successors!");
6345 }
6346
6347 MachineBasicBlock *ARMTargetLowering::
6348 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6349   // This pseudo instruction has 3 operands: dst, src, size
6350   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6351   // Otherwise, we will generate unrolled scalar copies.
6352   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6353   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6354   MachineFunction::iterator It = BB;
6355   ++It;
6356
6357   unsigned dest = MI->getOperand(0).getReg();
6358   unsigned src = MI->getOperand(1).getReg();
6359   unsigned SizeVal = MI->getOperand(2).getImm();
6360   unsigned Align = MI->getOperand(3).getImm();
6361   DebugLoc dl = MI->getDebugLoc();
6362
6363   bool isThumb2 = Subtarget->isThumb2();
6364   MachineFunction *MF = BB->getParent();
6365   MachineRegisterInfo &MRI = MF->getRegInfo();
6366   unsigned ldrOpc, strOpc, UnitSize = 0;
6367
6368   const TargetRegisterClass *TRC = isThumb2 ?
6369     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6370     (const TargetRegisterClass*)&ARM::GPRRegClass;
6371   const TargetRegisterClass *TRC_Vec = 0;
6372
6373   if (Align & 1) {
6374     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6375     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6376     UnitSize = 1;
6377   } else if (Align & 2) {
6378     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6379     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6380     UnitSize = 2;
6381   } else {
6382     // Check whether we can use NEON instructions.
6383     if (!MF->getFunction()->getFnAttributes().
6384           hasAttribute(Attributes::NoImplicitFloat) &&
6385         Subtarget->hasNEON()) {
6386       if ((Align % 16 == 0) && SizeVal >= 16) {
6387         ldrOpc = ARM::VLD1q32wb_fixed;
6388         strOpc = ARM::VST1q32wb_fixed;
6389         UnitSize = 16;
6390         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6391       }
6392       else if ((Align % 8 == 0) && SizeVal >= 8) {
6393         ldrOpc = ARM::VLD1d32wb_fixed;
6394         strOpc = ARM::VST1d32wb_fixed;
6395         UnitSize = 8;
6396         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6397       }
6398     }
6399     // Can't use NEON instructions.
6400     if (UnitSize == 0) {
6401       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6402       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6403       UnitSize = 4;
6404     }
6405   }
6406
6407   unsigned BytesLeft = SizeVal % UnitSize;
6408   unsigned LoopSize = SizeVal - BytesLeft;
6409
6410   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6411     // Use LDR and STR to copy.
6412     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6413     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6414     unsigned srcIn = src;
6415     unsigned destIn = dest;
6416     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6417       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6418       unsigned srcOut = MRI.createVirtualRegister(TRC);
6419       unsigned destOut = MRI.createVirtualRegister(TRC);
6420       if (UnitSize >= 8) {
6421         AddDefaultPred(BuildMI(*BB, MI, dl,
6422           TII->get(ldrOpc), scratch)
6423           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6424
6425         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6426           .addReg(destIn).addImm(0).addReg(scratch));
6427       } else if (isThumb2) {
6428         AddDefaultPred(BuildMI(*BB, MI, dl,
6429           TII->get(ldrOpc), scratch)
6430           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6431
6432         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6433           .addReg(scratch).addReg(destIn)
6434           .addImm(UnitSize));
6435       } else {
6436         AddDefaultPred(BuildMI(*BB, MI, dl,
6437           TII->get(ldrOpc), scratch)
6438           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6439           .addImm(UnitSize));
6440
6441         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6442           .addReg(scratch).addReg(destIn)
6443           .addReg(0).addImm(UnitSize));
6444       }
6445       srcIn = srcOut;
6446       destIn = destOut;
6447     }
6448
6449     // Handle the leftover bytes with LDRB and STRB.
6450     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6451     // [destOut] = STRB_POST(scratch, destIn, 1)
6452     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6453     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6454     for (unsigned i = 0; i < BytesLeft; i++) {
6455       unsigned scratch = MRI.createVirtualRegister(TRC);
6456       unsigned srcOut = MRI.createVirtualRegister(TRC);
6457       unsigned destOut = MRI.createVirtualRegister(TRC);
6458       if (isThumb2) {
6459         AddDefaultPred(BuildMI(*BB, MI, dl,
6460           TII->get(ldrOpc),scratch)
6461           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6462
6463         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6464           .addReg(scratch).addReg(destIn)
6465           .addReg(0).addImm(1));
6466       } else {
6467         AddDefaultPred(BuildMI(*BB, MI, dl,
6468           TII->get(ldrOpc),scratch)
6469           .addReg(srcOut, RegState::Define).addReg(srcIn)
6470           .addReg(0).addImm(1));
6471
6472         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6473           .addReg(scratch).addReg(destIn)
6474           .addReg(0).addImm(1));
6475       }
6476       srcIn = srcOut;
6477       destIn = destOut;
6478     }
6479     MI->eraseFromParent();   // The instruction is gone now.
6480     return BB;
6481   }
6482
6483   // Expand the pseudo op to a loop.
6484   // thisMBB:
6485   //   ...
6486   //   movw varEnd, # --> with thumb2
6487   //   movt varEnd, #
6488   //   ldrcp varEnd, idx --> without thumb2
6489   //   fallthrough --> loopMBB
6490   // loopMBB:
6491   //   PHI varPhi, varEnd, varLoop
6492   //   PHI srcPhi, src, srcLoop
6493   //   PHI destPhi, dst, destLoop
6494   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6495   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6496   //   subs varLoop, varPhi, #UnitSize
6497   //   bne loopMBB
6498   //   fallthrough --> exitMBB
6499   // exitMBB:
6500   //   epilogue to handle left-over bytes
6501   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6502   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6503   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6504   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6505   MF->insert(It, loopMBB);
6506   MF->insert(It, exitMBB);
6507
6508   // Transfer the remainder of BB and its successor edges to exitMBB.
6509   exitMBB->splice(exitMBB->begin(), BB,
6510                   llvm::next(MachineBasicBlock::iterator(MI)),
6511                   BB->end());
6512   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6513
6514   // Load an immediate to varEnd.
6515   unsigned varEnd = MRI.createVirtualRegister(TRC);
6516   if (isThumb2) {
6517     unsigned VReg1 = varEnd;
6518     if ((LoopSize & 0xFFFF0000) != 0)
6519       VReg1 = MRI.createVirtualRegister(TRC);
6520     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6521                    .addImm(LoopSize & 0xFFFF));
6522
6523     if ((LoopSize & 0xFFFF0000) != 0)
6524       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6525                      .addReg(VReg1)
6526                      .addImm(LoopSize >> 16));
6527   } else {
6528     MachineConstantPool *ConstantPool = MF->getConstantPool();
6529     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6530     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6531
6532     // MachineConstantPool wants an explicit alignment.
6533     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6534     if (Align == 0)
6535       Align = getDataLayout()->getTypeAllocSize(C->getType());
6536     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6537
6538     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6539                    .addReg(varEnd, RegState::Define)
6540                    .addConstantPoolIndex(Idx)
6541                    .addImm(0));
6542   }
6543   BB->addSuccessor(loopMBB);
6544
6545   // Generate the loop body:
6546   //   varPhi = PHI(varLoop, varEnd)
6547   //   srcPhi = PHI(srcLoop, src)
6548   //   destPhi = PHI(destLoop, dst)
6549   MachineBasicBlock *entryBB = BB;
6550   BB = loopMBB;
6551   unsigned varLoop = MRI.createVirtualRegister(TRC);
6552   unsigned varPhi = MRI.createVirtualRegister(TRC);
6553   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6554   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6555   unsigned destLoop = MRI.createVirtualRegister(TRC);
6556   unsigned destPhi = MRI.createVirtualRegister(TRC);
6557
6558   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6559     .addReg(varLoop).addMBB(loopMBB)
6560     .addReg(varEnd).addMBB(entryBB);
6561   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6562     .addReg(srcLoop).addMBB(loopMBB)
6563     .addReg(src).addMBB(entryBB);
6564   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6565     .addReg(destLoop).addMBB(loopMBB)
6566     .addReg(dest).addMBB(entryBB);
6567
6568   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6569   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6570   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6571   if (UnitSize >= 8) {
6572     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6573       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6574
6575     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6576       .addReg(destPhi).addImm(0).addReg(scratch));
6577   } else if (isThumb2) {
6578     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6579       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6580
6581     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6582       .addReg(scratch).addReg(destPhi)
6583       .addImm(UnitSize));
6584   } else {
6585     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6586       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6587       .addImm(UnitSize));
6588
6589     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6590       .addReg(scratch).addReg(destPhi)
6591       .addReg(0).addImm(UnitSize));
6592   }
6593
6594   // Decrement loop variable by UnitSize.
6595   MachineInstrBuilder MIB = BuildMI(BB, dl,
6596     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6597   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6598   MIB->getOperand(5).setReg(ARM::CPSR);
6599   MIB->getOperand(5).setIsDef(true);
6600
6601   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6602     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6603
6604   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6605   BB->addSuccessor(loopMBB);
6606   BB->addSuccessor(exitMBB);
6607
6608   // Add epilogue to handle BytesLeft.
6609   BB = exitMBB;
6610   MachineInstr *StartOfExit = exitMBB->begin();
6611   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6612   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6613
6614   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6615   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6616   unsigned srcIn = srcLoop;
6617   unsigned destIn = destLoop;
6618   for (unsigned i = 0; i < BytesLeft; i++) {
6619     unsigned scratch = MRI.createVirtualRegister(TRC);
6620     unsigned srcOut = MRI.createVirtualRegister(TRC);
6621     unsigned destOut = MRI.createVirtualRegister(TRC);
6622     if (isThumb2) {
6623       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6624         TII->get(ldrOpc),scratch)
6625         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6626
6627       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6628         .addReg(scratch).addReg(destIn)
6629         .addImm(1));
6630     } else {
6631       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6632         TII->get(ldrOpc),scratch)
6633         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6634
6635       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6636         .addReg(scratch).addReg(destIn)
6637         .addReg(0).addImm(1));
6638     }
6639     srcIn = srcOut;
6640     destIn = destOut;
6641   }
6642
6643   MI->eraseFromParent();   // The instruction is gone now.
6644   return BB;
6645 }
6646
6647 MachineBasicBlock *
6648 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6649                                                MachineBasicBlock *BB) const {
6650   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6651   DebugLoc dl = MI->getDebugLoc();
6652   bool isThumb2 = Subtarget->isThumb2();
6653   switch (MI->getOpcode()) {
6654   default: {
6655     MI->dump();
6656     llvm_unreachable("Unexpected instr type to insert");
6657   }
6658   // The Thumb2 pre-indexed stores have the same MI operands, they just
6659   // define them differently in the .td files from the isel patterns, so
6660   // they need pseudos.
6661   case ARM::t2STR_preidx:
6662     MI->setDesc(TII->get(ARM::t2STR_PRE));
6663     return BB;
6664   case ARM::t2STRB_preidx:
6665     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6666     return BB;
6667   case ARM::t2STRH_preidx:
6668     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6669     return BB;
6670
6671   case ARM::STRi_preidx:
6672   case ARM::STRBi_preidx: {
6673     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6674       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6675     // Decode the offset.
6676     unsigned Offset = MI->getOperand(4).getImm();
6677     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6678     Offset = ARM_AM::getAM2Offset(Offset);
6679     if (isSub)
6680       Offset = -Offset;
6681
6682     MachineMemOperand *MMO = *MI->memoperands_begin();
6683     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6684       .addOperand(MI->getOperand(0))  // Rn_wb
6685       .addOperand(MI->getOperand(1))  // Rt
6686       .addOperand(MI->getOperand(2))  // Rn
6687       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6688       .addOperand(MI->getOperand(5))  // pred
6689       .addOperand(MI->getOperand(6))
6690       .addMemOperand(MMO);
6691     MI->eraseFromParent();
6692     return BB;
6693   }
6694   case ARM::STRr_preidx:
6695   case ARM::STRBr_preidx:
6696   case ARM::STRH_preidx: {
6697     unsigned NewOpc;
6698     switch (MI->getOpcode()) {
6699     default: llvm_unreachable("unexpected opcode!");
6700     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6701     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6702     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6703     }
6704     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6705     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6706       MIB.addOperand(MI->getOperand(i));
6707     MI->eraseFromParent();
6708     return BB;
6709   }
6710   case ARM::ATOMIC_LOAD_ADD_I8:
6711      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6712   case ARM::ATOMIC_LOAD_ADD_I16:
6713      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6714   case ARM::ATOMIC_LOAD_ADD_I32:
6715      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6716
6717   case ARM::ATOMIC_LOAD_AND_I8:
6718      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6719   case ARM::ATOMIC_LOAD_AND_I16:
6720      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6721   case ARM::ATOMIC_LOAD_AND_I32:
6722      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6723
6724   case ARM::ATOMIC_LOAD_OR_I8:
6725      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6726   case ARM::ATOMIC_LOAD_OR_I16:
6727      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6728   case ARM::ATOMIC_LOAD_OR_I32:
6729      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6730
6731   case ARM::ATOMIC_LOAD_XOR_I8:
6732      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6733   case ARM::ATOMIC_LOAD_XOR_I16:
6734      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6735   case ARM::ATOMIC_LOAD_XOR_I32:
6736      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6737
6738   case ARM::ATOMIC_LOAD_NAND_I8:
6739      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6740   case ARM::ATOMIC_LOAD_NAND_I16:
6741      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6742   case ARM::ATOMIC_LOAD_NAND_I32:
6743      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6744
6745   case ARM::ATOMIC_LOAD_SUB_I8:
6746      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6747   case ARM::ATOMIC_LOAD_SUB_I16:
6748      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6749   case ARM::ATOMIC_LOAD_SUB_I32:
6750      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6751
6752   case ARM::ATOMIC_LOAD_MIN_I8:
6753      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6754   case ARM::ATOMIC_LOAD_MIN_I16:
6755      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6756   case ARM::ATOMIC_LOAD_MIN_I32:
6757      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6758
6759   case ARM::ATOMIC_LOAD_MAX_I8:
6760      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6761   case ARM::ATOMIC_LOAD_MAX_I16:
6762      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6763   case ARM::ATOMIC_LOAD_MAX_I32:
6764      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6765
6766   case ARM::ATOMIC_LOAD_UMIN_I8:
6767      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6768   case ARM::ATOMIC_LOAD_UMIN_I16:
6769      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6770   case ARM::ATOMIC_LOAD_UMIN_I32:
6771      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6772
6773   case ARM::ATOMIC_LOAD_UMAX_I8:
6774      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6775   case ARM::ATOMIC_LOAD_UMAX_I16:
6776      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6777   case ARM::ATOMIC_LOAD_UMAX_I32:
6778      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6779
6780   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6781   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6782   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6783
6784   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6785   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6786   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6787
6788
6789   case ARM::ATOMADD6432:
6790     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6791                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6792                               /*NeedsCarry*/ true);
6793   case ARM::ATOMSUB6432:
6794     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6795                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6796                               /*NeedsCarry*/ true);
6797   case ARM::ATOMOR6432:
6798     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6799                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6800   case ARM::ATOMXOR6432:
6801     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6802                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6803   case ARM::ATOMAND6432:
6804     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6805                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6806   case ARM::ATOMSWAP6432:
6807     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6808   case ARM::ATOMCMPXCHG6432:
6809     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6810                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6811                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6812
6813   case ARM::tMOVCCr_pseudo: {
6814     // To "insert" a SELECT_CC instruction, we actually have to insert the
6815     // diamond control-flow pattern.  The incoming instruction knows the
6816     // destination vreg to set, the condition code register to branch on, the
6817     // true/false values to select between, and a branch opcode to use.
6818     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6819     MachineFunction::iterator It = BB;
6820     ++It;
6821
6822     //  thisMBB:
6823     //  ...
6824     //   TrueVal = ...
6825     //   cmpTY ccX, r1, r2
6826     //   bCC copy1MBB
6827     //   fallthrough --> copy0MBB
6828     MachineBasicBlock *thisMBB  = BB;
6829     MachineFunction *F = BB->getParent();
6830     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6831     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6832     F->insert(It, copy0MBB);
6833     F->insert(It, sinkMBB);
6834
6835     // Transfer the remainder of BB and its successor edges to sinkMBB.
6836     sinkMBB->splice(sinkMBB->begin(), BB,
6837                     llvm::next(MachineBasicBlock::iterator(MI)),
6838                     BB->end());
6839     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6840
6841     BB->addSuccessor(copy0MBB);
6842     BB->addSuccessor(sinkMBB);
6843
6844     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6845       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6846
6847     //  copy0MBB:
6848     //   %FalseValue = ...
6849     //   # fallthrough to sinkMBB
6850     BB = copy0MBB;
6851
6852     // Update machine-CFG edges
6853     BB->addSuccessor(sinkMBB);
6854
6855     //  sinkMBB:
6856     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6857     //  ...
6858     BB = sinkMBB;
6859     BuildMI(*BB, BB->begin(), dl,
6860             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6861       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6862       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6863
6864     MI->eraseFromParent();   // The pseudo instruction is gone now.
6865     return BB;
6866   }
6867
6868   case ARM::BCCi64:
6869   case ARM::BCCZi64: {
6870     // If there is an unconditional branch to the other successor, remove it.
6871     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6872
6873     // Compare both parts that make up the double comparison separately for
6874     // equality.
6875     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6876
6877     unsigned LHS1 = MI->getOperand(1).getReg();
6878     unsigned LHS2 = MI->getOperand(2).getReg();
6879     if (RHSisZero) {
6880       AddDefaultPred(BuildMI(BB, dl,
6881                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6882                      .addReg(LHS1).addImm(0));
6883       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6884         .addReg(LHS2).addImm(0)
6885         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6886     } else {
6887       unsigned RHS1 = MI->getOperand(3).getReg();
6888       unsigned RHS2 = MI->getOperand(4).getReg();
6889       AddDefaultPred(BuildMI(BB, dl,
6890                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6891                      .addReg(LHS1).addReg(RHS1));
6892       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6893         .addReg(LHS2).addReg(RHS2)
6894         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6895     }
6896
6897     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6898     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6899     if (MI->getOperand(0).getImm() == ARMCC::NE)
6900       std::swap(destMBB, exitMBB);
6901
6902     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6903       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6904     if (isThumb2)
6905       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6906     else
6907       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6908
6909     MI->eraseFromParent();   // The pseudo instruction is gone now.
6910     return BB;
6911   }
6912
6913   case ARM::Int_eh_sjlj_setjmp:
6914   case ARM::Int_eh_sjlj_setjmp_nofp:
6915   case ARM::tInt_eh_sjlj_setjmp:
6916   case ARM::t2Int_eh_sjlj_setjmp:
6917   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6918     EmitSjLjDispatchBlock(MI, BB);
6919     return BB;
6920
6921   case ARM::ABS:
6922   case ARM::t2ABS: {
6923     // To insert an ABS instruction, we have to insert the
6924     // diamond control-flow pattern.  The incoming instruction knows the
6925     // source vreg to test against 0, the destination vreg to set,
6926     // the condition code register to branch on, the
6927     // true/false values to select between, and a branch opcode to use.
6928     // It transforms
6929     //     V1 = ABS V0
6930     // into
6931     //     V2 = MOVS V0
6932     //     BCC                      (branch to SinkBB if V0 >= 0)
6933     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6934     //     SinkBB: V1 = PHI(V2, V3)
6935     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6936     MachineFunction::iterator BBI = BB;
6937     ++BBI;
6938     MachineFunction *Fn = BB->getParent();
6939     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6940     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6941     Fn->insert(BBI, RSBBB);
6942     Fn->insert(BBI, SinkBB);
6943
6944     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6945     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6946     bool isThumb2 = Subtarget->isThumb2();
6947     MachineRegisterInfo &MRI = Fn->getRegInfo();
6948     // In Thumb mode S must not be specified if source register is the SP or
6949     // PC and if destination register is the SP, so restrict register class
6950     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6951       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6952       (const TargetRegisterClass*)&ARM::GPRRegClass);
6953
6954     // Transfer the remainder of BB and its successor edges to sinkMBB.
6955     SinkBB->splice(SinkBB->begin(), BB,
6956       llvm::next(MachineBasicBlock::iterator(MI)),
6957       BB->end());
6958     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6959
6960     BB->addSuccessor(RSBBB);
6961     BB->addSuccessor(SinkBB);
6962
6963     // fall through to SinkMBB
6964     RSBBB->addSuccessor(SinkBB);
6965
6966     // insert a cmp at the end of BB
6967     AddDefaultPred(BuildMI(BB, dl,
6968                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6969                    .addReg(ABSSrcReg).addImm(0));
6970
6971     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6972     BuildMI(BB, dl,
6973       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6974       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6975
6976     // insert rsbri in RSBBB
6977     // Note: BCC and rsbri will be converted into predicated rsbmi
6978     // by if-conversion pass
6979     BuildMI(*RSBBB, RSBBB->begin(), dl,
6980       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6981       .addReg(ABSSrcReg, RegState::Kill)
6982       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6983
6984     // insert PHI in SinkBB,
6985     // reuse ABSDstReg to not change uses of ABS instruction
6986     BuildMI(*SinkBB, SinkBB->begin(), dl,
6987       TII->get(ARM::PHI), ABSDstReg)
6988       .addReg(NewRsbDstReg).addMBB(RSBBB)
6989       .addReg(ABSSrcReg).addMBB(BB);
6990
6991     // remove ABS instruction
6992     MI->eraseFromParent();
6993
6994     // return last added BB
6995     return SinkBB;
6996   }
6997   case ARM::COPY_STRUCT_BYVAL_I32:
6998     ++NumLoopByVals;
6999     return EmitStructByval(MI, BB);
7000   }
7001 }
7002
7003 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7004                                                       SDNode *Node) const {
7005   if (!MI->hasPostISelHook()) {
7006     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7007            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7008     return;
7009   }
7010
7011   const MCInstrDesc *MCID = &MI->getDesc();
7012   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7013   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7014   // operand is still set to noreg. If needed, set the optional operand's
7015   // register to CPSR, and remove the redundant implicit def.
7016   //
7017   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7018
7019   // Rename pseudo opcodes.
7020   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7021   if (NewOpc) {
7022     const ARMBaseInstrInfo *TII =
7023       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7024     MCID = &TII->get(NewOpc);
7025
7026     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7027            "converted opcode should be the same except for cc_out");
7028
7029     MI->setDesc(*MCID);
7030
7031     // Add the optional cc_out operand
7032     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7033   }
7034   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7035
7036   // Any ARM instruction that sets the 's' bit should specify an optional
7037   // "cc_out" operand in the last operand position.
7038   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7039     assert(!NewOpc && "Optional cc_out operand required");
7040     return;
7041   }
7042   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7043   // since we already have an optional CPSR def.
7044   bool definesCPSR = false;
7045   bool deadCPSR = false;
7046   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7047        i != e; ++i) {
7048     const MachineOperand &MO = MI->getOperand(i);
7049     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7050       definesCPSR = true;
7051       if (MO.isDead())
7052         deadCPSR = true;
7053       MI->RemoveOperand(i);
7054       break;
7055     }
7056   }
7057   if (!definesCPSR) {
7058     assert(!NewOpc && "Optional cc_out operand required");
7059     return;
7060   }
7061   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7062   if (deadCPSR) {
7063     assert(!MI->getOperand(ccOutIdx).getReg() &&
7064            "expect uninitialized optional cc_out operand");
7065     return;
7066   }
7067
7068   // If this instruction was defined with an optional CPSR def and its dag node
7069   // had a live implicit CPSR def, then activate the optional CPSR def.
7070   MachineOperand &MO = MI->getOperand(ccOutIdx);
7071   MO.setReg(ARM::CPSR);
7072   MO.setIsDef(true);
7073 }
7074
7075 //===----------------------------------------------------------------------===//
7076 //                           ARM Optimization Hooks
7077 //===----------------------------------------------------------------------===//
7078
7079 // Helper function that checks if N is a null or all ones constant.
7080 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7081   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7082   if (!C)
7083     return false;
7084   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7085 }
7086
7087 // Return true if N is conditionally 0 or all ones.
7088 // Detects these expressions where cc is an i1 value:
7089 //
7090 //   (select cc 0, y)   [AllOnes=0]
7091 //   (select cc y, 0)   [AllOnes=0]
7092 //   (zext cc)          [AllOnes=0]
7093 //   (sext cc)          [AllOnes=0/1]
7094 //   (select cc -1, y)  [AllOnes=1]
7095 //   (select cc y, -1)  [AllOnes=1]
7096 //
7097 // Invert is set when N is the null/all ones constant when CC is false.
7098 // OtherOp is set to the alternative value of N.
7099 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7100                                        SDValue &CC, bool &Invert,
7101                                        SDValue &OtherOp,
7102                                        SelectionDAG &DAG) {
7103   switch (N->getOpcode()) {
7104   default: return false;
7105   case ISD::SELECT: {
7106     CC = N->getOperand(0);
7107     SDValue N1 = N->getOperand(1);
7108     SDValue N2 = N->getOperand(2);
7109     if (isZeroOrAllOnes(N1, AllOnes)) {
7110       Invert = false;
7111       OtherOp = N2;
7112       return true;
7113     }
7114     if (isZeroOrAllOnes(N2, AllOnes)) {
7115       Invert = true;
7116       OtherOp = N1;
7117       return true;
7118     }
7119     return false;
7120   }
7121   case ISD::ZERO_EXTEND:
7122     // (zext cc) can never be the all ones value.
7123     if (AllOnes)
7124       return false;
7125     // Fall through.
7126   case ISD::SIGN_EXTEND: {
7127     EVT VT = N->getValueType(0);
7128     CC = N->getOperand(0);
7129     if (CC.getValueType() != MVT::i1)
7130       return false;
7131     Invert = !AllOnes;
7132     if (AllOnes)
7133       // When looking for an AllOnes constant, N is an sext, and the 'other'
7134       // value is 0.
7135       OtherOp = DAG.getConstant(0, VT);
7136     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7137       // When looking for a 0 constant, N can be zext or sext.
7138       OtherOp = DAG.getConstant(1, VT);
7139     else
7140       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7141     return true;
7142   }
7143   }
7144 }
7145
7146 // Combine a constant select operand into its use:
7147 //
7148 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7149 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7150 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7151 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7152 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7153 //
7154 // The transform is rejected if the select doesn't have a constant operand that
7155 // is null, or all ones when AllOnes is set.
7156 //
7157 // Also recognize sext/zext from i1:
7158 //
7159 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7160 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7161 //
7162 // These transformations eventually create predicated instructions.
7163 //
7164 // @param N       The node to transform.
7165 // @param Slct    The N operand that is a select.
7166 // @param OtherOp The other N operand (x above).
7167 // @param DCI     Context.
7168 // @param AllOnes Require the select constant to be all ones instead of null.
7169 // @returns The new node, or SDValue() on failure.
7170 static
7171 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7172                             TargetLowering::DAGCombinerInfo &DCI,
7173                             bool AllOnes = false) {
7174   SelectionDAG &DAG = DCI.DAG;
7175   EVT VT = N->getValueType(0);
7176   SDValue NonConstantVal;
7177   SDValue CCOp;
7178   bool SwapSelectOps;
7179   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7180                                   NonConstantVal, DAG))
7181     return SDValue();
7182
7183   // Slct is now know to be the desired identity constant when CC is true.
7184   SDValue TrueVal = OtherOp;
7185   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7186                                  OtherOp, NonConstantVal);
7187   // Unless SwapSelectOps says CC should be false.
7188   if (SwapSelectOps)
7189     std::swap(TrueVal, FalseVal);
7190
7191   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7192                      CCOp, TrueVal, FalseVal);
7193 }
7194
7195 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7196 static
7197 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7198                                        TargetLowering::DAGCombinerInfo &DCI) {
7199   SDValue N0 = N->getOperand(0);
7200   SDValue N1 = N->getOperand(1);
7201   if (N0.getNode()->hasOneUse()) {
7202     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7203     if (Result.getNode())
7204       return Result;
7205   }
7206   if (N1.getNode()->hasOneUse()) {
7207     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7208     if (Result.getNode())
7209       return Result;
7210   }
7211   return SDValue();
7212 }
7213
7214 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7215 // (only after legalization).
7216 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7217                                  TargetLowering::DAGCombinerInfo &DCI,
7218                                  const ARMSubtarget *Subtarget) {
7219
7220   // Only perform optimization if after legalize, and if NEON is available. We
7221   // also expected both operands to be BUILD_VECTORs.
7222   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7223       || N0.getOpcode() != ISD::BUILD_VECTOR
7224       || N1.getOpcode() != ISD::BUILD_VECTOR)
7225     return SDValue();
7226
7227   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7228   EVT VT = N->getValueType(0);
7229   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7230     return SDValue();
7231
7232   // Check that the vector operands are of the right form.
7233   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7234   // operands, where N is the size of the formed vector.
7235   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7236   // index such that we have a pair wise add pattern.
7237
7238   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7239   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7240     return SDValue();
7241   SDValue Vec = N0->getOperand(0)->getOperand(0);
7242   SDNode *V = Vec.getNode();
7243   unsigned nextIndex = 0;
7244
7245   // For each operands to the ADD which are BUILD_VECTORs,
7246   // check to see if each of their operands are an EXTRACT_VECTOR with
7247   // the same vector and appropriate index.
7248   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7249     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7250         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7251
7252       SDValue ExtVec0 = N0->getOperand(i);
7253       SDValue ExtVec1 = N1->getOperand(i);
7254
7255       // First operand is the vector, verify its the same.
7256       if (V != ExtVec0->getOperand(0).getNode() ||
7257           V != ExtVec1->getOperand(0).getNode())
7258         return SDValue();
7259
7260       // Second is the constant, verify its correct.
7261       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7262       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7263
7264       // For the constant, we want to see all the even or all the odd.
7265       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7266           || C1->getZExtValue() != nextIndex+1)
7267         return SDValue();
7268
7269       // Increment index.
7270       nextIndex+=2;
7271     } else
7272       return SDValue();
7273   }
7274
7275   // Create VPADDL node.
7276   SelectionDAG &DAG = DCI.DAG;
7277   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7278
7279   // Build operand list.
7280   SmallVector<SDValue, 8> Ops;
7281   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7282                                 TLI.getPointerTy()));
7283
7284   // Input is the vector.
7285   Ops.push_back(Vec);
7286
7287   // Get widened type and narrowed type.
7288   MVT widenType;
7289   unsigned numElem = VT.getVectorNumElements();
7290   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7291     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7292     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7293     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7294     default:
7295       llvm_unreachable("Invalid vector element type for padd optimization.");
7296   }
7297
7298   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7299                             widenType, &Ops[0], Ops.size());
7300   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7301 }
7302
7303 static SDValue findMUL_LOHI(SDValue V) {
7304   if (V->getOpcode() == ISD::UMUL_LOHI ||
7305       V->getOpcode() == ISD::SMUL_LOHI)
7306     return V;
7307   return SDValue();
7308 }
7309
7310 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7311                                      TargetLowering::DAGCombinerInfo &DCI,
7312                                      const ARMSubtarget *Subtarget) {
7313
7314   if (Subtarget->isThumb1Only()) return SDValue();
7315
7316   // Only perform the checks after legalize when the pattern is available.
7317   if (DCI.isBeforeLegalize()) return SDValue();
7318
7319   // Look for multiply add opportunities.
7320   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7321   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7322   // a glue link from the first add to the second add.
7323   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7324   // a S/UMLAL instruction.
7325   //          loAdd   UMUL_LOHI
7326   //            \    / :lo    \ :hi
7327   //             \  /          \          [no multiline comment]
7328   //              ADDC         |  hiAdd
7329   //                 \ :glue  /  /
7330   //                  \      /  /
7331   //                    ADDE
7332   //
7333   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7334   SDValue AddcOp0 = AddcNode->getOperand(0);
7335   SDValue AddcOp1 = AddcNode->getOperand(1);
7336
7337   // Check if the two operands are from the same mul_lohi node.
7338   if (AddcOp0.getNode() == AddcOp1.getNode())
7339     return SDValue();
7340
7341   assert(AddcNode->getNumValues() == 2 &&
7342          AddcNode->getValueType(0) == MVT::i32 &&
7343          AddcNode->getValueType(1) == MVT::Glue &&
7344          "Expect ADDC with two result values: i32, glue");
7345
7346   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7347   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7348       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7349       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7350       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7351     return SDValue();
7352
7353   // Look for the glued ADDE.
7354   SDNode* AddeNode = AddcNode->getGluedUser();
7355   if (AddeNode == NULL)
7356     return SDValue();
7357
7358   // Make sure it is really an ADDE.
7359   if (AddeNode->getOpcode() != ISD::ADDE)
7360     return SDValue();
7361
7362   assert(AddeNode->getNumOperands() == 3 &&
7363          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7364          "ADDE node has the wrong inputs");
7365
7366   // Check for the triangle shape.
7367   SDValue AddeOp0 = AddeNode->getOperand(0);
7368   SDValue AddeOp1 = AddeNode->getOperand(1);
7369
7370   // Make sure that the ADDE operands are not coming from the same node.
7371   if (AddeOp0.getNode() == AddeOp1.getNode())
7372     return SDValue();
7373
7374   // Find the MUL_LOHI node walking up ADDE's operands.
7375   bool IsLeftOperandMUL = false;
7376   SDValue MULOp = findMUL_LOHI(AddeOp0);
7377   if (MULOp == SDValue())
7378    MULOp = findMUL_LOHI(AddeOp1);
7379   else
7380     IsLeftOperandMUL = true;
7381   if (MULOp == SDValue())
7382      return SDValue();
7383
7384   // Figure out the right opcode.
7385   unsigned Opc = MULOp->getOpcode();
7386   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7387
7388   // Figure out the high and low input values to the MLAL node.
7389   SDValue* HiMul = &MULOp;
7390   SDValue* HiAdd = NULL;
7391   SDValue* LoMul = NULL;
7392   SDValue* LowAdd = NULL;
7393
7394   if (IsLeftOperandMUL)
7395     HiAdd = &AddeOp1;
7396   else
7397     HiAdd = &AddeOp0;
7398
7399
7400   if (AddcOp0->getOpcode() == Opc) {
7401     LoMul = &AddcOp0;
7402     LowAdd = &AddcOp1;
7403   }
7404   if (AddcOp1->getOpcode() == Opc) {
7405     LoMul = &AddcOp1;
7406     LowAdd = &AddcOp0;
7407   }
7408
7409   if (LoMul == NULL)
7410     return SDValue();
7411
7412   if (LoMul->getNode() != HiMul->getNode())
7413     return SDValue();
7414
7415   // Create the merged node.
7416   SelectionDAG &DAG = DCI.DAG;
7417
7418   // Build operand list.
7419   SmallVector<SDValue, 8> Ops;
7420   Ops.push_back(LoMul->getOperand(0));
7421   Ops.push_back(LoMul->getOperand(1));
7422   Ops.push_back(*LowAdd);
7423   Ops.push_back(*HiAdd);
7424
7425   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7426                                  DAG.getVTList(MVT::i32, MVT::i32),
7427                                  &Ops[0], Ops.size());
7428
7429   // Replace the ADDs' nodes uses by the MLA node's values.
7430   SDValue HiMLALResult(MLALNode.getNode(), 1);
7431   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7432
7433   SDValue LoMLALResult(MLALNode.getNode(), 0);
7434   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7435
7436   // Return original node to notify the driver to stop replacing.
7437   SDValue resNode(AddcNode, 0);
7438   return resNode;
7439 }
7440
7441 /// PerformADDCCombine - Target-specific dag combine transform from
7442 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7443 static SDValue PerformADDCCombine(SDNode *N,
7444                                  TargetLowering::DAGCombinerInfo &DCI,
7445                                  const ARMSubtarget *Subtarget) {
7446
7447   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7448
7449 }
7450
7451 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7452 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7453 /// called with the default operands, and if that fails, with commuted
7454 /// operands.
7455 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7456                                           TargetLowering::DAGCombinerInfo &DCI,
7457                                           const ARMSubtarget *Subtarget){
7458
7459   // Attempt to create vpaddl for this add.
7460   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7461   if (Result.getNode())
7462     return Result;
7463
7464   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7465   if (N0.getNode()->hasOneUse()) {
7466     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7467     if (Result.getNode()) return Result;
7468   }
7469   return SDValue();
7470 }
7471
7472 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7473 ///
7474 static SDValue PerformADDCombine(SDNode *N,
7475                                  TargetLowering::DAGCombinerInfo &DCI,
7476                                  const ARMSubtarget *Subtarget) {
7477   SDValue N0 = N->getOperand(0);
7478   SDValue N1 = N->getOperand(1);
7479
7480   // First try with the default operand order.
7481   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7482   if (Result.getNode())
7483     return Result;
7484
7485   // If that didn't work, try again with the operands commuted.
7486   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7487 }
7488
7489 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7490 ///
7491 static SDValue PerformSUBCombine(SDNode *N,
7492                                  TargetLowering::DAGCombinerInfo &DCI) {
7493   SDValue N0 = N->getOperand(0);
7494   SDValue N1 = N->getOperand(1);
7495
7496   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7497   if (N1.getNode()->hasOneUse()) {
7498     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7499     if (Result.getNode()) return Result;
7500   }
7501
7502   return SDValue();
7503 }
7504
7505 /// PerformVMULCombine
7506 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7507 /// special multiplier accumulator forwarding.
7508 ///   vmul d3, d0, d2
7509 ///   vmla d3, d1, d2
7510 /// is faster than
7511 ///   vadd d3, d0, d1
7512 ///   vmul d3, d3, d2
7513 static SDValue PerformVMULCombine(SDNode *N,
7514                                   TargetLowering::DAGCombinerInfo &DCI,
7515                                   const ARMSubtarget *Subtarget) {
7516   if (!Subtarget->hasVMLxForwarding())
7517     return SDValue();
7518
7519   SelectionDAG &DAG = DCI.DAG;
7520   SDValue N0 = N->getOperand(0);
7521   SDValue N1 = N->getOperand(1);
7522   unsigned Opcode = N0.getOpcode();
7523   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7524       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7525     Opcode = N1.getOpcode();
7526     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7527         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7528       return SDValue();
7529     std::swap(N0, N1);
7530   }
7531
7532   EVT VT = N->getValueType(0);
7533   DebugLoc DL = N->getDebugLoc();
7534   SDValue N00 = N0->getOperand(0);
7535   SDValue N01 = N0->getOperand(1);
7536   return DAG.getNode(Opcode, DL, VT,
7537                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7538                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7539 }
7540
7541 static SDValue PerformMULCombine(SDNode *N,
7542                                  TargetLowering::DAGCombinerInfo &DCI,
7543                                  const ARMSubtarget *Subtarget) {
7544   SelectionDAG &DAG = DCI.DAG;
7545
7546   if (Subtarget->isThumb1Only())
7547     return SDValue();
7548
7549   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7550     return SDValue();
7551
7552   EVT VT = N->getValueType(0);
7553   if (VT.is64BitVector() || VT.is128BitVector())
7554     return PerformVMULCombine(N, DCI, Subtarget);
7555   if (VT != MVT::i32)
7556     return SDValue();
7557
7558   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7559   if (!C)
7560     return SDValue();
7561
7562   int64_t MulAmt = C->getSExtValue();
7563   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7564
7565   ShiftAmt = ShiftAmt & (32 - 1);
7566   SDValue V = N->getOperand(0);
7567   DebugLoc DL = N->getDebugLoc();
7568
7569   SDValue Res;
7570   MulAmt >>= ShiftAmt;
7571
7572   if (MulAmt >= 0) {
7573     if (isPowerOf2_32(MulAmt - 1)) {
7574       // (mul x, 2^N + 1) => (add (shl x, N), x)
7575       Res = DAG.getNode(ISD::ADD, DL, VT,
7576                         V,
7577                         DAG.getNode(ISD::SHL, DL, VT,
7578                                     V,
7579                                     DAG.getConstant(Log2_32(MulAmt - 1),
7580                                                     MVT::i32)));
7581     } else if (isPowerOf2_32(MulAmt + 1)) {
7582       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7583       Res = DAG.getNode(ISD::SUB, DL, VT,
7584                         DAG.getNode(ISD::SHL, DL, VT,
7585                                     V,
7586                                     DAG.getConstant(Log2_32(MulAmt + 1),
7587                                                     MVT::i32)),
7588                         V);
7589     } else
7590       return SDValue();
7591   } else {
7592     uint64_t MulAmtAbs = -MulAmt;
7593     if (isPowerOf2_32(MulAmtAbs + 1)) {
7594       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7595       Res = DAG.getNode(ISD::SUB, DL, VT,
7596                         V,
7597                         DAG.getNode(ISD::SHL, DL, VT,
7598                                     V,
7599                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7600                                                     MVT::i32)));
7601     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7602       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7603       Res = DAG.getNode(ISD::ADD, DL, VT,
7604                         V,
7605                         DAG.getNode(ISD::SHL, DL, VT,
7606                                     V,
7607                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7608                                                     MVT::i32)));
7609       Res = DAG.getNode(ISD::SUB, DL, VT,
7610                         DAG.getConstant(0, MVT::i32),Res);
7611
7612     } else
7613       return SDValue();
7614   }
7615
7616   if (ShiftAmt != 0)
7617     Res = DAG.getNode(ISD::SHL, DL, VT,
7618                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7619
7620   // Do not add new nodes to DAG combiner worklist.
7621   DCI.CombineTo(N, Res, false);
7622   return SDValue();
7623 }
7624
7625 static SDValue PerformANDCombine(SDNode *N,
7626                                  TargetLowering::DAGCombinerInfo &DCI,
7627                                  const ARMSubtarget *Subtarget) {
7628
7629   // Attempt to use immediate-form VBIC
7630   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7631   DebugLoc dl = N->getDebugLoc();
7632   EVT VT = N->getValueType(0);
7633   SelectionDAG &DAG = DCI.DAG;
7634
7635   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7636     return SDValue();
7637
7638   APInt SplatBits, SplatUndef;
7639   unsigned SplatBitSize;
7640   bool HasAnyUndefs;
7641   if (BVN &&
7642       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7643     if (SplatBitSize <= 64) {
7644       EVT VbicVT;
7645       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7646                                       SplatUndef.getZExtValue(), SplatBitSize,
7647                                       DAG, VbicVT, VT.is128BitVector(),
7648                                       OtherModImm);
7649       if (Val.getNode()) {
7650         SDValue Input =
7651           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7652         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7653         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7654       }
7655     }
7656   }
7657
7658   if (!Subtarget->isThumb1Only()) {
7659     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7660     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7661     if (Result.getNode())
7662       return Result;
7663   }
7664
7665   return SDValue();
7666 }
7667
7668 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7669 static SDValue PerformORCombine(SDNode *N,
7670                                 TargetLowering::DAGCombinerInfo &DCI,
7671                                 const ARMSubtarget *Subtarget) {
7672   // Attempt to use immediate-form VORR
7673   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7674   DebugLoc dl = N->getDebugLoc();
7675   EVT VT = N->getValueType(0);
7676   SelectionDAG &DAG = DCI.DAG;
7677
7678   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7679     return SDValue();
7680
7681   APInt SplatBits, SplatUndef;
7682   unsigned SplatBitSize;
7683   bool HasAnyUndefs;
7684   if (BVN && Subtarget->hasNEON() &&
7685       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7686     if (SplatBitSize <= 64) {
7687       EVT VorrVT;
7688       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7689                                       SplatUndef.getZExtValue(), SplatBitSize,
7690                                       DAG, VorrVT, VT.is128BitVector(),
7691                                       OtherModImm);
7692       if (Val.getNode()) {
7693         SDValue Input =
7694           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7695         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7696         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7697       }
7698     }
7699   }
7700
7701   if (!Subtarget->isThumb1Only()) {
7702     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7703     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7704     if (Result.getNode())
7705       return Result;
7706   }
7707
7708   // The code below optimizes (or (and X, Y), Z).
7709   // The AND operand needs to have a single user to make these optimizations
7710   // profitable.
7711   SDValue N0 = N->getOperand(0);
7712   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7713     return SDValue();
7714   SDValue N1 = N->getOperand(1);
7715
7716   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7717   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7718       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7719     APInt SplatUndef;
7720     unsigned SplatBitSize;
7721     bool HasAnyUndefs;
7722
7723     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7724     APInt SplatBits0;
7725     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7726                                   HasAnyUndefs) && !HasAnyUndefs) {
7727       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7728       APInt SplatBits1;
7729       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7730                                     HasAnyUndefs) && !HasAnyUndefs &&
7731           SplatBits0 == ~SplatBits1) {
7732         // Canonicalize the vector type to make instruction selection simpler.
7733         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7734         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7735                                      N0->getOperand(1), N0->getOperand(0),
7736                                      N1->getOperand(0));
7737         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7738       }
7739     }
7740   }
7741
7742   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7743   // reasonable.
7744
7745   // BFI is only available on V6T2+
7746   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7747     return SDValue();
7748
7749   DebugLoc DL = N->getDebugLoc();
7750   // 1) or (and A, mask), val => ARMbfi A, val, mask
7751   //      iff (val & mask) == val
7752   //
7753   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7754   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7755   //          && mask == ~mask2
7756   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7757   //          && ~mask == mask2
7758   //  (i.e., copy a bitfield value into another bitfield of the same width)
7759
7760   if (VT != MVT::i32)
7761     return SDValue();
7762
7763   SDValue N00 = N0.getOperand(0);
7764
7765   // The value and the mask need to be constants so we can verify this is
7766   // actually a bitfield set. If the mask is 0xffff, we can do better
7767   // via a movt instruction, so don't use BFI in that case.
7768   SDValue MaskOp = N0.getOperand(1);
7769   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7770   if (!MaskC)
7771     return SDValue();
7772   unsigned Mask = MaskC->getZExtValue();
7773   if (Mask == 0xffff)
7774     return SDValue();
7775   SDValue Res;
7776   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7777   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7778   if (N1C) {
7779     unsigned Val = N1C->getZExtValue();
7780     if ((Val & ~Mask) != Val)
7781       return SDValue();
7782
7783     if (ARM::isBitFieldInvertedMask(Mask)) {
7784       Val >>= CountTrailingZeros_32(~Mask);
7785
7786       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7787                         DAG.getConstant(Val, MVT::i32),
7788                         DAG.getConstant(Mask, MVT::i32));
7789
7790       // Do not add new nodes to DAG combiner worklist.
7791       DCI.CombineTo(N, Res, false);
7792       return SDValue();
7793     }
7794   } else if (N1.getOpcode() == ISD::AND) {
7795     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7796     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7797     if (!N11C)
7798       return SDValue();
7799     unsigned Mask2 = N11C->getZExtValue();
7800
7801     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7802     // as is to match.
7803     if (ARM::isBitFieldInvertedMask(Mask) &&
7804         (Mask == ~Mask2)) {
7805       // The pack halfword instruction works better for masks that fit it,
7806       // so use that when it's available.
7807       if (Subtarget->hasT2ExtractPack() &&
7808           (Mask == 0xffff || Mask == 0xffff0000))
7809         return SDValue();
7810       // 2a
7811       unsigned amt = CountTrailingZeros_32(Mask2);
7812       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7813                         DAG.getConstant(amt, MVT::i32));
7814       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7815                         DAG.getConstant(Mask, MVT::i32));
7816       // Do not add new nodes to DAG combiner worklist.
7817       DCI.CombineTo(N, Res, false);
7818       return SDValue();
7819     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7820                (~Mask == Mask2)) {
7821       // The pack halfword instruction works better for masks that fit it,
7822       // so use that when it's available.
7823       if (Subtarget->hasT2ExtractPack() &&
7824           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7825         return SDValue();
7826       // 2b
7827       unsigned lsb = CountTrailingZeros_32(Mask);
7828       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7829                         DAG.getConstant(lsb, MVT::i32));
7830       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7831                         DAG.getConstant(Mask2, MVT::i32));
7832       // Do not add new nodes to DAG combiner worklist.
7833       DCI.CombineTo(N, Res, false);
7834       return SDValue();
7835     }
7836   }
7837
7838   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7839       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7840       ARM::isBitFieldInvertedMask(~Mask)) {
7841     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7842     // where lsb(mask) == #shamt and masked bits of B are known zero.
7843     SDValue ShAmt = N00.getOperand(1);
7844     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7845     unsigned LSB = CountTrailingZeros_32(Mask);
7846     if (ShAmtC != LSB)
7847       return SDValue();
7848
7849     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7850                       DAG.getConstant(~Mask, MVT::i32));
7851
7852     // Do not add new nodes to DAG combiner worklist.
7853     DCI.CombineTo(N, Res, false);
7854   }
7855
7856   return SDValue();
7857 }
7858
7859 static SDValue PerformXORCombine(SDNode *N,
7860                                  TargetLowering::DAGCombinerInfo &DCI,
7861                                  const ARMSubtarget *Subtarget) {
7862   EVT VT = N->getValueType(0);
7863   SelectionDAG &DAG = DCI.DAG;
7864
7865   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7866     return SDValue();
7867
7868   if (!Subtarget->isThumb1Only()) {
7869     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7870     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7871     if (Result.getNode())
7872       return Result;
7873   }
7874
7875   return SDValue();
7876 }
7877
7878 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7879 /// the bits being cleared by the AND are not demanded by the BFI.
7880 static SDValue PerformBFICombine(SDNode *N,
7881                                  TargetLowering::DAGCombinerInfo &DCI) {
7882   SDValue N1 = N->getOperand(1);
7883   if (N1.getOpcode() == ISD::AND) {
7884     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7885     if (!N11C)
7886       return SDValue();
7887     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7888     unsigned LSB = CountTrailingZeros_32(~InvMask);
7889     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7890     unsigned Mask = (1 << Width)-1;
7891     unsigned Mask2 = N11C->getZExtValue();
7892     if ((Mask & (~Mask2)) == 0)
7893       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7894                              N->getOperand(0), N1.getOperand(0),
7895                              N->getOperand(2));
7896   }
7897   return SDValue();
7898 }
7899
7900 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7901 /// ARMISD::VMOVRRD.
7902 static SDValue PerformVMOVRRDCombine(SDNode *N,
7903                                      TargetLowering::DAGCombinerInfo &DCI) {
7904   // vmovrrd(vmovdrr x, y) -> x,y
7905   SDValue InDouble = N->getOperand(0);
7906   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7907     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7908
7909   // vmovrrd(load f64) -> (load i32), (load i32)
7910   SDNode *InNode = InDouble.getNode();
7911   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7912       InNode->getValueType(0) == MVT::f64 &&
7913       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7914       !cast<LoadSDNode>(InNode)->isVolatile()) {
7915     // TODO: Should this be done for non-FrameIndex operands?
7916     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7917
7918     SelectionDAG &DAG = DCI.DAG;
7919     DebugLoc DL = LD->getDebugLoc();
7920     SDValue BasePtr = LD->getBasePtr();
7921     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7922                                  LD->getPointerInfo(), LD->isVolatile(),
7923                                  LD->isNonTemporal(), LD->isInvariant(),
7924                                  LD->getAlignment());
7925
7926     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7927                                     DAG.getConstant(4, MVT::i32));
7928     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7929                                  LD->getPointerInfo(), LD->isVolatile(),
7930                                  LD->isNonTemporal(), LD->isInvariant(),
7931                                  std::min(4U, LD->getAlignment() / 2));
7932
7933     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7934     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7935     DCI.RemoveFromWorklist(LD);
7936     DAG.DeleteNode(LD);
7937     return Result;
7938   }
7939
7940   return SDValue();
7941 }
7942
7943 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7944 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7945 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7946   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7947   SDValue Op0 = N->getOperand(0);
7948   SDValue Op1 = N->getOperand(1);
7949   if (Op0.getOpcode() == ISD::BITCAST)
7950     Op0 = Op0.getOperand(0);
7951   if (Op1.getOpcode() == ISD::BITCAST)
7952     Op1 = Op1.getOperand(0);
7953   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7954       Op0.getNode() == Op1.getNode() &&
7955       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7956     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7957                        N->getValueType(0), Op0.getOperand(0));
7958   return SDValue();
7959 }
7960
7961 /// PerformSTORECombine - Target-specific dag combine xforms for
7962 /// ISD::STORE.
7963 static SDValue PerformSTORECombine(SDNode *N,
7964                                    TargetLowering::DAGCombinerInfo &DCI) {
7965   StoreSDNode *St = cast<StoreSDNode>(N);
7966   if (St->isVolatile())
7967     return SDValue();
7968
7969   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
7970   // pack all of the elements in one place.  Next, store to memory in fewer
7971   // chunks.
7972   SDValue StVal = St->getValue();
7973   EVT VT = StVal.getValueType();
7974   if (St->isTruncatingStore() && VT.isVector()) {
7975     SelectionDAG &DAG = DCI.DAG;
7976     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7977     EVT StVT = St->getMemoryVT();
7978     unsigned NumElems = VT.getVectorNumElements();
7979     assert(StVT != VT && "Cannot truncate to the same type");
7980     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7981     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7982
7983     // From, To sizes and ElemCount must be pow of two
7984     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7985
7986     // We are going to use the original vector elt for storing.
7987     // Accumulated smaller vector elements must be a multiple of the store size.
7988     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7989
7990     unsigned SizeRatio  = FromEltSz / ToEltSz;
7991     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7992
7993     // Create a type on which we perform the shuffle.
7994     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7995                                      NumElems*SizeRatio);
7996     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7997
7998     DebugLoc DL = St->getDebugLoc();
7999     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8000     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8001     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8002
8003     // Can't shuffle using an illegal type.
8004     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8005
8006     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8007                                 DAG.getUNDEF(WideVec.getValueType()),
8008                                 ShuffleVec.data());
8009     // At this point all of the data is stored at the bottom of the
8010     // register. We now need to save it to mem.
8011
8012     // Find the largest store unit
8013     MVT StoreType = MVT::i8;
8014     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8015          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8016       MVT Tp = (MVT::SimpleValueType)tp;
8017       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8018         StoreType = Tp;
8019     }
8020     // Didn't find a legal store type.
8021     if (!TLI.isTypeLegal(StoreType))
8022       return SDValue();
8023
8024     // Bitcast the original vector into a vector of store-size units
8025     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8026             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8027     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8028     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8029     SmallVector<SDValue, 8> Chains;
8030     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8031                                         TLI.getPointerTy());
8032     SDValue BasePtr = St->getBasePtr();
8033
8034     // Perform one or more big stores into memory.
8035     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8036     for (unsigned I = 0; I < E; I++) {
8037       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8038                                    StoreType, ShuffWide,
8039                                    DAG.getIntPtrConstant(I));
8040       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8041                                 St->getPointerInfo(), St->isVolatile(),
8042                                 St->isNonTemporal(), St->getAlignment());
8043       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8044                             Increment);
8045       Chains.push_back(Ch);
8046     }
8047     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8048                        Chains.size());
8049   }
8050
8051   if (!ISD::isNormalStore(St))
8052     return SDValue();
8053
8054   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8055   // ARM stores of arguments in the same cache line.
8056   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8057       StVal.getNode()->hasOneUse()) {
8058     SelectionDAG  &DAG = DCI.DAG;
8059     DebugLoc DL = St->getDebugLoc();
8060     SDValue BasePtr = St->getBasePtr();
8061     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8062                                   StVal.getNode()->getOperand(0), BasePtr,
8063                                   St->getPointerInfo(), St->isVolatile(),
8064                                   St->isNonTemporal(), St->getAlignment());
8065
8066     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8067                                     DAG.getConstant(4, MVT::i32));
8068     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8069                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8070                         St->isNonTemporal(),
8071                         std::min(4U, St->getAlignment() / 2));
8072   }
8073
8074   if (StVal.getValueType() != MVT::i64 ||
8075       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8076     return SDValue();
8077
8078   // Bitcast an i64 store extracted from a vector to f64.
8079   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8080   SelectionDAG &DAG = DCI.DAG;
8081   DebugLoc dl = StVal.getDebugLoc();
8082   SDValue IntVec = StVal.getOperand(0);
8083   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8084                                  IntVec.getValueType().getVectorNumElements());
8085   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8086   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8087                                Vec, StVal.getOperand(1));
8088   dl = N->getDebugLoc();
8089   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8090   // Make the DAGCombiner fold the bitcasts.
8091   DCI.AddToWorklist(Vec.getNode());
8092   DCI.AddToWorklist(ExtElt.getNode());
8093   DCI.AddToWorklist(V.getNode());
8094   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8095                       St->getPointerInfo(), St->isVolatile(),
8096                       St->isNonTemporal(), St->getAlignment(),
8097                       St->getTBAAInfo());
8098 }
8099
8100 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8101 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8102 /// i64 vector to have f64 elements, since the value can then be loaded
8103 /// directly into a VFP register.
8104 static bool hasNormalLoadOperand(SDNode *N) {
8105   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8106   for (unsigned i = 0; i < NumElts; ++i) {
8107     SDNode *Elt = N->getOperand(i).getNode();
8108     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8109       return true;
8110   }
8111   return false;
8112 }
8113
8114 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8115 /// ISD::BUILD_VECTOR.
8116 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8117                                           TargetLowering::DAGCombinerInfo &DCI){
8118   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8119   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8120   // into a pair of GPRs, which is fine when the value is used as a scalar,
8121   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8122   SelectionDAG &DAG = DCI.DAG;
8123   if (N->getNumOperands() == 2) {
8124     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8125     if (RV.getNode())
8126       return RV;
8127   }
8128
8129   // Load i64 elements as f64 values so that type legalization does not split
8130   // them up into i32 values.
8131   EVT VT = N->getValueType(0);
8132   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8133     return SDValue();
8134   DebugLoc dl = N->getDebugLoc();
8135   SmallVector<SDValue, 8> Ops;
8136   unsigned NumElts = VT.getVectorNumElements();
8137   for (unsigned i = 0; i < NumElts; ++i) {
8138     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8139     Ops.push_back(V);
8140     // Make the DAGCombiner fold the bitcast.
8141     DCI.AddToWorklist(V.getNode());
8142   }
8143   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8144   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8145   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8146 }
8147
8148 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8149 /// ISD::INSERT_VECTOR_ELT.
8150 static SDValue PerformInsertEltCombine(SDNode *N,
8151                                        TargetLowering::DAGCombinerInfo &DCI) {
8152   // Bitcast an i64 load inserted into a vector to f64.
8153   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8154   EVT VT = N->getValueType(0);
8155   SDNode *Elt = N->getOperand(1).getNode();
8156   if (VT.getVectorElementType() != MVT::i64 ||
8157       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8158     return SDValue();
8159
8160   SelectionDAG &DAG = DCI.DAG;
8161   DebugLoc dl = N->getDebugLoc();
8162   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8163                                  VT.getVectorNumElements());
8164   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8165   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8166   // Make the DAGCombiner fold the bitcasts.
8167   DCI.AddToWorklist(Vec.getNode());
8168   DCI.AddToWorklist(V.getNode());
8169   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8170                                Vec, V, N->getOperand(2));
8171   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8172 }
8173
8174 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8175 /// ISD::VECTOR_SHUFFLE.
8176 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8177   // The LLVM shufflevector instruction does not require the shuffle mask
8178   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8179   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8180   // operands do not match the mask length, they are extended by concatenating
8181   // them with undef vectors.  That is probably the right thing for other
8182   // targets, but for NEON it is better to concatenate two double-register
8183   // size vector operands into a single quad-register size vector.  Do that
8184   // transformation here:
8185   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8186   //   shuffle(concat(v1, v2), undef)
8187   SDValue Op0 = N->getOperand(0);
8188   SDValue Op1 = N->getOperand(1);
8189   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8190       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8191       Op0.getNumOperands() != 2 ||
8192       Op1.getNumOperands() != 2)
8193     return SDValue();
8194   SDValue Concat0Op1 = Op0.getOperand(1);
8195   SDValue Concat1Op1 = Op1.getOperand(1);
8196   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8197       Concat1Op1.getOpcode() != ISD::UNDEF)
8198     return SDValue();
8199   // Skip the transformation if any of the types are illegal.
8200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8201   EVT VT = N->getValueType(0);
8202   if (!TLI.isTypeLegal(VT) ||
8203       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8204       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8205     return SDValue();
8206
8207   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8208                                   Op0.getOperand(0), Op1.getOperand(0));
8209   // Translate the shuffle mask.
8210   SmallVector<int, 16> NewMask;
8211   unsigned NumElts = VT.getVectorNumElements();
8212   unsigned HalfElts = NumElts/2;
8213   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8214   for (unsigned n = 0; n < NumElts; ++n) {
8215     int MaskElt = SVN->getMaskElt(n);
8216     int NewElt = -1;
8217     if (MaskElt < (int)HalfElts)
8218       NewElt = MaskElt;
8219     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8220       NewElt = HalfElts + MaskElt - NumElts;
8221     NewMask.push_back(NewElt);
8222   }
8223   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8224                               DAG.getUNDEF(VT), NewMask.data());
8225 }
8226
8227 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8228 /// NEON load/store intrinsics to merge base address updates.
8229 static SDValue CombineBaseUpdate(SDNode *N,
8230                                  TargetLowering::DAGCombinerInfo &DCI) {
8231   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8232     return SDValue();
8233
8234   SelectionDAG &DAG = DCI.DAG;
8235   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8236                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8237   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8238   SDValue Addr = N->getOperand(AddrOpIdx);
8239
8240   // Search for a use of the address operand that is an increment.
8241   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8242          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8243     SDNode *User = *UI;
8244     if (User->getOpcode() != ISD::ADD ||
8245         UI.getUse().getResNo() != Addr.getResNo())
8246       continue;
8247
8248     // Check that the add is independent of the load/store.  Otherwise, folding
8249     // it would create a cycle.
8250     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8251       continue;
8252
8253     // Find the new opcode for the updating load/store.
8254     bool isLoad = true;
8255     bool isLaneOp = false;
8256     unsigned NewOpc = 0;
8257     unsigned NumVecs = 0;
8258     if (isIntrinsic) {
8259       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8260       switch (IntNo) {
8261       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8262       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8263         NumVecs = 1; break;
8264       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8265         NumVecs = 2; break;
8266       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8267         NumVecs = 3; break;
8268       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8269         NumVecs = 4; break;
8270       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8271         NumVecs = 2; isLaneOp = true; break;
8272       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8273         NumVecs = 3; isLaneOp = true; break;
8274       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8275         NumVecs = 4; isLaneOp = true; break;
8276       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8277         NumVecs = 1; isLoad = false; break;
8278       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8279         NumVecs = 2; isLoad = false; break;
8280       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8281         NumVecs = 3; isLoad = false; break;
8282       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8283         NumVecs = 4; isLoad = false; break;
8284       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8285         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8286       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8287         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8288       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8289         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8290       }
8291     } else {
8292       isLaneOp = true;
8293       switch (N->getOpcode()) {
8294       default: llvm_unreachable("unexpected opcode for Neon base update");
8295       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8296       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8297       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8298       }
8299     }
8300
8301     // Find the size of memory referenced by the load/store.
8302     EVT VecTy;
8303     if (isLoad)
8304       VecTy = N->getValueType(0);
8305     else
8306       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8307     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8308     if (isLaneOp)
8309       NumBytes /= VecTy.getVectorNumElements();
8310
8311     // If the increment is a constant, it must match the memory ref size.
8312     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8313     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8314       uint64_t IncVal = CInc->getZExtValue();
8315       if (IncVal != NumBytes)
8316         continue;
8317     } else if (NumBytes >= 3 * 16) {
8318       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8319       // separate instructions that make it harder to use a non-constant update.
8320       continue;
8321     }
8322
8323     // Create the new updating load/store node.
8324     EVT Tys[6];
8325     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8326     unsigned n;
8327     for (n = 0; n < NumResultVecs; ++n)
8328       Tys[n] = VecTy;
8329     Tys[n++] = MVT::i32;
8330     Tys[n] = MVT::Other;
8331     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8332     SmallVector<SDValue, 8> Ops;
8333     Ops.push_back(N->getOperand(0)); // incoming chain
8334     Ops.push_back(N->getOperand(AddrOpIdx));
8335     Ops.push_back(Inc);
8336     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8337       Ops.push_back(N->getOperand(i));
8338     }
8339     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8340     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8341                                            Ops.data(), Ops.size(),
8342                                            MemInt->getMemoryVT(),
8343                                            MemInt->getMemOperand());
8344
8345     // Update the uses.
8346     std::vector<SDValue> NewResults;
8347     for (unsigned i = 0; i < NumResultVecs; ++i) {
8348       NewResults.push_back(SDValue(UpdN.getNode(), i));
8349     }
8350     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8351     DCI.CombineTo(N, NewResults);
8352     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8353
8354     break;
8355   }
8356   return SDValue();
8357 }
8358
8359 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8360 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8361 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8362 /// return true.
8363 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8364   SelectionDAG &DAG = DCI.DAG;
8365   EVT VT = N->getValueType(0);
8366   // vldN-dup instructions only support 64-bit vectors for N > 1.
8367   if (!VT.is64BitVector())
8368     return false;
8369
8370   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8371   SDNode *VLD = N->getOperand(0).getNode();
8372   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8373     return false;
8374   unsigned NumVecs = 0;
8375   unsigned NewOpc = 0;
8376   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8377   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8378     NumVecs = 2;
8379     NewOpc = ARMISD::VLD2DUP;
8380   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8381     NumVecs = 3;
8382     NewOpc = ARMISD::VLD3DUP;
8383   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8384     NumVecs = 4;
8385     NewOpc = ARMISD::VLD4DUP;
8386   } else {
8387     return false;
8388   }
8389
8390   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8391   // numbers match the load.
8392   unsigned VLDLaneNo =
8393     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8394   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8395        UI != UE; ++UI) {
8396     // Ignore uses of the chain result.
8397     if (UI.getUse().getResNo() == NumVecs)
8398       continue;
8399     SDNode *User = *UI;
8400     if (User->getOpcode() != ARMISD::VDUPLANE ||
8401         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8402       return false;
8403   }
8404
8405   // Create the vldN-dup node.
8406   EVT Tys[5];
8407   unsigned n;
8408   for (n = 0; n < NumVecs; ++n)
8409     Tys[n] = VT;
8410   Tys[n] = MVT::Other;
8411   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8412   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8413   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8414   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8415                                            Ops, 2, VLDMemInt->getMemoryVT(),
8416                                            VLDMemInt->getMemOperand());
8417
8418   // Update the uses.
8419   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8420        UI != UE; ++UI) {
8421     unsigned ResNo = UI.getUse().getResNo();
8422     // Ignore uses of the chain result.
8423     if (ResNo == NumVecs)
8424       continue;
8425     SDNode *User = *UI;
8426     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8427   }
8428
8429   // Now the vldN-lane intrinsic is dead except for its chain result.
8430   // Update uses of the chain.
8431   std::vector<SDValue> VLDDupResults;
8432   for (unsigned n = 0; n < NumVecs; ++n)
8433     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8434   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8435   DCI.CombineTo(VLD, VLDDupResults);
8436
8437   return true;
8438 }
8439
8440 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8441 /// ARMISD::VDUPLANE.
8442 static SDValue PerformVDUPLANECombine(SDNode *N,
8443                                       TargetLowering::DAGCombinerInfo &DCI) {
8444   SDValue Op = N->getOperand(0);
8445
8446   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8447   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8448   if (CombineVLDDUP(N, DCI))
8449     return SDValue(N, 0);
8450
8451   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8452   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8453   while (Op.getOpcode() == ISD::BITCAST)
8454     Op = Op.getOperand(0);
8455   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8456     return SDValue();
8457
8458   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8459   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8460   // The canonical VMOV for a zero vector uses a 32-bit element size.
8461   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8462   unsigned EltBits;
8463   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8464     EltSize = 8;
8465   EVT VT = N->getValueType(0);
8466   if (EltSize > VT.getVectorElementType().getSizeInBits())
8467     return SDValue();
8468
8469   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8470 }
8471
8472 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8473 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8474 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8475 {
8476   integerPart cN;
8477   integerPart c0 = 0;
8478   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8479        I != E; I++) {
8480     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8481     if (!C)
8482       return false;
8483
8484     bool isExact;
8485     APFloat APF = C->getValueAPF();
8486     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8487         != APFloat::opOK || !isExact)
8488       return false;
8489
8490     c0 = (I == 0) ? cN : c0;
8491     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8492       return false;
8493   }
8494   C = c0;
8495   return true;
8496 }
8497
8498 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8499 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8500 /// when the VMUL has a constant operand that is a power of 2.
8501 ///
8502 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8503 ///  vmul.f32        d16, d17, d16
8504 ///  vcvt.s32.f32    d16, d16
8505 /// becomes:
8506 ///  vcvt.s32.f32    d16, d16, #3
8507 static SDValue PerformVCVTCombine(SDNode *N,
8508                                   TargetLowering::DAGCombinerInfo &DCI,
8509                                   const ARMSubtarget *Subtarget) {
8510   SelectionDAG &DAG = DCI.DAG;
8511   SDValue Op = N->getOperand(0);
8512
8513   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8514       Op.getOpcode() != ISD::FMUL)
8515     return SDValue();
8516
8517   uint64_t C;
8518   SDValue N0 = Op->getOperand(0);
8519   SDValue ConstVec = Op->getOperand(1);
8520   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8521
8522   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8523       !isConstVecPow2(ConstVec, isSigned, C))
8524     return SDValue();
8525
8526   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8527     Intrinsic::arm_neon_vcvtfp2fxu;
8528   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8529                      N->getValueType(0),
8530                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8531                      DAG.getConstant(Log2_64(C), MVT::i32));
8532 }
8533
8534 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8535 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8536 /// when the VDIV has a constant operand that is a power of 2.
8537 ///
8538 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8539 ///  vcvt.f32.s32    d16, d16
8540 ///  vdiv.f32        d16, d17, d16
8541 /// becomes:
8542 ///  vcvt.f32.s32    d16, d16, #3
8543 static SDValue PerformVDIVCombine(SDNode *N,
8544                                   TargetLowering::DAGCombinerInfo &DCI,
8545                                   const ARMSubtarget *Subtarget) {
8546   SelectionDAG &DAG = DCI.DAG;
8547   SDValue Op = N->getOperand(0);
8548   unsigned OpOpcode = Op.getNode()->getOpcode();
8549
8550   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8551       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8552     return SDValue();
8553
8554   uint64_t C;
8555   SDValue ConstVec = N->getOperand(1);
8556   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8557
8558   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8559       !isConstVecPow2(ConstVec, isSigned, C))
8560     return SDValue();
8561
8562   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8563     Intrinsic::arm_neon_vcvtfxu2fp;
8564   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8565                      Op.getValueType(),
8566                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8567                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8568 }
8569
8570 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8571 /// operand of a vector shift operation, where all the elements of the
8572 /// build_vector must have the same constant integer value.
8573 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8574   // Ignore bit_converts.
8575   while (Op.getOpcode() == ISD::BITCAST)
8576     Op = Op.getOperand(0);
8577   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8578   APInt SplatBits, SplatUndef;
8579   unsigned SplatBitSize;
8580   bool HasAnyUndefs;
8581   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8582                                       HasAnyUndefs, ElementBits) ||
8583       SplatBitSize > ElementBits)
8584     return false;
8585   Cnt = SplatBits.getSExtValue();
8586   return true;
8587 }
8588
8589 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8590 /// operand of a vector shift left operation.  That value must be in the range:
8591 ///   0 <= Value < ElementBits for a left shift; or
8592 ///   0 <= Value <= ElementBits for a long left shift.
8593 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8594   assert(VT.isVector() && "vector shift count is not a vector type");
8595   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8596   if (! getVShiftImm(Op, ElementBits, Cnt))
8597     return false;
8598   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8599 }
8600
8601 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8602 /// operand of a vector shift right operation.  For a shift opcode, the value
8603 /// is positive, but for an intrinsic the value count must be negative. The
8604 /// absolute value must be in the range:
8605 ///   1 <= |Value| <= ElementBits for a right shift; or
8606 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8607 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8608                          int64_t &Cnt) {
8609   assert(VT.isVector() && "vector shift count is not a vector type");
8610   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8611   if (! getVShiftImm(Op, ElementBits, Cnt))
8612     return false;
8613   if (isIntrinsic)
8614     Cnt = -Cnt;
8615   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8616 }
8617
8618 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8619 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8620   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8621   switch (IntNo) {
8622   default:
8623     // Don't do anything for most intrinsics.
8624     break;
8625
8626   // Vector shifts: check for immediate versions and lower them.
8627   // Note: This is done during DAG combining instead of DAG legalizing because
8628   // the build_vectors for 64-bit vector element shift counts are generally
8629   // not legal, and it is hard to see their values after they get legalized to
8630   // loads from a constant pool.
8631   case Intrinsic::arm_neon_vshifts:
8632   case Intrinsic::arm_neon_vshiftu:
8633   case Intrinsic::arm_neon_vshiftls:
8634   case Intrinsic::arm_neon_vshiftlu:
8635   case Intrinsic::arm_neon_vshiftn:
8636   case Intrinsic::arm_neon_vrshifts:
8637   case Intrinsic::arm_neon_vrshiftu:
8638   case Intrinsic::arm_neon_vrshiftn:
8639   case Intrinsic::arm_neon_vqshifts:
8640   case Intrinsic::arm_neon_vqshiftu:
8641   case Intrinsic::arm_neon_vqshiftsu:
8642   case Intrinsic::arm_neon_vqshiftns:
8643   case Intrinsic::arm_neon_vqshiftnu:
8644   case Intrinsic::arm_neon_vqshiftnsu:
8645   case Intrinsic::arm_neon_vqrshiftns:
8646   case Intrinsic::arm_neon_vqrshiftnu:
8647   case Intrinsic::arm_neon_vqrshiftnsu: {
8648     EVT VT = N->getOperand(1).getValueType();
8649     int64_t Cnt;
8650     unsigned VShiftOpc = 0;
8651
8652     switch (IntNo) {
8653     case Intrinsic::arm_neon_vshifts:
8654     case Intrinsic::arm_neon_vshiftu:
8655       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8656         VShiftOpc = ARMISD::VSHL;
8657         break;
8658       }
8659       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8660         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8661                      ARMISD::VSHRs : ARMISD::VSHRu);
8662         break;
8663       }
8664       return SDValue();
8665
8666     case Intrinsic::arm_neon_vshiftls:
8667     case Intrinsic::arm_neon_vshiftlu:
8668       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8669         break;
8670       llvm_unreachable("invalid shift count for vshll intrinsic");
8671
8672     case Intrinsic::arm_neon_vrshifts:
8673     case Intrinsic::arm_neon_vrshiftu:
8674       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8675         break;
8676       return SDValue();
8677
8678     case Intrinsic::arm_neon_vqshifts:
8679     case Intrinsic::arm_neon_vqshiftu:
8680       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8681         break;
8682       return SDValue();
8683
8684     case Intrinsic::arm_neon_vqshiftsu:
8685       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8686         break;
8687       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8688
8689     case Intrinsic::arm_neon_vshiftn:
8690     case Intrinsic::arm_neon_vrshiftn:
8691     case Intrinsic::arm_neon_vqshiftns:
8692     case Intrinsic::arm_neon_vqshiftnu:
8693     case Intrinsic::arm_neon_vqshiftnsu:
8694     case Intrinsic::arm_neon_vqrshiftns:
8695     case Intrinsic::arm_neon_vqrshiftnu:
8696     case Intrinsic::arm_neon_vqrshiftnsu:
8697       // Narrowing shifts require an immediate right shift.
8698       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8699         break;
8700       llvm_unreachable("invalid shift count for narrowing vector shift "
8701                        "intrinsic");
8702
8703     default:
8704       llvm_unreachable("unhandled vector shift");
8705     }
8706
8707     switch (IntNo) {
8708     case Intrinsic::arm_neon_vshifts:
8709     case Intrinsic::arm_neon_vshiftu:
8710       // Opcode already set above.
8711       break;
8712     case Intrinsic::arm_neon_vshiftls:
8713     case Intrinsic::arm_neon_vshiftlu:
8714       if (Cnt == VT.getVectorElementType().getSizeInBits())
8715         VShiftOpc = ARMISD::VSHLLi;
8716       else
8717         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8718                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8719       break;
8720     case Intrinsic::arm_neon_vshiftn:
8721       VShiftOpc = ARMISD::VSHRN; break;
8722     case Intrinsic::arm_neon_vrshifts:
8723       VShiftOpc = ARMISD::VRSHRs; break;
8724     case Intrinsic::arm_neon_vrshiftu:
8725       VShiftOpc = ARMISD::VRSHRu; break;
8726     case Intrinsic::arm_neon_vrshiftn:
8727       VShiftOpc = ARMISD::VRSHRN; break;
8728     case Intrinsic::arm_neon_vqshifts:
8729       VShiftOpc = ARMISD::VQSHLs; break;
8730     case Intrinsic::arm_neon_vqshiftu:
8731       VShiftOpc = ARMISD::VQSHLu; break;
8732     case Intrinsic::arm_neon_vqshiftsu:
8733       VShiftOpc = ARMISD::VQSHLsu; break;
8734     case Intrinsic::arm_neon_vqshiftns:
8735       VShiftOpc = ARMISD::VQSHRNs; break;
8736     case Intrinsic::arm_neon_vqshiftnu:
8737       VShiftOpc = ARMISD::VQSHRNu; break;
8738     case Intrinsic::arm_neon_vqshiftnsu:
8739       VShiftOpc = ARMISD::VQSHRNsu; break;
8740     case Intrinsic::arm_neon_vqrshiftns:
8741       VShiftOpc = ARMISD::VQRSHRNs; break;
8742     case Intrinsic::arm_neon_vqrshiftnu:
8743       VShiftOpc = ARMISD::VQRSHRNu; break;
8744     case Intrinsic::arm_neon_vqrshiftnsu:
8745       VShiftOpc = ARMISD::VQRSHRNsu; break;
8746     }
8747
8748     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8749                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8750   }
8751
8752   case Intrinsic::arm_neon_vshiftins: {
8753     EVT VT = N->getOperand(1).getValueType();
8754     int64_t Cnt;
8755     unsigned VShiftOpc = 0;
8756
8757     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8758       VShiftOpc = ARMISD::VSLI;
8759     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8760       VShiftOpc = ARMISD::VSRI;
8761     else {
8762       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8763     }
8764
8765     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8766                        N->getOperand(1), N->getOperand(2),
8767                        DAG.getConstant(Cnt, MVT::i32));
8768   }
8769
8770   case Intrinsic::arm_neon_vqrshifts:
8771   case Intrinsic::arm_neon_vqrshiftu:
8772     // No immediate versions of these to check for.
8773     break;
8774   }
8775
8776   return SDValue();
8777 }
8778
8779 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8780 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8781 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8782 /// vector element shift counts are generally not legal, and it is hard to see
8783 /// their values after they get legalized to loads from a constant pool.
8784 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8785                                    const ARMSubtarget *ST) {
8786   EVT VT = N->getValueType(0);
8787   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8788     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8789     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8790     SDValue N1 = N->getOperand(1);
8791     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8792       SDValue N0 = N->getOperand(0);
8793       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8794           DAG.MaskedValueIsZero(N0.getOperand(0),
8795                                 APInt::getHighBitsSet(32, 16)))
8796         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8797     }
8798   }
8799
8800   // Nothing to be done for scalar shifts.
8801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8802   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8803     return SDValue();
8804
8805   assert(ST->hasNEON() && "unexpected vector shift");
8806   int64_t Cnt;
8807
8808   switch (N->getOpcode()) {
8809   default: llvm_unreachable("unexpected shift opcode");
8810
8811   case ISD::SHL:
8812     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8813       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8814                          DAG.getConstant(Cnt, MVT::i32));
8815     break;
8816
8817   case ISD::SRA:
8818   case ISD::SRL:
8819     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8820       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8821                             ARMISD::VSHRs : ARMISD::VSHRu);
8822       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8823                          DAG.getConstant(Cnt, MVT::i32));
8824     }
8825   }
8826   return SDValue();
8827 }
8828
8829 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8830 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8831 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8832                                     const ARMSubtarget *ST) {
8833   SDValue N0 = N->getOperand(0);
8834
8835   // Check for sign- and zero-extensions of vector extract operations of 8-
8836   // and 16-bit vector elements.  NEON supports these directly.  They are
8837   // handled during DAG combining because type legalization will promote them
8838   // to 32-bit types and it is messy to recognize the operations after that.
8839   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8840     SDValue Vec = N0.getOperand(0);
8841     SDValue Lane = N0.getOperand(1);
8842     EVT VT = N->getValueType(0);
8843     EVT EltVT = N0.getValueType();
8844     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8845
8846     if (VT == MVT::i32 &&
8847         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8848         TLI.isTypeLegal(Vec.getValueType()) &&
8849         isa<ConstantSDNode>(Lane)) {
8850
8851       unsigned Opc = 0;
8852       switch (N->getOpcode()) {
8853       default: llvm_unreachable("unexpected opcode");
8854       case ISD::SIGN_EXTEND:
8855         Opc = ARMISD::VGETLANEs;
8856         break;
8857       case ISD::ZERO_EXTEND:
8858       case ISD::ANY_EXTEND:
8859         Opc = ARMISD::VGETLANEu;
8860         break;
8861       }
8862       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8863     }
8864   }
8865
8866   return SDValue();
8867 }
8868
8869 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8870 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8871 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8872                                        const ARMSubtarget *ST) {
8873   // If the target supports NEON, try to use vmax/vmin instructions for f32
8874   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8875   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8876   // a NaN; only do the transformation when it matches that behavior.
8877
8878   // For now only do this when using NEON for FP operations; if using VFP, it
8879   // is not obvious that the benefit outweighs the cost of switching to the
8880   // NEON pipeline.
8881   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8882       N->getValueType(0) != MVT::f32)
8883     return SDValue();
8884
8885   SDValue CondLHS = N->getOperand(0);
8886   SDValue CondRHS = N->getOperand(1);
8887   SDValue LHS = N->getOperand(2);
8888   SDValue RHS = N->getOperand(3);
8889   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8890
8891   unsigned Opcode = 0;
8892   bool IsReversed;
8893   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8894     IsReversed = false; // x CC y ? x : y
8895   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8896     IsReversed = true ; // x CC y ? y : x
8897   } else {
8898     return SDValue();
8899   }
8900
8901   bool IsUnordered;
8902   switch (CC) {
8903   default: break;
8904   case ISD::SETOLT:
8905   case ISD::SETOLE:
8906   case ISD::SETLT:
8907   case ISD::SETLE:
8908   case ISD::SETULT:
8909   case ISD::SETULE:
8910     // If LHS is NaN, an ordered comparison will be false and the result will
8911     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8912     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8913     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8914     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8915       break;
8916     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8917     // will return -0, so vmin can only be used for unsafe math or if one of
8918     // the operands is known to be nonzero.
8919     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8920         !DAG.getTarget().Options.UnsafeFPMath &&
8921         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8922       break;
8923     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8924     break;
8925
8926   case ISD::SETOGT:
8927   case ISD::SETOGE:
8928   case ISD::SETGT:
8929   case ISD::SETGE:
8930   case ISD::SETUGT:
8931   case ISD::SETUGE:
8932     // If LHS is NaN, an ordered comparison will be false and the result will
8933     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8934     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8935     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8936     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8937       break;
8938     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8939     // will return +0, so vmax can only be used for unsafe math or if one of
8940     // the operands is known to be nonzero.
8941     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8942         !DAG.getTarget().Options.UnsafeFPMath &&
8943         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8944       break;
8945     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8946     break;
8947   }
8948
8949   if (!Opcode)
8950     return SDValue();
8951   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8952 }
8953
8954 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8955 SDValue
8956 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8957   SDValue Cmp = N->getOperand(4);
8958   if (Cmp.getOpcode() != ARMISD::CMPZ)
8959     // Only looking at EQ and NE cases.
8960     return SDValue();
8961
8962   EVT VT = N->getValueType(0);
8963   DebugLoc dl = N->getDebugLoc();
8964   SDValue LHS = Cmp.getOperand(0);
8965   SDValue RHS = Cmp.getOperand(1);
8966   SDValue FalseVal = N->getOperand(0);
8967   SDValue TrueVal = N->getOperand(1);
8968   SDValue ARMcc = N->getOperand(2);
8969   ARMCC::CondCodes CC =
8970     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8971
8972   // Simplify
8973   //   mov     r1, r0
8974   //   cmp     r1, x
8975   //   mov     r0, y
8976   //   moveq   r0, x
8977   // to
8978   //   cmp     r0, x
8979   //   movne   r0, y
8980   //
8981   //   mov     r1, r0
8982   //   cmp     r1, x
8983   //   mov     r0, x
8984   //   movne   r0, y
8985   // to
8986   //   cmp     r0, x
8987   //   movne   r0, y
8988   /// FIXME: Turn this into a target neutral optimization?
8989   SDValue Res;
8990   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8991     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8992                       N->getOperand(3), Cmp);
8993   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8994     SDValue ARMcc;
8995     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8996     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8997                       N->getOperand(3), NewCmp);
8998   }
8999
9000   if (Res.getNode()) {
9001     APInt KnownZero, KnownOne;
9002     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9003     // Capture demanded bits information that would be otherwise lost.
9004     if (KnownZero == 0xfffffffe)
9005       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9006                         DAG.getValueType(MVT::i1));
9007     else if (KnownZero == 0xffffff00)
9008       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9009                         DAG.getValueType(MVT::i8));
9010     else if (KnownZero == 0xffff0000)
9011       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9012                         DAG.getValueType(MVT::i16));
9013   }
9014
9015   return Res;
9016 }
9017
9018 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9019                                              DAGCombinerInfo &DCI) const {
9020   switch (N->getOpcode()) {
9021   default: break;
9022   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9023   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9024   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9025   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9026   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9027   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9028   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9029   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9030   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9031   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9032   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9033   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9034   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9035   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9036   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9037   case ISD::FP_TO_SINT:
9038   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9039   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9040   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9041   case ISD::SHL:
9042   case ISD::SRA:
9043   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9044   case ISD::SIGN_EXTEND:
9045   case ISD::ZERO_EXTEND:
9046   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9047   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9048   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9049   case ARMISD::VLD2DUP:
9050   case ARMISD::VLD3DUP:
9051   case ARMISD::VLD4DUP:
9052     return CombineBaseUpdate(N, DCI);
9053   case ISD::INTRINSIC_VOID:
9054   case ISD::INTRINSIC_W_CHAIN:
9055     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9056     case Intrinsic::arm_neon_vld1:
9057     case Intrinsic::arm_neon_vld2:
9058     case Intrinsic::arm_neon_vld3:
9059     case Intrinsic::arm_neon_vld4:
9060     case Intrinsic::arm_neon_vld2lane:
9061     case Intrinsic::arm_neon_vld3lane:
9062     case Intrinsic::arm_neon_vld4lane:
9063     case Intrinsic::arm_neon_vst1:
9064     case Intrinsic::arm_neon_vst2:
9065     case Intrinsic::arm_neon_vst3:
9066     case Intrinsic::arm_neon_vst4:
9067     case Intrinsic::arm_neon_vst2lane:
9068     case Intrinsic::arm_neon_vst3lane:
9069     case Intrinsic::arm_neon_vst4lane:
9070       return CombineBaseUpdate(N, DCI);
9071     default: break;
9072     }
9073     break;
9074   }
9075   return SDValue();
9076 }
9077
9078 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9079                                                           EVT VT) const {
9080   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9081 }
9082
9083 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9084   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9085   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9086
9087   switch (VT.getSimpleVT().SimpleTy) {
9088   default:
9089     return false;
9090   case MVT::i8:
9091   case MVT::i16:
9092   case MVT::i32:
9093     // Unaligned access can use (for example) LRDB, LRDH, LDR
9094     return AllowsUnaligned;
9095   case MVT::f64:
9096   case MVT::v2f64:
9097     // For any little-endian targets with neon, we can support unaligned ld/st
9098     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9099     // A big-endian target may also explictly support unaligned accesses
9100     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9101   }
9102 }
9103
9104 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9105                        unsigned AlignCheck) {
9106   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9107           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9108 }
9109
9110 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9111                                            unsigned DstAlign, unsigned SrcAlign,
9112                                            bool IsZeroVal,
9113                                            bool MemcpyStrSrc,
9114                                            MachineFunction &MF) const {
9115   const Function *F = MF.getFunction();
9116
9117   // See if we can use NEON instructions for this...
9118   if (IsZeroVal &&
9119       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat) &&
9120       Subtarget->hasNEON()) {
9121     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9122       return MVT::v4i32;
9123     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9124       return MVT::v2i32;
9125     }
9126   }
9127
9128   // Lowering to i32/i16 if the size permits.
9129   if (Size >= 4) {
9130     return MVT::i32;
9131   } else if (Size >= 2) {
9132     return MVT::i16;
9133   }
9134
9135   // Let the target-independent logic figure it out.
9136   return MVT::Other;
9137 }
9138
9139 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9140   if (V < 0)
9141     return false;
9142
9143   unsigned Scale = 1;
9144   switch (VT.getSimpleVT().SimpleTy) {
9145   default: return false;
9146   case MVT::i1:
9147   case MVT::i8:
9148     // Scale == 1;
9149     break;
9150   case MVT::i16:
9151     // Scale == 2;
9152     Scale = 2;
9153     break;
9154   case MVT::i32:
9155     // Scale == 4;
9156     Scale = 4;
9157     break;
9158   }
9159
9160   if ((V & (Scale - 1)) != 0)
9161     return false;
9162   V /= Scale;
9163   return V == (V & ((1LL << 5) - 1));
9164 }
9165
9166 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9167                                       const ARMSubtarget *Subtarget) {
9168   bool isNeg = false;
9169   if (V < 0) {
9170     isNeg = true;
9171     V = - V;
9172   }
9173
9174   switch (VT.getSimpleVT().SimpleTy) {
9175   default: return false;
9176   case MVT::i1:
9177   case MVT::i8:
9178   case MVT::i16:
9179   case MVT::i32:
9180     // + imm12 or - imm8
9181     if (isNeg)
9182       return V == (V & ((1LL << 8) - 1));
9183     return V == (V & ((1LL << 12) - 1));
9184   case MVT::f32:
9185   case MVT::f64:
9186     // Same as ARM mode. FIXME: NEON?
9187     if (!Subtarget->hasVFP2())
9188       return false;
9189     if ((V & 3) != 0)
9190       return false;
9191     V >>= 2;
9192     return V == (V & ((1LL << 8) - 1));
9193   }
9194 }
9195
9196 /// isLegalAddressImmediate - Return true if the integer value can be used
9197 /// as the offset of the target addressing mode for load / store of the
9198 /// given type.
9199 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9200                                     const ARMSubtarget *Subtarget) {
9201   if (V == 0)
9202     return true;
9203
9204   if (!VT.isSimple())
9205     return false;
9206
9207   if (Subtarget->isThumb1Only())
9208     return isLegalT1AddressImmediate(V, VT);
9209   else if (Subtarget->isThumb2())
9210     return isLegalT2AddressImmediate(V, VT, Subtarget);
9211
9212   // ARM mode.
9213   if (V < 0)
9214     V = - V;
9215   switch (VT.getSimpleVT().SimpleTy) {
9216   default: return false;
9217   case MVT::i1:
9218   case MVT::i8:
9219   case MVT::i32:
9220     // +- imm12
9221     return V == (V & ((1LL << 12) - 1));
9222   case MVT::i16:
9223     // +- imm8
9224     return V == (V & ((1LL << 8) - 1));
9225   case MVT::f32:
9226   case MVT::f64:
9227     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9228       return false;
9229     if ((V & 3) != 0)
9230       return false;
9231     V >>= 2;
9232     return V == (V & ((1LL << 8) - 1));
9233   }
9234 }
9235
9236 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9237                                                       EVT VT) const {
9238   int Scale = AM.Scale;
9239   if (Scale < 0)
9240     return false;
9241
9242   switch (VT.getSimpleVT().SimpleTy) {
9243   default: return false;
9244   case MVT::i1:
9245   case MVT::i8:
9246   case MVT::i16:
9247   case MVT::i32:
9248     if (Scale == 1)
9249       return true;
9250     // r + r << imm
9251     Scale = Scale & ~1;
9252     return Scale == 2 || Scale == 4 || Scale == 8;
9253   case MVT::i64:
9254     // r + r
9255     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9256       return true;
9257     return false;
9258   case MVT::isVoid:
9259     // Note, we allow "void" uses (basically, uses that aren't loads or
9260     // stores), because arm allows folding a scale into many arithmetic
9261     // operations.  This should be made more precise and revisited later.
9262
9263     // Allow r << imm, but the imm has to be a multiple of two.
9264     if (Scale & 1) return false;
9265     return isPowerOf2_32(Scale);
9266   }
9267 }
9268
9269 /// isLegalAddressingMode - Return true if the addressing mode represented
9270 /// by AM is legal for this target, for a load/store of the specified type.
9271 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9272                                               Type *Ty) const {
9273   EVT VT = getValueType(Ty, true);
9274   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9275     return false;
9276
9277   // Can never fold addr of global into load/store.
9278   if (AM.BaseGV)
9279     return false;
9280
9281   switch (AM.Scale) {
9282   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9283     break;
9284   case 1:
9285     if (Subtarget->isThumb1Only())
9286       return false;
9287     // FALL THROUGH.
9288   default:
9289     // ARM doesn't support any R+R*scale+imm addr modes.
9290     if (AM.BaseOffs)
9291       return false;
9292
9293     if (!VT.isSimple())
9294       return false;
9295
9296     if (Subtarget->isThumb2())
9297       return isLegalT2ScaledAddressingMode(AM, VT);
9298
9299     int Scale = AM.Scale;
9300     switch (VT.getSimpleVT().SimpleTy) {
9301     default: return false;
9302     case MVT::i1:
9303     case MVT::i8:
9304     case MVT::i32:
9305       if (Scale < 0) Scale = -Scale;
9306       if (Scale == 1)
9307         return true;
9308       // r + r << imm
9309       return isPowerOf2_32(Scale & ~1);
9310     case MVT::i16:
9311     case MVT::i64:
9312       // r + r
9313       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9314         return true;
9315       return false;
9316
9317     case MVT::isVoid:
9318       // Note, we allow "void" uses (basically, uses that aren't loads or
9319       // stores), because arm allows folding a scale into many arithmetic
9320       // operations.  This should be made more precise and revisited later.
9321
9322       // Allow r << imm, but the imm has to be a multiple of two.
9323       if (Scale & 1) return false;
9324       return isPowerOf2_32(Scale);
9325     }
9326   }
9327   return true;
9328 }
9329
9330 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9331 /// icmp immediate, that is the target has icmp instructions which can compare
9332 /// a register against the immediate without having to materialize the
9333 /// immediate into a register.
9334 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9335   // Thumb2 and ARM modes can use cmn for negative immediates.
9336   if (!Subtarget->isThumb())
9337     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9338   if (Subtarget->isThumb2())
9339     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9340   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9341   return Imm >= 0 && Imm <= 255;
9342 }
9343
9344 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9345 /// *or sub* immediate, that is the target has add or sub instructions which can
9346 /// add a register with the immediate without having to materialize the
9347 /// immediate into a register.
9348 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9349   // Same encoding for add/sub, just flip the sign.
9350   int64_t AbsImm = llvm::abs64(Imm);
9351   if (!Subtarget->isThumb())
9352     return ARM_AM::getSOImmVal(AbsImm) != -1;
9353   if (Subtarget->isThumb2())
9354     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9355   // Thumb1 only has 8-bit unsigned immediate.
9356   return AbsImm >= 0 && AbsImm <= 255;
9357 }
9358
9359 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9360                                       bool isSEXTLoad, SDValue &Base,
9361                                       SDValue &Offset, bool &isInc,
9362                                       SelectionDAG &DAG) {
9363   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9364     return false;
9365
9366   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9367     // AddressingMode 3
9368     Base = Ptr->getOperand(0);
9369     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9370       int RHSC = (int)RHS->getZExtValue();
9371       if (RHSC < 0 && RHSC > -256) {
9372         assert(Ptr->getOpcode() == ISD::ADD);
9373         isInc = false;
9374         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9375         return true;
9376       }
9377     }
9378     isInc = (Ptr->getOpcode() == ISD::ADD);
9379     Offset = Ptr->getOperand(1);
9380     return true;
9381   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9382     // AddressingMode 2
9383     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9384       int RHSC = (int)RHS->getZExtValue();
9385       if (RHSC < 0 && RHSC > -0x1000) {
9386         assert(Ptr->getOpcode() == ISD::ADD);
9387         isInc = false;
9388         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9389         Base = Ptr->getOperand(0);
9390         return true;
9391       }
9392     }
9393
9394     if (Ptr->getOpcode() == ISD::ADD) {
9395       isInc = true;
9396       ARM_AM::ShiftOpc ShOpcVal=
9397         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9398       if (ShOpcVal != ARM_AM::no_shift) {
9399         Base = Ptr->getOperand(1);
9400         Offset = Ptr->getOperand(0);
9401       } else {
9402         Base = Ptr->getOperand(0);
9403         Offset = Ptr->getOperand(1);
9404       }
9405       return true;
9406     }
9407
9408     isInc = (Ptr->getOpcode() == ISD::ADD);
9409     Base = Ptr->getOperand(0);
9410     Offset = Ptr->getOperand(1);
9411     return true;
9412   }
9413
9414   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9415   return false;
9416 }
9417
9418 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9419                                      bool isSEXTLoad, SDValue &Base,
9420                                      SDValue &Offset, bool &isInc,
9421                                      SelectionDAG &DAG) {
9422   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9423     return false;
9424
9425   Base = Ptr->getOperand(0);
9426   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9427     int RHSC = (int)RHS->getZExtValue();
9428     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9429       assert(Ptr->getOpcode() == ISD::ADD);
9430       isInc = false;
9431       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9432       return true;
9433     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9434       isInc = Ptr->getOpcode() == ISD::ADD;
9435       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9436       return true;
9437     }
9438   }
9439
9440   return false;
9441 }
9442
9443 /// getPreIndexedAddressParts - returns true by value, base pointer and
9444 /// offset pointer and addressing mode by reference if the node's address
9445 /// can be legally represented as pre-indexed load / store address.
9446 bool
9447 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9448                                              SDValue &Offset,
9449                                              ISD::MemIndexedMode &AM,
9450                                              SelectionDAG &DAG) const {
9451   if (Subtarget->isThumb1Only())
9452     return false;
9453
9454   EVT VT;
9455   SDValue Ptr;
9456   bool isSEXTLoad = false;
9457   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9458     Ptr = LD->getBasePtr();
9459     VT  = LD->getMemoryVT();
9460     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9461   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9462     Ptr = ST->getBasePtr();
9463     VT  = ST->getMemoryVT();
9464   } else
9465     return false;
9466
9467   bool isInc;
9468   bool isLegal = false;
9469   if (Subtarget->isThumb2())
9470     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9471                                        Offset, isInc, DAG);
9472   else
9473     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9474                                         Offset, isInc, DAG);
9475   if (!isLegal)
9476     return false;
9477
9478   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9479   return true;
9480 }
9481
9482 /// getPostIndexedAddressParts - returns true by value, base pointer and
9483 /// offset pointer and addressing mode by reference if this node can be
9484 /// combined with a load / store to form a post-indexed load / store.
9485 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9486                                                    SDValue &Base,
9487                                                    SDValue &Offset,
9488                                                    ISD::MemIndexedMode &AM,
9489                                                    SelectionDAG &DAG) const {
9490   if (Subtarget->isThumb1Only())
9491     return false;
9492
9493   EVT VT;
9494   SDValue Ptr;
9495   bool isSEXTLoad = false;
9496   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9497     VT  = LD->getMemoryVT();
9498     Ptr = LD->getBasePtr();
9499     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9500   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9501     VT  = ST->getMemoryVT();
9502     Ptr = ST->getBasePtr();
9503   } else
9504     return false;
9505
9506   bool isInc;
9507   bool isLegal = false;
9508   if (Subtarget->isThumb2())
9509     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9510                                        isInc, DAG);
9511   else
9512     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9513                                         isInc, DAG);
9514   if (!isLegal)
9515     return false;
9516
9517   if (Ptr != Base) {
9518     // Swap base ptr and offset to catch more post-index load / store when
9519     // it's legal. In Thumb2 mode, offset must be an immediate.
9520     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9521         !Subtarget->isThumb2())
9522       std::swap(Base, Offset);
9523
9524     // Post-indexed load / store update the base pointer.
9525     if (Ptr != Base)
9526       return false;
9527   }
9528
9529   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9530   return true;
9531 }
9532
9533 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9534                                                        APInt &KnownZero,
9535                                                        APInt &KnownOne,
9536                                                        const SelectionDAG &DAG,
9537                                                        unsigned Depth) const {
9538   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9539   switch (Op.getOpcode()) {
9540   default: break;
9541   case ARMISD::CMOV: {
9542     // Bits are known zero/one if known on the LHS and RHS.
9543     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9544     if (KnownZero == 0 && KnownOne == 0) return;
9545
9546     APInt KnownZeroRHS, KnownOneRHS;
9547     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9548     KnownZero &= KnownZeroRHS;
9549     KnownOne  &= KnownOneRHS;
9550     return;
9551   }
9552   }
9553 }
9554
9555 //===----------------------------------------------------------------------===//
9556 //                           ARM Inline Assembly Support
9557 //===----------------------------------------------------------------------===//
9558
9559 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9560   // Looking for "rev" which is V6+.
9561   if (!Subtarget->hasV6Ops())
9562     return false;
9563
9564   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9565   std::string AsmStr = IA->getAsmString();
9566   SmallVector<StringRef, 4> AsmPieces;
9567   SplitString(AsmStr, AsmPieces, ";\n");
9568
9569   switch (AsmPieces.size()) {
9570   default: return false;
9571   case 1:
9572     AsmStr = AsmPieces[0];
9573     AsmPieces.clear();
9574     SplitString(AsmStr, AsmPieces, " \t,");
9575
9576     // rev $0, $1
9577     if (AsmPieces.size() == 3 &&
9578         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9579         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9580       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9581       if (Ty && Ty->getBitWidth() == 32)
9582         return IntrinsicLowering::LowerToByteSwap(CI);
9583     }
9584     break;
9585   }
9586
9587   return false;
9588 }
9589
9590 /// getConstraintType - Given a constraint letter, return the type of
9591 /// constraint it is for this target.
9592 ARMTargetLowering::ConstraintType
9593 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9594   if (Constraint.size() == 1) {
9595     switch (Constraint[0]) {
9596     default:  break;
9597     case 'l': return C_RegisterClass;
9598     case 'w': return C_RegisterClass;
9599     case 'h': return C_RegisterClass;
9600     case 'x': return C_RegisterClass;
9601     case 't': return C_RegisterClass;
9602     case 'j': return C_Other; // Constant for movw.
9603       // An address with a single base register. Due to the way we
9604       // currently handle addresses it is the same as an 'r' memory constraint.
9605     case 'Q': return C_Memory;
9606     }
9607   } else if (Constraint.size() == 2) {
9608     switch (Constraint[0]) {
9609     default: break;
9610     // All 'U+' constraints are addresses.
9611     case 'U': return C_Memory;
9612     }
9613   }
9614   return TargetLowering::getConstraintType(Constraint);
9615 }
9616
9617 /// Examine constraint type and operand type and determine a weight value.
9618 /// This object must already have been set up with the operand type
9619 /// and the current alternative constraint selected.
9620 TargetLowering::ConstraintWeight
9621 ARMTargetLowering::getSingleConstraintMatchWeight(
9622     AsmOperandInfo &info, const char *constraint) const {
9623   ConstraintWeight weight = CW_Invalid;
9624   Value *CallOperandVal = info.CallOperandVal;
9625     // If we don't have a value, we can't do a match,
9626     // but allow it at the lowest weight.
9627   if (CallOperandVal == NULL)
9628     return CW_Default;
9629   Type *type = CallOperandVal->getType();
9630   // Look at the constraint type.
9631   switch (*constraint) {
9632   default:
9633     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9634     break;
9635   case 'l':
9636     if (type->isIntegerTy()) {
9637       if (Subtarget->isThumb())
9638         weight = CW_SpecificReg;
9639       else
9640         weight = CW_Register;
9641     }
9642     break;
9643   case 'w':
9644     if (type->isFloatingPointTy())
9645       weight = CW_Register;
9646     break;
9647   }
9648   return weight;
9649 }
9650
9651 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9652 RCPair
9653 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9654                                                 EVT VT) const {
9655   if (Constraint.size() == 1) {
9656     // GCC ARM Constraint Letters
9657     switch (Constraint[0]) {
9658     case 'l': // Low regs or general regs.
9659       if (Subtarget->isThumb())
9660         return RCPair(0U, &ARM::tGPRRegClass);
9661       return RCPair(0U, &ARM::GPRRegClass);
9662     case 'h': // High regs or no regs.
9663       if (Subtarget->isThumb())
9664         return RCPair(0U, &ARM::hGPRRegClass);
9665       break;
9666     case 'r':
9667       return RCPair(0U, &ARM::GPRRegClass);
9668     case 'w':
9669       if (VT == MVT::f32)
9670         return RCPair(0U, &ARM::SPRRegClass);
9671       if (VT.getSizeInBits() == 64)
9672         return RCPair(0U, &ARM::DPRRegClass);
9673       if (VT.getSizeInBits() == 128)
9674         return RCPair(0U, &ARM::QPRRegClass);
9675       break;
9676     case 'x':
9677       if (VT == MVT::f32)
9678         return RCPair(0U, &ARM::SPR_8RegClass);
9679       if (VT.getSizeInBits() == 64)
9680         return RCPair(0U, &ARM::DPR_8RegClass);
9681       if (VT.getSizeInBits() == 128)
9682         return RCPair(0U, &ARM::QPR_8RegClass);
9683       break;
9684     case 't':
9685       if (VT == MVT::f32)
9686         return RCPair(0U, &ARM::SPRRegClass);
9687       break;
9688     }
9689   }
9690   if (StringRef("{cc}").equals_lower(Constraint))
9691     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9692
9693   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9694 }
9695
9696 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9697 /// vector.  If it is invalid, don't add anything to Ops.
9698 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9699                                                      std::string &Constraint,
9700                                                      std::vector<SDValue>&Ops,
9701                                                      SelectionDAG &DAG) const {
9702   SDValue Result(0, 0);
9703
9704   // Currently only support length 1 constraints.
9705   if (Constraint.length() != 1) return;
9706
9707   char ConstraintLetter = Constraint[0];
9708   switch (ConstraintLetter) {
9709   default: break;
9710   case 'j':
9711   case 'I': case 'J': case 'K': case 'L':
9712   case 'M': case 'N': case 'O':
9713     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9714     if (!C)
9715       return;
9716
9717     int64_t CVal64 = C->getSExtValue();
9718     int CVal = (int) CVal64;
9719     // None of these constraints allow values larger than 32 bits.  Check
9720     // that the value fits in an int.
9721     if (CVal != CVal64)
9722       return;
9723
9724     switch (ConstraintLetter) {
9725       case 'j':
9726         // Constant suitable for movw, must be between 0 and
9727         // 65535.
9728         if (Subtarget->hasV6T2Ops())
9729           if (CVal >= 0 && CVal <= 65535)
9730             break;
9731         return;
9732       case 'I':
9733         if (Subtarget->isThumb1Only()) {
9734           // This must be a constant between 0 and 255, for ADD
9735           // immediates.
9736           if (CVal >= 0 && CVal <= 255)
9737             break;
9738         } else if (Subtarget->isThumb2()) {
9739           // A constant that can be used as an immediate value in a
9740           // data-processing instruction.
9741           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9742             break;
9743         } else {
9744           // A constant that can be used as an immediate value in a
9745           // data-processing instruction.
9746           if (ARM_AM::getSOImmVal(CVal) != -1)
9747             break;
9748         }
9749         return;
9750
9751       case 'J':
9752         if (Subtarget->isThumb()) {  // FIXME thumb2
9753           // This must be a constant between -255 and -1, for negated ADD
9754           // immediates. This can be used in GCC with an "n" modifier that
9755           // prints the negated value, for use with SUB instructions. It is
9756           // not useful otherwise but is implemented for compatibility.
9757           if (CVal >= -255 && CVal <= -1)
9758             break;
9759         } else {
9760           // This must be a constant between -4095 and 4095. It is not clear
9761           // what this constraint is intended for. Implemented for
9762           // compatibility with GCC.
9763           if (CVal >= -4095 && CVal <= 4095)
9764             break;
9765         }
9766         return;
9767
9768       case 'K':
9769         if (Subtarget->isThumb1Only()) {
9770           // A 32-bit value where only one byte has a nonzero value. Exclude
9771           // zero to match GCC. This constraint is used by GCC internally for
9772           // constants that can be loaded with a move/shift combination.
9773           // It is not useful otherwise but is implemented for compatibility.
9774           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9775             break;
9776         } else if (Subtarget->isThumb2()) {
9777           // A constant whose bitwise inverse can be used as an immediate
9778           // value in a data-processing instruction. This can be used in GCC
9779           // with a "B" modifier that prints the inverted value, for use with
9780           // BIC and MVN instructions. It is not useful otherwise but is
9781           // implemented for compatibility.
9782           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9783             break;
9784         } else {
9785           // A constant whose bitwise inverse can be used as an immediate
9786           // value in a data-processing instruction. This can be used in GCC
9787           // with a "B" modifier that prints the inverted value, for use with
9788           // BIC and MVN instructions. It is not useful otherwise but is
9789           // implemented for compatibility.
9790           if (ARM_AM::getSOImmVal(~CVal) != -1)
9791             break;
9792         }
9793         return;
9794
9795       case 'L':
9796         if (Subtarget->isThumb1Only()) {
9797           // This must be a constant between -7 and 7,
9798           // for 3-operand ADD/SUB immediate instructions.
9799           if (CVal >= -7 && CVal < 7)
9800             break;
9801         } else if (Subtarget->isThumb2()) {
9802           // A constant whose negation can be used as an immediate value in a
9803           // data-processing instruction. This can be used in GCC with an "n"
9804           // modifier that prints the negated value, for use with SUB
9805           // instructions. It is not useful otherwise but is implemented for
9806           // compatibility.
9807           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9808             break;
9809         } else {
9810           // A constant whose negation can be used as an immediate value in a
9811           // data-processing instruction. This can be used in GCC with an "n"
9812           // modifier that prints the negated value, for use with SUB
9813           // instructions. It is not useful otherwise but is implemented for
9814           // compatibility.
9815           if (ARM_AM::getSOImmVal(-CVal) != -1)
9816             break;
9817         }
9818         return;
9819
9820       case 'M':
9821         if (Subtarget->isThumb()) { // FIXME thumb2
9822           // This must be a multiple of 4 between 0 and 1020, for
9823           // ADD sp + immediate.
9824           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9825             break;
9826         } else {
9827           // A power of two or a constant between 0 and 32.  This is used in
9828           // GCC for the shift amount on shifted register operands, but it is
9829           // useful in general for any shift amounts.
9830           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9831             break;
9832         }
9833         return;
9834
9835       case 'N':
9836         if (Subtarget->isThumb()) {  // FIXME thumb2
9837           // This must be a constant between 0 and 31, for shift amounts.
9838           if (CVal >= 0 && CVal <= 31)
9839             break;
9840         }
9841         return;
9842
9843       case 'O':
9844         if (Subtarget->isThumb()) {  // FIXME thumb2
9845           // This must be a multiple of 4 between -508 and 508, for
9846           // ADD/SUB sp = sp + immediate.
9847           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9848             break;
9849         }
9850         return;
9851     }
9852     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9853     break;
9854   }
9855
9856   if (Result.getNode()) {
9857     Ops.push_back(Result);
9858     return;
9859   }
9860   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9861 }
9862
9863 bool
9864 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9865   // The ARM target isn't yet aware of offsets.
9866   return false;
9867 }
9868
9869 bool ARM::isBitFieldInvertedMask(unsigned v) {
9870   if (v == 0xffffffff)
9871     return 0;
9872   // there can be 1's on either or both "outsides", all the "inside"
9873   // bits must be 0's
9874   unsigned int lsb = 0, msb = 31;
9875   while (v & (1 << msb)) --msb;
9876   while (v & (1 << lsb)) ++lsb;
9877   for (unsigned int i = lsb; i <= msb; ++i) {
9878     if (v & (1 << i))
9879       return 0;
9880   }
9881   return 1;
9882 }
9883
9884 /// isFPImmLegal - Returns true if the target can instruction select the
9885 /// specified FP immediate natively. If false, the legalizer will
9886 /// materialize the FP immediate as a load from a constant pool.
9887 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9888   if (!Subtarget->hasVFP3())
9889     return false;
9890   if (VT == MVT::f32)
9891     return ARM_AM::getFP32Imm(Imm) != -1;
9892   if (VT == MVT::f64)
9893     return ARM_AM::getFP64Imm(Imm) != -1;
9894   return false;
9895 }
9896
9897 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9898 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9899 /// specified in the intrinsic calls.
9900 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9901                                            const CallInst &I,
9902                                            unsigned Intrinsic) const {
9903   switch (Intrinsic) {
9904   case Intrinsic::arm_neon_vld1:
9905   case Intrinsic::arm_neon_vld2:
9906   case Intrinsic::arm_neon_vld3:
9907   case Intrinsic::arm_neon_vld4:
9908   case Intrinsic::arm_neon_vld2lane:
9909   case Intrinsic::arm_neon_vld3lane:
9910   case Intrinsic::arm_neon_vld4lane: {
9911     Info.opc = ISD::INTRINSIC_W_CHAIN;
9912     // Conservatively set memVT to the entire set of vectors loaded.
9913     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
9914     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9915     Info.ptrVal = I.getArgOperand(0);
9916     Info.offset = 0;
9917     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9918     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9919     Info.vol = false; // volatile loads with NEON intrinsics not supported
9920     Info.readMem = true;
9921     Info.writeMem = false;
9922     return true;
9923   }
9924   case Intrinsic::arm_neon_vst1:
9925   case Intrinsic::arm_neon_vst2:
9926   case Intrinsic::arm_neon_vst3:
9927   case Intrinsic::arm_neon_vst4:
9928   case Intrinsic::arm_neon_vst2lane:
9929   case Intrinsic::arm_neon_vst3lane:
9930   case Intrinsic::arm_neon_vst4lane: {
9931     Info.opc = ISD::INTRINSIC_VOID;
9932     // Conservatively set memVT to the entire set of vectors stored.
9933     unsigned NumElts = 0;
9934     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9935       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9936       if (!ArgTy->isVectorTy())
9937         break;
9938       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
9939     }
9940     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9941     Info.ptrVal = I.getArgOperand(0);
9942     Info.offset = 0;
9943     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9944     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9945     Info.vol = false; // volatile stores with NEON intrinsics not supported
9946     Info.readMem = false;
9947     Info.writeMem = true;
9948     return true;
9949   }
9950   case Intrinsic::arm_strexd: {
9951     Info.opc = ISD::INTRINSIC_W_CHAIN;
9952     Info.memVT = MVT::i64;
9953     Info.ptrVal = I.getArgOperand(2);
9954     Info.offset = 0;
9955     Info.align = 8;
9956     Info.vol = true;
9957     Info.readMem = false;
9958     Info.writeMem = true;
9959     return true;
9960   }
9961   case Intrinsic::arm_ldrexd: {
9962     Info.opc = ISD::INTRINSIC_W_CHAIN;
9963     Info.memVT = MVT::i64;
9964     Info.ptrVal = I.getArgOperand(0);
9965     Info.offset = 0;
9966     Info.align = 8;
9967     Info.vol = true;
9968     Info.readMem = true;
9969     Info.writeMem = false;
9970     return true;
9971   }
9972   default:
9973     break;
9974   }
9975
9976   return false;
9977 }