Remove the old CodePlacementOpt pass.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
508
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Mark v2f32 intrinsics.
526     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
541
542     // Neon does not support some operations on v1i64 and v2i64 types.
543     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544     // Custom handling for some quad-vector types to detect VMULL.
545     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548     // Custom handling for some vector types to avoid expensive expansions
549     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556     // a destination type that is wider than the source, and nor does
557     // it have a FP_TO_[SU]INT instruction with a narrower destination than
558     // source.
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
563
564     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
565     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
566
567     // Custom expand long extensions to vectors.
568     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
569     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
571     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
575     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
576
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585     // NEON only has FMA instructions as of VFP4.
586     if (!Subtarget->hasVFP4()) {
587       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
589     }
590
591     setTargetDAGCombine(ISD::INTRINSIC_VOID);
592     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594     setTargetDAGCombine(ISD::SHL);
595     setTargetDAGCombine(ISD::SRL);
596     setTargetDAGCombine(ISD::SRA);
597     setTargetDAGCombine(ISD::SIGN_EXTEND);
598     setTargetDAGCombine(ISD::ZERO_EXTEND);
599     setTargetDAGCombine(ISD::ANY_EXTEND);
600     setTargetDAGCombine(ISD::SELECT_CC);
601     setTargetDAGCombine(ISD::BUILD_VECTOR);
602     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604     setTargetDAGCombine(ISD::STORE);
605     setTargetDAGCombine(ISD::FP_TO_SINT);
606     setTargetDAGCombine(ISD::FP_TO_UINT);
607     setTargetDAGCombine(ISD::FDIV);
608
609     // It is legal to extload from v4i8 to v4i16 or v4i32.
610     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611                   MVT::v4i16, MVT::v2i16,
612                   MVT::v2i32};
613     for (unsigned i = 0; i < 6; ++i) {
614       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
617     }
618   }
619
620   // ARM and Thumb2 support UMLAL/SMLAL.
621   if (!Subtarget->isThumb1Only())
622     setTargetDAGCombine(ISD::ADDC);
623
624
625   computeRegisterProperties();
626
627   // ARM does not have f32 extending load.
628   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
629
630   // ARM does not have i1 sign extending load.
631   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
632
633   // ARM supports all 4 flavors of integer indexed load / store.
634   if (!Subtarget->isThumb1Only()) {
635     for (unsigned im = (unsigned)ISD::PRE_INC;
636          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637       setIndexedLoadAction(im,  MVT::i1,  Legal);
638       setIndexedLoadAction(im,  MVT::i8,  Legal);
639       setIndexedLoadAction(im,  MVT::i16, Legal);
640       setIndexedLoadAction(im,  MVT::i32, Legal);
641       setIndexedStoreAction(im, MVT::i1,  Legal);
642       setIndexedStoreAction(im, MVT::i8,  Legal);
643       setIndexedStoreAction(im, MVT::i16, Legal);
644       setIndexedStoreAction(im, MVT::i32, Legal);
645     }
646   }
647
648   // i64 operation support.
649   setOperationAction(ISD::MUL,     MVT::i64, Expand);
650   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
651   if (Subtarget->isThumb1Only()) {
652     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
654   }
655   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657     setOperationAction(ISD::MULHS, MVT::i32, Expand);
658
659   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL,       MVT::i64, Custom);
663   setOperationAction(ISD::SRA,       MVT::i64, Custom);
664
665   if (!Subtarget->isThumb1Only()) {
666     // FIXME: We should do this for Thumb1 as well.
667     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
668     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
669     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
671   }
672
673   // ARM does not have ROTL.
674   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
675   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
676   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
679
680   // These just redirect to CTTZ and CTLZ on ARM.
681   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
682   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
683
684   // Only ARMv6 has BSWAP.
685   if (!Subtarget->hasV6Ops())
686     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
687
688   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
689       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
690     // These are expanded into libcalls if the cpu doesn't have HW divider.
691     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
692     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
693   }
694   setOperationAction(ISD::SREM,  MVT::i32, Expand);
695   setOperationAction(ISD::UREM,  MVT::i32, Expand);
696   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
697   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
698
699   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
700   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
701   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
702   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
703   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
704
705   setOperationAction(ISD::TRAP, MVT::Other, Legal);
706
707   // Use the default implementation.
708   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
709   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
710   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
711   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
712   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
713   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
714
715   if (!Subtarget->isTargetDarwin()) {
716     // Non-Darwin platforms may return values in these registers via the
717     // personality function.
718     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
719     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
720     setExceptionPointerRegister(ARM::R0);
721     setExceptionSelectorRegister(ARM::R1);
722   }
723
724   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
725   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
726   // the default expansion.
727   // FIXME: This should be checking for v6k, not just v6.
728   if (Subtarget->hasDataBarrier() ||
729       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
730     // membarrier needs custom lowering; the rest are legal and handled
731     // normally.
732     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
733     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
734     // Custom lowering for 64-bit ops
735     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
736     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
737     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
738     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
739     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
740     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
741     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
742     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
743     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
744     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
745     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
746     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
747     setInsertFencesForAtomic(true);
748   } else {
749     // Set them all for expansion, which will force libcalls.
750     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
751     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
752     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
755     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
756     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
757     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
758     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
759     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
762     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
763     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
764     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
765     // Unordered/Monotonic case.
766     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
767     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
768     // Since the libcalls include locking, fold in the fences
769     setShouldFoldAtomicFences(true);
770   }
771
772   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
773
774   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
775   if (!Subtarget->hasV6Ops()) {
776     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
777     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
778   }
779   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
780
781   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
782       !Subtarget->isThumb1Only()) {
783     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
784     // iff target supports vfp2.
785     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
786     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
787   }
788
789   // We want to custom lower some of our intrinsics.
790   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
791   if (Subtarget->isTargetDarwin()) {
792     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
793     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
794     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
795   }
796
797   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
798   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
799   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
800   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
801   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
802   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
803   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
804   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
805   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
806
807   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
808   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
809   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
810   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
811   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
812
813   // We don't support sin/cos/fmod/copysign/pow
814   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
815   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
816   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
817   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
818   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
819   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
820   setOperationAction(ISD::FREM,      MVT::f64, Expand);
821   setOperationAction(ISD::FREM,      MVT::f32, Expand);
822   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
823       !Subtarget->isThumb1Only()) {
824     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
825     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
826   }
827   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
828   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
829
830   if (!Subtarget->hasVFP4()) {
831     setOperationAction(ISD::FMA, MVT::f64, Expand);
832     setOperationAction(ISD::FMA, MVT::f32, Expand);
833   }
834
835   // Various VFP goodness
836   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
837     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
838     if (Subtarget->hasVFP2()) {
839       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
840       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
841       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
842       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
843     }
844     // Special handling for half-precision FP.
845     if (!Subtarget->hasFP16()) {
846       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
847       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
848     }
849   }
850
851   // We have target-specific dag combine patterns for the following nodes:
852   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
853   setTargetDAGCombine(ISD::ADD);
854   setTargetDAGCombine(ISD::SUB);
855   setTargetDAGCombine(ISD::MUL);
856   setTargetDAGCombine(ISD::AND);
857   setTargetDAGCombine(ISD::OR);
858   setTargetDAGCombine(ISD::XOR);
859
860   if (Subtarget->hasV6Ops())
861     setTargetDAGCombine(ISD::SRL);
862
863   setStackPointerRegisterToSaveRestore(ARM::SP);
864
865   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
866       !Subtarget->hasVFP2())
867     setSchedulingPreference(Sched::RegPressure);
868   else
869     setSchedulingPreference(Sched::Hybrid);
870
871   //// temporary - rewrite interface to use type
872   MaxStoresPerMemset = 8;
873   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
874   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
875   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
876   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
877   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
878
879   // On ARM arguments smaller than 4 bytes are extended, so all arguments
880   // are at least 4 bytes aligned.
881   setMinStackArgumentAlignment(4);
882
883   // Prefer likely predicted branches to selects on out-of-order cores.
884   PredictableSelectIsExpensive = Subtarget->isLikeA9();
885
886   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
887 }
888
889 // FIXME: It might make sense to define the representative register class as the
890 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
891 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
892 // SPR's representative would be DPR_VFP2. This should work well if register
893 // pressure tracking were modified such that a register use would increment the
894 // pressure of the register class's representative and all of it's super
895 // classes' representatives transitively. We have not implemented this because
896 // of the difficulty prior to coalescing of modeling operand register classes
897 // due to the common occurrence of cross class copies and subregister insertions
898 // and extractions.
899 std::pair<const TargetRegisterClass*, uint8_t>
900 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
901   const TargetRegisterClass *RRC = 0;
902   uint8_t Cost = 1;
903   switch (VT.SimpleTy) {
904   default:
905     return TargetLowering::findRepresentativeClass(VT);
906   // Use DPR as representative register class for all floating point
907   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
908   // the cost is 1 for both f32 and f64.
909   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
910   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
911     RRC = &ARM::DPRRegClass;
912     // When NEON is used for SP, only half of the register file is available
913     // because operations that define both SP and DP results will be constrained
914     // to the VFP2 class (D0-D15). We currently model this constraint prior to
915     // coalescing by double-counting the SP regs. See the FIXME above.
916     if (Subtarget->useNEONForSinglePrecisionFP())
917       Cost = 2;
918     break;
919   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
920   case MVT::v4f32: case MVT::v2f64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 2;
923     break;
924   case MVT::v4i64:
925     RRC = &ARM::DPRRegClass;
926     Cost = 4;
927     break;
928   case MVT::v8i64:
929     RRC = &ARM::DPRRegClass;
930     Cost = 8;
931     break;
932   }
933   return std::make_pair(RRC, Cost);
934 }
935
936 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
937   switch (Opcode) {
938   default: return 0;
939   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
940   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
941   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
942   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
943   case ARMISD::CALL:          return "ARMISD::CALL";
944   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
945   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
946   case ARMISD::tCALL:         return "ARMISD::tCALL";
947   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
948   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
949   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
950   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
951   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
952   case ARMISD::CMP:           return "ARMISD::CMP";
953   case ARMISD::CMN:           return "ARMISD::CMN";
954   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
955   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
956   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
957   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
958   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
959
960   case ARMISD::CMOV:          return "ARMISD::CMOV";
961
962   case ARMISD::RBIT:          return "ARMISD::RBIT";
963
964   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
965   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
966   case ARMISD::SITOF:         return "ARMISD::SITOF";
967   case ARMISD::UITOF:         return "ARMISD::UITOF";
968
969   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
970   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
971   case ARMISD::RRX:           return "ARMISD::RRX";
972
973   case ARMISD::ADDC:          return "ARMISD::ADDC";
974   case ARMISD::ADDE:          return "ARMISD::ADDE";
975   case ARMISD::SUBC:          return "ARMISD::SUBC";
976   case ARMISD::SUBE:          return "ARMISD::SUBE";
977
978   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
979   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
980
981   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
982   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
983
984   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
985
986   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
987
988   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
989
990   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
991   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
992
993   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
994
995   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
996   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
997   case ARMISD::VCGE:          return "ARMISD::VCGE";
998   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
999   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1000   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1001   case ARMISD::VCGT:          return "ARMISD::VCGT";
1002   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1003   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1004   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1005   case ARMISD::VTST:          return "ARMISD::VTST";
1006
1007   case ARMISD::VSHL:          return "ARMISD::VSHL";
1008   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1009   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1010   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1011   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1012   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1013   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1014   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1015   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1016   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1017   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1018   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1019   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1020   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1021   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1022   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1023   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1024   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1025   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1026   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1027   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1028   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1029   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1030   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1031   case ARMISD::VDUP:          return "ARMISD::VDUP";
1032   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1033   case ARMISD::VEXT:          return "ARMISD::VEXT";
1034   case ARMISD::VREV64:        return "ARMISD::VREV64";
1035   case ARMISD::VREV32:        return "ARMISD::VREV32";
1036   case ARMISD::VREV16:        return "ARMISD::VREV16";
1037   case ARMISD::VZIP:          return "ARMISD::VZIP";
1038   case ARMISD::VUZP:          return "ARMISD::VUZP";
1039   case ARMISD::VTRN:          return "ARMISD::VTRN";
1040   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1041   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1042   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1043   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1044   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1045   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1046   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1047   case ARMISD::FMAX:          return "ARMISD::FMAX";
1048   case ARMISD::FMIN:          return "ARMISD::FMIN";
1049   case ARMISD::BFI:           return "ARMISD::BFI";
1050   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1051   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1052   case ARMISD::VBSL:          return "ARMISD::VBSL";
1053   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1054   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1055   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1056   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1057   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1058   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1059   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1060   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1061   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1062   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1063   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1064   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1065   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1066   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1067   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1068   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1069   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1070   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1071   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1072   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1073   }
1074 }
1075
1076 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1077   if (!VT.isVector()) return getPointerTy();
1078   return VT.changeVectorElementTypeToInteger();
1079 }
1080
1081 /// getRegClassFor - Return the register class that should be used for the
1082 /// specified value type.
1083 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1084   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1085   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1086   // load / store 4 to 8 consecutive D registers.
1087   if (Subtarget->hasNEON()) {
1088     if (VT == MVT::v4i64)
1089       return &ARM::QQPRRegClass;
1090     if (VT == MVT::v8i64)
1091       return &ARM::QQQQPRRegClass;
1092   }
1093   return TargetLowering::getRegClassFor(VT);
1094 }
1095
1096 // Create a fast isel object.
1097 FastISel *
1098 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1099                                   const TargetLibraryInfo *libInfo) const {
1100   return ARM::createFastISel(funcInfo, libInfo);
1101 }
1102
1103 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1104 /// be used for loads / stores from the global.
1105 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1106   return (Subtarget->isThumb1Only() ? 127 : 4095);
1107 }
1108
1109 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1110   unsigned NumVals = N->getNumValues();
1111   if (!NumVals)
1112     return Sched::RegPressure;
1113
1114   for (unsigned i = 0; i != NumVals; ++i) {
1115     EVT VT = N->getValueType(i);
1116     if (VT == MVT::Glue || VT == MVT::Other)
1117       continue;
1118     if (VT.isFloatingPoint() || VT.isVector())
1119       return Sched::ILP;
1120   }
1121
1122   if (!N->isMachineOpcode())
1123     return Sched::RegPressure;
1124
1125   // Load are scheduled for latency even if there instruction itinerary
1126   // is not available.
1127   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1128   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1129
1130   if (MCID.getNumDefs() == 0)
1131     return Sched::RegPressure;
1132   if (!Itins->isEmpty() &&
1133       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1134     return Sched::ILP;
1135
1136   return Sched::RegPressure;
1137 }
1138
1139 //===----------------------------------------------------------------------===//
1140 // Lowering Code
1141 //===----------------------------------------------------------------------===//
1142
1143 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1144 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1145   switch (CC) {
1146   default: llvm_unreachable("Unknown condition code!");
1147   case ISD::SETNE:  return ARMCC::NE;
1148   case ISD::SETEQ:  return ARMCC::EQ;
1149   case ISD::SETGT:  return ARMCC::GT;
1150   case ISD::SETGE:  return ARMCC::GE;
1151   case ISD::SETLT:  return ARMCC::LT;
1152   case ISD::SETLE:  return ARMCC::LE;
1153   case ISD::SETUGT: return ARMCC::HI;
1154   case ISD::SETUGE: return ARMCC::HS;
1155   case ISD::SETULT: return ARMCC::LO;
1156   case ISD::SETULE: return ARMCC::LS;
1157   }
1158 }
1159
1160 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1161 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1162                         ARMCC::CondCodes &CondCode2) {
1163   CondCode2 = ARMCC::AL;
1164   switch (CC) {
1165   default: llvm_unreachable("Unknown FP condition!");
1166   case ISD::SETEQ:
1167   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1168   case ISD::SETGT:
1169   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1170   case ISD::SETGE:
1171   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1172   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1173   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1174   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1175   case ISD::SETO:   CondCode = ARMCC::VC; break;
1176   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1177   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1178   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1179   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1180   case ISD::SETLT:
1181   case ISD::SETULT: CondCode = ARMCC::LT; break;
1182   case ISD::SETLE:
1183   case ISD::SETULE: CondCode = ARMCC::LE; break;
1184   case ISD::SETNE:
1185   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1186   }
1187 }
1188
1189 //===----------------------------------------------------------------------===//
1190 //                      Calling Convention Implementation
1191 //===----------------------------------------------------------------------===//
1192
1193 #include "ARMGenCallingConv.inc"
1194
1195 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1196 /// given CallingConvention value.
1197 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1198                                                  bool Return,
1199                                                  bool isVarArg) const {
1200   switch (CC) {
1201   default:
1202     llvm_unreachable("Unsupported calling convention");
1203   case CallingConv::Fast:
1204     if (Subtarget->hasVFP2() && !isVarArg) {
1205       if (!Subtarget->isAAPCS_ABI())
1206         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1207       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1208       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1209     }
1210     // Fallthrough
1211   case CallingConv::C: {
1212     // Use target triple & subtarget features to do actual dispatch.
1213     if (!Subtarget->isAAPCS_ABI())
1214       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1215     else if (Subtarget->hasVFP2() &&
1216              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1217              !isVarArg)
1218       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1219     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1220   }
1221   case CallingConv::ARM_AAPCS_VFP:
1222     if (!isVarArg)
1223       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1224     // Fallthrough
1225   case CallingConv::ARM_AAPCS:
1226     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1227   case CallingConv::ARM_APCS:
1228     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1229   case CallingConv::GHC:
1230     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1231   }
1232 }
1233
1234 /// LowerCallResult - Lower the result values of a call into the
1235 /// appropriate copies out of appropriate physical registers.
1236 SDValue
1237 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1238                                    CallingConv::ID CallConv, bool isVarArg,
1239                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1240                                    DebugLoc dl, SelectionDAG &DAG,
1241                                    SmallVectorImpl<SDValue> &InVals) const {
1242
1243   // Assign locations to each value returned by this call.
1244   SmallVector<CCValAssign, 16> RVLocs;
1245   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1246                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1247   CCInfo.AnalyzeCallResult(Ins,
1248                            CCAssignFnForNode(CallConv, /* Return*/ true,
1249                                              isVarArg));
1250
1251   // Copy all of the result registers out of their specified physreg.
1252   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1253     CCValAssign VA = RVLocs[i];
1254
1255     SDValue Val;
1256     if (VA.needsCustom()) {
1257       // Handle f64 or half of a v2f64.
1258       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1259                                       InFlag);
1260       Chain = Lo.getValue(1);
1261       InFlag = Lo.getValue(2);
1262       VA = RVLocs[++i]; // skip ahead to next loc
1263       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1264                                       InFlag);
1265       Chain = Hi.getValue(1);
1266       InFlag = Hi.getValue(2);
1267       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1268
1269       if (VA.getLocVT() == MVT::v2f64) {
1270         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1271         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1272                           DAG.getConstant(0, MVT::i32));
1273
1274         VA = RVLocs[++i]; // skip ahead to next loc
1275         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1276         Chain = Lo.getValue(1);
1277         InFlag = Lo.getValue(2);
1278         VA = RVLocs[++i]; // skip ahead to next loc
1279         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1280         Chain = Hi.getValue(1);
1281         InFlag = Hi.getValue(2);
1282         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1283         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1284                           DAG.getConstant(1, MVT::i32));
1285       }
1286     } else {
1287       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1288                                InFlag);
1289       Chain = Val.getValue(1);
1290       InFlag = Val.getValue(2);
1291     }
1292
1293     switch (VA.getLocInfo()) {
1294     default: llvm_unreachable("Unknown loc info!");
1295     case CCValAssign::Full: break;
1296     case CCValAssign::BCvt:
1297       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1298       break;
1299     }
1300
1301     InVals.push_back(Val);
1302   }
1303
1304   return Chain;
1305 }
1306
1307 /// LowerMemOpCallTo - Store the argument to the stack.
1308 SDValue
1309 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1310                                     SDValue StackPtr, SDValue Arg,
1311                                     DebugLoc dl, SelectionDAG &DAG,
1312                                     const CCValAssign &VA,
1313                                     ISD::ArgFlagsTy Flags) const {
1314   unsigned LocMemOffset = VA.getLocMemOffset();
1315   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1316   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1317   return DAG.getStore(Chain, dl, Arg, PtrOff,
1318                       MachinePointerInfo::getStack(LocMemOffset),
1319                       false, false, 0);
1320 }
1321
1322 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1323                                          SDValue Chain, SDValue &Arg,
1324                                          RegsToPassVector &RegsToPass,
1325                                          CCValAssign &VA, CCValAssign &NextVA,
1326                                          SDValue &StackPtr,
1327                                          SmallVector<SDValue, 8> &MemOpChains,
1328                                          ISD::ArgFlagsTy Flags) const {
1329
1330   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1331                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1332   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1333
1334   if (NextVA.isRegLoc())
1335     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1336   else {
1337     assert(NextVA.isMemLoc());
1338     if (StackPtr.getNode() == 0)
1339       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1340
1341     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1342                                            dl, DAG, NextVA,
1343                                            Flags));
1344   }
1345 }
1346
1347 /// LowerCall - Lowering a call into a callseq_start <-
1348 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1349 /// nodes.
1350 SDValue
1351 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1352                              SmallVectorImpl<SDValue> &InVals) const {
1353   SelectionDAG &DAG                     = CLI.DAG;
1354   DebugLoc &dl                          = CLI.DL;
1355   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1356   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1357   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1358   SDValue Chain                         = CLI.Chain;
1359   SDValue Callee                        = CLI.Callee;
1360   bool &isTailCall                      = CLI.IsTailCall;
1361   CallingConv::ID CallConv              = CLI.CallConv;
1362   bool doesNotRet                       = CLI.DoesNotReturn;
1363   bool isVarArg                         = CLI.IsVarArg;
1364
1365   MachineFunction &MF = DAG.getMachineFunction();
1366   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1367   bool IsSibCall = false;
1368   // Disable tail calls if they're not supported.
1369   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1370     isTailCall = false;
1371   if (isTailCall) {
1372     // Check if it's really possible to do a tail call.
1373     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1374                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1375                                                    Outs, OutVals, Ins, DAG);
1376     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1377     // detected sibcalls.
1378     if (isTailCall) {
1379       ++NumTailCalls;
1380       IsSibCall = true;
1381     }
1382   }
1383
1384   // Analyze operands of the call, assigning locations to each operand.
1385   SmallVector<CCValAssign, 16> ArgLocs;
1386   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1387                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1388   CCInfo.AnalyzeCallOperands(Outs,
1389                              CCAssignFnForNode(CallConv, /* Return*/ false,
1390                                                isVarArg));
1391
1392   // Get a count of how many bytes are to be pushed on the stack.
1393   unsigned NumBytes = CCInfo.getNextStackOffset();
1394
1395   // For tail calls, memory operands are available in our caller's stack.
1396   if (IsSibCall)
1397     NumBytes = 0;
1398
1399   // Adjust the stack pointer for the new arguments...
1400   // These operations are automatically eliminated by the prolog/epilog pass
1401   if (!IsSibCall)
1402     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1403
1404   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1405
1406   RegsToPassVector RegsToPass;
1407   SmallVector<SDValue, 8> MemOpChains;
1408
1409   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1410   // of tail call optimization, arguments are handled later.
1411   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1412        i != e;
1413        ++i, ++realArgIdx) {
1414     CCValAssign &VA = ArgLocs[i];
1415     SDValue Arg = OutVals[realArgIdx];
1416     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1417     bool isByVal = Flags.isByVal();
1418
1419     // Promote the value if needed.
1420     switch (VA.getLocInfo()) {
1421     default: llvm_unreachable("Unknown loc info!");
1422     case CCValAssign::Full: break;
1423     case CCValAssign::SExt:
1424       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1425       break;
1426     case CCValAssign::ZExt:
1427       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1428       break;
1429     case CCValAssign::AExt:
1430       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1431       break;
1432     case CCValAssign::BCvt:
1433       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1434       break;
1435     }
1436
1437     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1438     if (VA.needsCustom()) {
1439       if (VA.getLocVT() == MVT::v2f64) {
1440         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1441                                   DAG.getConstant(0, MVT::i32));
1442         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1443                                   DAG.getConstant(1, MVT::i32));
1444
1445         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1446                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1447
1448         VA = ArgLocs[++i]; // skip ahead to next loc
1449         if (VA.isRegLoc()) {
1450           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1451                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1452         } else {
1453           assert(VA.isMemLoc());
1454
1455           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1456                                                  dl, DAG, VA, Flags));
1457         }
1458       } else {
1459         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1460                          StackPtr, MemOpChains, Flags);
1461       }
1462     } else if (VA.isRegLoc()) {
1463       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1464     } else if (isByVal) {
1465       assert(VA.isMemLoc());
1466       unsigned offset = 0;
1467
1468       // True if this byval aggregate will be split between registers
1469       // and memory.
1470       if (CCInfo.isFirstByValRegValid()) {
1471         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1472         unsigned int i, j;
1473         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1474           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1475           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1476           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1477                                      MachinePointerInfo(),
1478                                      false, false, false, 0);
1479           MemOpChains.push_back(Load.getValue(1));
1480           RegsToPass.push_back(std::make_pair(j, Load));
1481         }
1482         offset = ARM::R4 - CCInfo.getFirstByValReg();
1483         CCInfo.clearFirstByValReg();
1484       }
1485
1486       if (Flags.getByValSize() - 4*offset > 0) {
1487         unsigned LocMemOffset = VA.getLocMemOffset();
1488         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1489         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1490                                   StkPtrOff);
1491         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1492         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1493         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1494                                            MVT::i32);
1495         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1496
1497         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1498         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1499         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1500                                           Ops, array_lengthof(Ops)));
1501       }
1502     } else if (!IsSibCall) {
1503       assert(VA.isMemLoc());
1504
1505       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1506                                              dl, DAG, VA, Flags));
1507     }
1508   }
1509
1510   if (!MemOpChains.empty())
1511     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1512                         &MemOpChains[0], MemOpChains.size());
1513
1514   // Build a sequence of copy-to-reg nodes chained together with token chain
1515   // and flag operands which copy the outgoing args into the appropriate regs.
1516   SDValue InFlag;
1517   // Tail call byval lowering might overwrite argument registers so in case of
1518   // tail call optimization the copies to registers are lowered later.
1519   if (!isTailCall)
1520     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1521       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1522                                RegsToPass[i].second, InFlag);
1523       InFlag = Chain.getValue(1);
1524     }
1525
1526   // For tail calls lower the arguments to the 'real' stack slot.
1527   if (isTailCall) {
1528     // Force all the incoming stack arguments to be loaded from the stack
1529     // before any new outgoing arguments are stored to the stack, because the
1530     // outgoing stack slots may alias the incoming argument stack slots, and
1531     // the alias isn't otherwise explicit. This is slightly more conservative
1532     // than necessary, because it means that each store effectively depends
1533     // on every argument instead of just those arguments it would clobber.
1534
1535     // Do not flag preceding copytoreg stuff together with the following stuff.
1536     InFlag = SDValue();
1537     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1538       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1539                                RegsToPass[i].second, InFlag);
1540       InFlag = Chain.getValue(1);
1541     }
1542     InFlag =SDValue();
1543   }
1544
1545   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1546   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1547   // node so that legalize doesn't hack it.
1548   bool isDirect = false;
1549   bool isARMFunc = false;
1550   bool isLocalARMFunc = false;
1551   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1552
1553   if (EnableARMLongCalls) {
1554     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1555             && "long-calls with non-static relocation model!");
1556     // Handle a global address or an external symbol. If it's not one of
1557     // those, the target's already in a register, so we don't need to do
1558     // anything extra.
1559     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1560       const GlobalValue *GV = G->getGlobal();
1561       // Create a constant pool entry for the callee address
1562       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1563       ARMConstantPoolValue *CPV =
1564         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1565
1566       // Get the address of the callee into a register
1567       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1568       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1569       Callee = DAG.getLoad(getPointerTy(), dl,
1570                            DAG.getEntryNode(), CPAddr,
1571                            MachinePointerInfo::getConstantPool(),
1572                            false, false, false, 0);
1573     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1574       const char *Sym = S->getSymbol();
1575
1576       // Create a constant pool entry for the callee address
1577       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1578       ARMConstantPoolValue *CPV =
1579         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1580                                       ARMPCLabelIndex, 0);
1581       // Get the address of the callee into a register
1582       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1583       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1584       Callee = DAG.getLoad(getPointerTy(), dl,
1585                            DAG.getEntryNode(), CPAddr,
1586                            MachinePointerInfo::getConstantPool(),
1587                            false, false, false, 0);
1588     }
1589   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1590     const GlobalValue *GV = G->getGlobal();
1591     isDirect = true;
1592     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1593     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1594                    getTargetMachine().getRelocationModel() != Reloc::Static;
1595     isARMFunc = !Subtarget->isThumb() || isStub;
1596     // ARM call to a local ARM function is predicable.
1597     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1598     // tBX takes a register source operand.
1599     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1600       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1601       ARMConstantPoolValue *CPV =
1602         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1603       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1604       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1605       Callee = DAG.getLoad(getPointerTy(), dl,
1606                            DAG.getEntryNode(), CPAddr,
1607                            MachinePointerInfo::getConstantPool(),
1608                            false, false, false, 0);
1609       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1610       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1611                            getPointerTy(), Callee, PICLabel);
1612     } else {
1613       // On ELF targets for PIC code, direct calls should go through the PLT
1614       unsigned OpFlags = 0;
1615       if (Subtarget->isTargetELF() &&
1616           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1617         OpFlags = ARMII::MO_PLT;
1618       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1619     }
1620   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1621     isDirect = true;
1622     bool isStub = Subtarget->isTargetDarwin() &&
1623                   getTargetMachine().getRelocationModel() != Reloc::Static;
1624     isARMFunc = !Subtarget->isThumb() || isStub;
1625     // tBX takes a register source operand.
1626     const char *Sym = S->getSymbol();
1627     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1628       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1629       ARMConstantPoolValue *CPV =
1630         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1631                                       ARMPCLabelIndex, 4);
1632       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1633       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1634       Callee = DAG.getLoad(getPointerTy(), dl,
1635                            DAG.getEntryNode(), CPAddr,
1636                            MachinePointerInfo::getConstantPool(),
1637                            false, false, false, 0);
1638       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1639       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1640                            getPointerTy(), Callee, PICLabel);
1641     } else {
1642       unsigned OpFlags = 0;
1643       // On ELF targets for PIC code, direct calls should go through the PLT
1644       if (Subtarget->isTargetELF() &&
1645                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1646         OpFlags = ARMII::MO_PLT;
1647       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1648     }
1649   }
1650
1651   // FIXME: handle tail calls differently.
1652   unsigned CallOpc;
1653   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1654     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1655   if (Subtarget->isThumb()) {
1656     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1657       CallOpc = ARMISD::CALL_NOLINK;
1658     else
1659       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1660   } else {
1661     if (!isDirect && !Subtarget->hasV5TOps())
1662       CallOpc = ARMISD::CALL_NOLINK;
1663     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1664                // Emit regular call when code size is the priority
1665                !HasMinSizeAttr)
1666       // "mov lr, pc; b _foo" to avoid confusing the RSP
1667       CallOpc = ARMISD::CALL_NOLINK;
1668     else
1669       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1670   }
1671
1672   std::vector<SDValue> Ops;
1673   Ops.push_back(Chain);
1674   Ops.push_back(Callee);
1675
1676   // Add argument registers to the end of the list so that they are known live
1677   // into the call.
1678   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1679     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1680                                   RegsToPass[i].second.getValueType()));
1681
1682   // Add a register mask operand representing the call-preserved registers.
1683   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1684   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1685   assert(Mask && "Missing call preserved mask for calling convention");
1686   Ops.push_back(DAG.getRegisterMask(Mask));
1687
1688   if (InFlag.getNode())
1689     Ops.push_back(InFlag);
1690
1691   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1692   if (isTailCall)
1693     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1694
1695   // Returns a chain and a flag for retval copy to use.
1696   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1697   InFlag = Chain.getValue(1);
1698
1699   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1700                              DAG.getIntPtrConstant(0, true), InFlag);
1701   if (!Ins.empty())
1702     InFlag = Chain.getValue(1);
1703
1704   // Handle result values, copying them out of physregs into vregs that we
1705   // return.
1706   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1707                          dl, DAG, InVals);
1708 }
1709
1710 /// HandleByVal - Every parameter *after* a byval parameter is passed
1711 /// on the stack.  Remember the next parameter register to allocate,
1712 /// and then confiscate the rest of the parameter registers to insure
1713 /// this.
1714 void
1715 ARMTargetLowering::HandleByVal(
1716     CCState *State, unsigned &size, unsigned Align) const {
1717   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1718   assert((State->getCallOrPrologue() == Prologue ||
1719           State->getCallOrPrologue() == Call) &&
1720          "unhandled ParmContext");
1721   if ((!State->isFirstByValRegValid()) &&
1722       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1723     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1724       unsigned AlignInRegs = Align / 4;
1725       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1726       for (unsigned i = 0; i < Waste; ++i)
1727         reg = State->AllocateReg(GPRArgRegs, 4);
1728     }
1729     if (reg != 0) {
1730       State->setFirstByValReg(reg);
1731       // At a call site, a byval parameter that is split between
1732       // registers and memory needs its size truncated here.  In a
1733       // function prologue, such byval parameters are reassembled in
1734       // memory, and are not truncated.
1735       if (State->getCallOrPrologue() == Call) {
1736         unsigned excess = 4 * (ARM::R4 - reg);
1737         assert(size >= excess && "expected larger existing stack allocation");
1738         size -= excess;
1739       }
1740     }
1741   }
1742   // Confiscate any remaining parameter registers to preclude their
1743   // assignment to subsequent parameters.
1744   while (State->AllocateReg(GPRArgRegs, 4))
1745     ;
1746 }
1747
1748 /// MatchingStackOffset - Return true if the given stack call argument is
1749 /// already available in the same position (relatively) of the caller's
1750 /// incoming argument stack.
1751 static
1752 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1753                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1754                          const TargetInstrInfo *TII) {
1755   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1756   int FI = INT_MAX;
1757   if (Arg.getOpcode() == ISD::CopyFromReg) {
1758     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1759     if (!TargetRegisterInfo::isVirtualRegister(VR))
1760       return false;
1761     MachineInstr *Def = MRI->getVRegDef(VR);
1762     if (!Def)
1763       return false;
1764     if (!Flags.isByVal()) {
1765       if (!TII->isLoadFromStackSlot(Def, FI))
1766         return false;
1767     } else {
1768       return false;
1769     }
1770   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1771     if (Flags.isByVal())
1772       // ByVal argument is passed in as a pointer but it's now being
1773       // dereferenced. e.g.
1774       // define @foo(%struct.X* %A) {
1775       //   tail call @bar(%struct.X* byval %A)
1776       // }
1777       return false;
1778     SDValue Ptr = Ld->getBasePtr();
1779     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1780     if (!FINode)
1781       return false;
1782     FI = FINode->getIndex();
1783   } else
1784     return false;
1785
1786   assert(FI != INT_MAX);
1787   if (!MFI->isFixedObjectIndex(FI))
1788     return false;
1789   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1790 }
1791
1792 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1793 /// for tail call optimization. Targets which want to do tail call
1794 /// optimization should implement this function.
1795 bool
1796 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1797                                                      CallingConv::ID CalleeCC,
1798                                                      bool isVarArg,
1799                                                      bool isCalleeStructRet,
1800                                                      bool isCallerStructRet,
1801                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1802                                     const SmallVectorImpl<SDValue> &OutVals,
1803                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1804                                                      SelectionDAG& DAG) const {
1805   const Function *CallerF = DAG.getMachineFunction().getFunction();
1806   CallingConv::ID CallerCC = CallerF->getCallingConv();
1807   bool CCMatch = CallerCC == CalleeCC;
1808
1809   // Look for obvious safe cases to perform tail call optimization that do not
1810   // require ABI changes. This is what gcc calls sibcall.
1811
1812   // Do not sibcall optimize vararg calls unless the call site is not passing
1813   // any arguments.
1814   if (isVarArg && !Outs.empty())
1815     return false;
1816
1817   // Also avoid sibcall optimization if either caller or callee uses struct
1818   // return semantics.
1819   if (isCalleeStructRet || isCallerStructRet)
1820     return false;
1821
1822   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1823   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1824   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1825   // support in the assembler and linker to be used. This would need to be
1826   // fixed to fully support tail calls in Thumb1.
1827   //
1828   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1829   // LR.  This means if we need to reload LR, it takes an extra instructions,
1830   // which outweighs the value of the tail call; but here we don't know yet
1831   // whether LR is going to be used.  Probably the right approach is to
1832   // generate the tail call here and turn it back into CALL/RET in
1833   // emitEpilogue if LR is used.
1834
1835   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1836   // but we need to make sure there are enough registers; the only valid
1837   // registers are the 4 used for parameters.  We don't currently do this
1838   // case.
1839   if (Subtarget->isThumb1Only())
1840     return false;
1841
1842   // If the calling conventions do not match, then we'd better make sure the
1843   // results are returned in the same way as what the caller expects.
1844   if (!CCMatch) {
1845     SmallVector<CCValAssign, 16> RVLocs1;
1846     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1847                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1848     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1849
1850     SmallVector<CCValAssign, 16> RVLocs2;
1851     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1852                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1853     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1854
1855     if (RVLocs1.size() != RVLocs2.size())
1856       return false;
1857     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1858       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1859         return false;
1860       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1861         return false;
1862       if (RVLocs1[i].isRegLoc()) {
1863         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1864           return false;
1865       } else {
1866         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1867           return false;
1868       }
1869     }
1870   }
1871
1872   // If Caller's vararg or byval argument has been split between registers and
1873   // stack, do not perform tail call, since part of the argument is in caller's
1874   // local frame.
1875   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1876                                       getInfo<ARMFunctionInfo>();
1877   if (AFI_Caller->getVarArgsRegSaveSize())
1878     return false;
1879
1880   // If the callee takes no arguments then go on to check the results of the
1881   // call.
1882   if (!Outs.empty()) {
1883     // Check if stack adjustment is needed. For now, do not do this if any
1884     // argument is passed on the stack.
1885     SmallVector<CCValAssign, 16> ArgLocs;
1886     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1887                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1888     CCInfo.AnalyzeCallOperands(Outs,
1889                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1890     if (CCInfo.getNextStackOffset()) {
1891       MachineFunction &MF = DAG.getMachineFunction();
1892
1893       // Check if the arguments are already laid out in the right way as
1894       // the caller's fixed stack objects.
1895       MachineFrameInfo *MFI = MF.getFrameInfo();
1896       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1897       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1898       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1899            i != e;
1900            ++i, ++realArgIdx) {
1901         CCValAssign &VA = ArgLocs[i];
1902         EVT RegVT = VA.getLocVT();
1903         SDValue Arg = OutVals[realArgIdx];
1904         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1905         if (VA.getLocInfo() == CCValAssign::Indirect)
1906           return false;
1907         if (VA.needsCustom()) {
1908           // f64 and vector types are split into multiple registers or
1909           // register/stack-slot combinations.  The types will not match
1910           // the registers; give up on memory f64 refs until we figure
1911           // out what to do about this.
1912           if (!VA.isRegLoc())
1913             return false;
1914           if (!ArgLocs[++i].isRegLoc())
1915             return false;
1916           if (RegVT == MVT::v2f64) {
1917             if (!ArgLocs[++i].isRegLoc())
1918               return false;
1919             if (!ArgLocs[++i].isRegLoc())
1920               return false;
1921           }
1922         } else if (!VA.isRegLoc()) {
1923           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1924                                    MFI, MRI, TII))
1925             return false;
1926         }
1927       }
1928     }
1929   }
1930
1931   return true;
1932 }
1933
1934 bool
1935 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1936                                   MachineFunction &MF, bool isVarArg,
1937                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
1938                                   LLVMContext &Context) const {
1939   SmallVector<CCValAssign, 16> RVLocs;
1940   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1941   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1942                                                     isVarArg));
1943 }
1944
1945 SDValue
1946 ARMTargetLowering::LowerReturn(SDValue Chain,
1947                                CallingConv::ID CallConv, bool isVarArg,
1948                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1949                                const SmallVectorImpl<SDValue> &OutVals,
1950                                DebugLoc dl, SelectionDAG &DAG) const {
1951
1952   // CCValAssign - represent the assignment of the return value to a location.
1953   SmallVector<CCValAssign, 16> RVLocs;
1954
1955   // CCState - Info about the registers and stack slots.
1956   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1957                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1958
1959   // Analyze outgoing return values.
1960   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1961                                                isVarArg));
1962
1963   SDValue Flag;
1964   SmallVector<SDValue, 4> RetOps;
1965   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1966
1967   // Copy the result values into the output registers.
1968   for (unsigned i = 0, realRVLocIdx = 0;
1969        i != RVLocs.size();
1970        ++i, ++realRVLocIdx) {
1971     CCValAssign &VA = RVLocs[i];
1972     assert(VA.isRegLoc() && "Can only return in registers!");
1973
1974     SDValue Arg = OutVals[realRVLocIdx];
1975
1976     switch (VA.getLocInfo()) {
1977     default: llvm_unreachable("Unknown loc info!");
1978     case CCValAssign::Full: break;
1979     case CCValAssign::BCvt:
1980       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1981       break;
1982     }
1983
1984     if (VA.needsCustom()) {
1985       if (VA.getLocVT() == MVT::v2f64) {
1986         // Extract the first half and return it in two registers.
1987         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1988                                    DAG.getConstant(0, MVT::i32));
1989         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1990                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1991
1992         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1993         Flag = Chain.getValue(1);
1994         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1995         VA = RVLocs[++i]; // skip ahead to next loc
1996         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1997                                  HalfGPRs.getValue(1), Flag);
1998         Flag = Chain.getValue(1);
1999         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2000         VA = RVLocs[++i]; // skip ahead to next loc
2001
2002         // Extract the 2nd half and fall through to handle it as an f64 value.
2003         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2004                           DAG.getConstant(1, MVT::i32));
2005       }
2006       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2007       // available.
2008       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2009                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2010       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2011       Flag = Chain.getValue(1);
2012       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2013       VA = RVLocs[++i]; // skip ahead to next loc
2014       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2015                                Flag);
2016     } else
2017       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2018
2019     // Guarantee that all emitted copies are
2020     // stuck together, avoiding something bad.
2021     Flag = Chain.getValue(1);
2022     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2023   }
2024
2025   // Update chain and glue.
2026   RetOps[0] = Chain;
2027   if (Flag.getNode())
2028     RetOps.push_back(Flag);
2029
2030   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2031                      RetOps.data(), RetOps.size());
2032 }
2033
2034 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2035   if (N->getNumValues() != 1)
2036     return false;
2037   if (!N->hasNUsesOfValue(1, 0))
2038     return false;
2039
2040   SDValue TCChain = Chain;
2041   SDNode *Copy = *N->use_begin();
2042   if (Copy->getOpcode() == ISD::CopyToReg) {
2043     // If the copy has a glue operand, we conservatively assume it isn't safe to
2044     // perform a tail call.
2045     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2046       return false;
2047     TCChain = Copy->getOperand(0);
2048   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2049     SDNode *VMov = Copy;
2050     // f64 returned in a pair of GPRs.
2051     SmallPtrSet<SDNode*, 2> Copies;
2052     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2053          UI != UE; ++UI) {
2054       if (UI->getOpcode() != ISD::CopyToReg)
2055         return false;
2056       Copies.insert(*UI);
2057     }
2058     if (Copies.size() > 2)
2059       return false;
2060
2061     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2062          UI != UE; ++UI) {
2063       SDValue UseChain = UI->getOperand(0);
2064       if (Copies.count(UseChain.getNode()))
2065         // Second CopyToReg
2066         Copy = *UI;
2067       else
2068         // First CopyToReg
2069         TCChain = UseChain;
2070     }
2071   } else if (Copy->getOpcode() == ISD::BITCAST) {
2072     // f32 returned in a single GPR.
2073     if (!Copy->hasOneUse())
2074       return false;
2075     Copy = *Copy->use_begin();
2076     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2077       return false;
2078     Chain = Copy->getOperand(0);
2079   } else {
2080     return false;
2081   }
2082
2083   bool HasRet = false;
2084   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2085        UI != UE; ++UI) {
2086     if (UI->getOpcode() != ARMISD::RET_FLAG)
2087       return false;
2088     HasRet = true;
2089   }
2090
2091   if (!HasRet)
2092     return false;
2093
2094   Chain = TCChain;
2095   return true;
2096 }
2097
2098 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2099   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2100     return false;
2101
2102   if (!CI->isTailCall())
2103     return false;
2104
2105   return !Subtarget->isThumb1Only();
2106 }
2107
2108 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2109 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2110 // one of the above mentioned nodes. It has to be wrapped because otherwise
2111 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2112 // be used to form addressing mode. These wrapped nodes will be selected
2113 // into MOVi.
2114 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2115   EVT PtrVT = Op.getValueType();
2116   // FIXME there is no actual debug info here
2117   DebugLoc dl = Op.getDebugLoc();
2118   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2119   SDValue Res;
2120   if (CP->isMachineConstantPoolEntry())
2121     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2122                                     CP->getAlignment());
2123   else
2124     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2125                                     CP->getAlignment());
2126   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2127 }
2128
2129 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2130   return MachineJumpTableInfo::EK_Inline;
2131 }
2132
2133 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2134                                              SelectionDAG &DAG) const {
2135   MachineFunction &MF = DAG.getMachineFunction();
2136   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2137   unsigned ARMPCLabelIndex = 0;
2138   DebugLoc DL = Op.getDebugLoc();
2139   EVT PtrVT = getPointerTy();
2140   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2141   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2142   SDValue CPAddr;
2143   if (RelocM == Reloc::Static) {
2144     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2145   } else {
2146     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2147     ARMPCLabelIndex = AFI->createPICLabelUId();
2148     ARMConstantPoolValue *CPV =
2149       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2150                                       ARMCP::CPBlockAddress, PCAdj);
2151     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2152   }
2153   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2154   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2155                                MachinePointerInfo::getConstantPool(),
2156                                false, false, false, 0);
2157   if (RelocM == Reloc::Static)
2158     return Result;
2159   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2160   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2161 }
2162
2163 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2164 SDValue
2165 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2166                                                  SelectionDAG &DAG) const {
2167   DebugLoc dl = GA->getDebugLoc();
2168   EVT PtrVT = getPointerTy();
2169   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2170   MachineFunction &MF = DAG.getMachineFunction();
2171   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2172   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2173   ARMConstantPoolValue *CPV =
2174     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2175                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2176   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2177   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2178   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2179                          MachinePointerInfo::getConstantPool(),
2180                          false, false, false, 0);
2181   SDValue Chain = Argument.getValue(1);
2182
2183   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2184   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2185
2186   // call __tls_get_addr.
2187   ArgListTy Args;
2188   ArgListEntry Entry;
2189   Entry.Node = Argument;
2190   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2191   Args.push_back(Entry);
2192   // FIXME: is there useful debug info available here?
2193   TargetLowering::CallLoweringInfo CLI(Chain,
2194                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2195                 false, false, false, false,
2196                 0, CallingConv::C, /*isTailCall=*/false,
2197                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2198                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2199   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2200   return CallResult.first;
2201 }
2202
2203 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2204 // "local exec" model.
2205 SDValue
2206 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2207                                         SelectionDAG &DAG,
2208                                         TLSModel::Model model) const {
2209   const GlobalValue *GV = GA->getGlobal();
2210   DebugLoc dl = GA->getDebugLoc();
2211   SDValue Offset;
2212   SDValue Chain = DAG.getEntryNode();
2213   EVT PtrVT = getPointerTy();
2214   // Get the Thread Pointer
2215   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2216
2217   if (model == TLSModel::InitialExec) {
2218     MachineFunction &MF = DAG.getMachineFunction();
2219     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2220     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2221     // Initial exec model.
2222     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2223     ARMConstantPoolValue *CPV =
2224       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2225                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2226                                       true);
2227     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2228     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2229     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2230                          MachinePointerInfo::getConstantPool(),
2231                          false, false, false, 0);
2232     Chain = Offset.getValue(1);
2233
2234     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2235     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2236
2237     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2238                          MachinePointerInfo::getConstantPool(),
2239                          false, false, false, 0);
2240   } else {
2241     // local exec model
2242     assert(model == TLSModel::LocalExec);
2243     ARMConstantPoolValue *CPV =
2244       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2245     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2246     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2247     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2248                          MachinePointerInfo::getConstantPool(),
2249                          false, false, false, 0);
2250   }
2251
2252   // The address of the thread local variable is the add of the thread
2253   // pointer with the offset of the variable.
2254   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2255 }
2256
2257 SDValue
2258 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2259   // TODO: implement the "local dynamic" model
2260   assert(Subtarget->isTargetELF() &&
2261          "TLS not implemented for non-ELF targets");
2262   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2263
2264   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2265
2266   switch (model) {
2267     case TLSModel::GeneralDynamic:
2268     case TLSModel::LocalDynamic:
2269       return LowerToTLSGeneralDynamicModel(GA, DAG);
2270     case TLSModel::InitialExec:
2271     case TLSModel::LocalExec:
2272       return LowerToTLSExecModels(GA, DAG, model);
2273   }
2274   llvm_unreachable("bogus TLS model");
2275 }
2276
2277 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2278                                                  SelectionDAG &DAG) const {
2279   EVT PtrVT = getPointerTy();
2280   DebugLoc dl = Op.getDebugLoc();
2281   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2282   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2283     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2284     ARMConstantPoolValue *CPV =
2285       ARMConstantPoolConstant::Create(GV,
2286                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2287     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2288     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2289     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2290                                  CPAddr,
2291                                  MachinePointerInfo::getConstantPool(),
2292                                  false, false, false, 0);
2293     SDValue Chain = Result.getValue(1);
2294     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2295     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2296     if (!UseGOTOFF)
2297       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2298                            MachinePointerInfo::getGOT(),
2299                            false, false, false, 0);
2300     return Result;
2301   }
2302
2303   // If we have T2 ops, we can materialize the address directly via movt/movw
2304   // pair. This is always cheaper.
2305   if (Subtarget->useMovt()) {
2306     ++NumMovwMovt;
2307     // FIXME: Once remat is capable of dealing with instructions with register
2308     // operands, expand this into two nodes.
2309     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2310                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2311   } else {
2312     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2313     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2314     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2315                        MachinePointerInfo::getConstantPool(),
2316                        false, false, false, 0);
2317   }
2318 }
2319
2320 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2321                                                     SelectionDAG &DAG) const {
2322   EVT PtrVT = getPointerTy();
2323   DebugLoc dl = Op.getDebugLoc();
2324   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2325   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2326
2327   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2328   // update ARMFastISel::ARMMaterializeGV.
2329   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2330     ++NumMovwMovt;
2331     // FIXME: Once remat is capable of dealing with instructions with register
2332     // operands, expand this into two nodes.
2333     if (RelocM == Reloc::Static)
2334       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2335                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2336
2337     unsigned Wrapper = (RelocM == Reloc::PIC_)
2338       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2339     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2340                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2341     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2342       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2343                            MachinePointerInfo::getGOT(),
2344                            false, false, false, 0);
2345     return Result;
2346   }
2347
2348   unsigned ARMPCLabelIndex = 0;
2349   SDValue CPAddr;
2350   if (RelocM == Reloc::Static) {
2351     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2352   } else {
2353     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2354     ARMPCLabelIndex = AFI->createPICLabelUId();
2355     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2356     ARMConstantPoolValue *CPV =
2357       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2358                                       PCAdj);
2359     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360   }
2361   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2362
2363   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2364                                MachinePointerInfo::getConstantPool(),
2365                                false, false, false, 0);
2366   SDValue Chain = Result.getValue(1);
2367
2368   if (RelocM == Reloc::PIC_) {
2369     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2370     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2371   }
2372
2373   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2374     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2375                          false, false, false, 0);
2376
2377   return Result;
2378 }
2379
2380 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2381                                                     SelectionDAG &DAG) const {
2382   assert(Subtarget->isTargetELF() &&
2383          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2384   MachineFunction &MF = DAG.getMachineFunction();
2385   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2386   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2387   EVT PtrVT = getPointerTy();
2388   DebugLoc dl = Op.getDebugLoc();
2389   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2390   ARMConstantPoolValue *CPV =
2391     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2392                                   ARMPCLabelIndex, PCAdj);
2393   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2394   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2395   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2396                                MachinePointerInfo::getConstantPool(),
2397                                false, false, false, 0);
2398   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2399   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2400 }
2401
2402 SDValue
2403 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2404   DebugLoc dl = Op.getDebugLoc();
2405   SDValue Val = DAG.getConstant(0, MVT::i32);
2406   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2407                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2408                      Op.getOperand(1), Val);
2409 }
2410
2411 SDValue
2412 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2413   DebugLoc dl = Op.getDebugLoc();
2414   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2415                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2416 }
2417
2418 SDValue
2419 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2420                                           const ARMSubtarget *Subtarget) const {
2421   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2422   DebugLoc dl = Op.getDebugLoc();
2423   switch (IntNo) {
2424   default: return SDValue();    // Don't custom lower most intrinsics.
2425   case Intrinsic::arm_thread_pointer: {
2426     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2427     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2428   }
2429   case Intrinsic::eh_sjlj_lsda: {
2430     MachineFunction &MF = DAG.getMachineFunction();
2431     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2432     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2433     EVT PtrVT = getPointerTy();
2434     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2435     SDValue CPAddr;
2436     unsigned PCAdj = (RelocM != Reloc::PIC_)
2437       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2438     ARMConstantPoolValue *CPV =
2439       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2440                                       ARMCP::CPLSDA, PCAdj);
2441     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2442     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2443     SDValue Result =
2444       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2445                   MachinePointerInfo::getConstantPool(),
2446                   false, false, false, 0);
2447
2448     if (RelocM == Reloc::PIC_) {
2449       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2450       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2451     }
2452     return Result;
2453   }
2454   case Intrinsic::arm_neon_vmulls:
2455   case Intrinsic::arm_neon_vmullu: {
2456     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2457       ? ARMISD::VMULLs : ARMISD::VMULLu;
2458     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2459                        Op.getOperand(1), Op.getOperand(2));
2460   }
2461   }
2462 }
2463
2464 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2465                                const ARMSubtarget *Subtarget) {
2466   DebugLoc dl = Op.getDebugLoc();
2467   if (!Subtarget->hasDataBarrier()) {
2468     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2469     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2470     // here.
2471     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2472            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2473     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2474                        DAG.getConstant(0, MVT::i32));
2475   }
2476
2477   SDValue Op5 = Op.getOperand(5);
2478   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2479   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2480   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2481   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2482
2483   ARM_MB::MemBOpt DMBOpt;
2484   if (isDeviceBarrier)
2485     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2486   else
2487     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2488   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2489                      DAG.getConstant(DMBOpt, MVT::i32));
2490 }
2491
2492
2493 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2494                                  const ARMSubtarget *Subtarget) {
2495   // FIXME: handle "fence singlethread" more efficiently.
2496   DebugLoc dl = Op.getDebugLoc();
2497   if (!Subtarget->hasDataBarrier()) {
2498     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2499     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2500     // here.
2501     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2502            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2503     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2504                        DAG.getConstant(0, MVT::i32));
2505   }
2506
2507   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2508                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2509 }
2510
2511 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2512                              const ARMSubtarget *Subtarget) {
2513   // ARM pre v5TE and Thumb1 does not have preload instructions.
2514   if (!(Subtarget->isThumb2() ||
2515         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2516     // Just preserve the chain.
2517     return Op.getOperand(0);
2518
2519   DebugLoc dl = Op.getDebugLoc();
2520   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2521   if (!isRead &&
2522       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2523     // ARMv7 with MP extension has PLDW.
2524     return Op.getOperand(0);
2525
2526   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2527   if (Subtarget->isThumb()) {
2528     // Invert the bits.
2529     isRead = ~isRead & 1;
2530     isData = ~isData & 1;
2531   }
2532
2533   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2534                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2535                      DAG.getConstant(isData, MVT::i32));
2536 }
2537
2538 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2539   MachineFunction &MF = DAG.getMachineFunction();
2540   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2541
2542   // vastart just stores the address of the VarArgsFrameIndex slot into the
2543   // memory location argument.
2544   DebugLoc dl = Op.getDebugLoc();
2545   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2546   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2547   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2548   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2549                       MachinePointerInfo(SV), false, false, 0);
2550 }
2551
2552 SDValue
2553 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2554                                         SDValue &Root, SelectionDAG &DAG,
2555                                         DebugLoc dl) const {
2556   MachineFunction &MF = DAG.getMachineFunction();
2557   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2558
2559   const TargetRegisterClass *RC;
2560   if (AFI->isThumb1OnlyFunction())
2561     RC = &ARM::tGPRRegClass;
2562   else
2563     RC = &ARM::GPRRegClass;
2564
2565   // Transform the arguments stored in physical registers into virtual ones.
2566   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2567   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2568
2569   SDValue ArgValue2;
2570   if (NextVA.isMemLoc()) {
2571     MachineFrameInfo *MFI = MF.getFrameInfo();
2572     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2573
2574     // Create load node to retrieve arguments from the stack.
2575     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2576     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2577                             MachinePointerInfo::getFixedStack(FI),
2578                             false, false, false, 0);
2579   } else {
2580     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2581     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2582   }
2583
2584   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2585 }
2586
2587 void
2588 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2589                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2590   const {
2591   unsigned NumGPRs;
2592   if (CCInfo.isFirstByValRegValid())
2593     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2594   else {
2595     unsigned int firstUnalloced;
2596     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2597                                                 sizeof(GPRArgRegs) /
2598                                                 sizeof(GPRArgRegs[0]));
2599     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2600   }
2601
2602   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2603   VARegSize = NumGPRs * 4;
2604   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2605 }
2606
2607 // The remaining GPRs hold either the beginning of variable-argument
2608 // data, or the beginning of an aggregate passed by value (usually
2609 // byval).  Either way, we allocate stack slots adjacent to the data
2610 // provided by our caller, and store the unallocated registers there.
2611 // If this is a variadic function, the va_list pointer will begin with
2612 // these values; otherwise, this reassembles a (byval) structure that
2613 // was split between registers and memory.
2614 void
2615 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2616                                         DebugLoc dl, SDValue &Chain,
2617                                         const Value *OrigArg,
2618                                         unsigned OffsetFromOrigArg,
2619                                         unsigned ArgOffset,
2620                                         bool ForceMutable) const {
2621   MachineFunction &MF = DAG.getMachineFunction();
2622   MachineFrameInfo *MFI = MF.getFrameInfo();
2623   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2624   unsigned firstRegToSaveIndex;
2625   if (CCInfo.isFirstByValRegValid())
2626     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2627   else {
2628     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2629       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2630   }
2631
2632   unsigned VARegSize, VARegSaveSize;
2633   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2634   if (VARegSaveSize) {
2635     // If this function is vararg, store any remaining integer argument regs
2636     // to their spots on the stack so that they may be loaded by deferencing
2637     // the result of va_next.
2638     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2639     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2640                                                      ArgOffset + VARegSaveSize
2641                                                      - VARegSize,
2642                                                      false));
2643     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2644                                     getPointerTy());
2645
2646     SmallVector<SDValue, 4> MemOps;
2647     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2648       const TargetRegisterClass *RC;
2649       if (AFI->isThumb1OnlyFunction())
2650         RC = &ARM::tGPRRegClass;
2651       else
2652         RC = &ARM::GPRRegClass;
2653
2654       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2655       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2656       SDValue Store =
2657         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2658                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2659                      false, false, 0);
2660       MemOps.push_back(Store);
2661       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2662                         DAG.getConstant(4, getPointerTy()));
2663     }
2664     if (!MemOps.empty())
2665       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2666                           &MemOps[0], MemOps.size());
2667   } else
2668     // This will point to the next argument passed via stack.
2669     AFI->setVarArgsFrameIndex(
2670         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2671 }
2672
2673 SDValue
2674 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2675                                         CallingConv::ID CallConv, bool isVarArg,
2676                                         const SmallVectorImpl<ISD::InputArg>
2677                                           &Ins,
2678                                         DebugLoc dl, SelectionDAG &DAG,
2679                                         SmallVectorImpl<SDValue> &InVals)
2680                                           const {
2681   MachineFunction &MF = DAG.getMachineFunction();
2682   MachineFrameInfo *MFI = MF.getFrameInfo();
2683
2684   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2685
2686   // Assign locations to all of the incoming arguments.
2687   SmallVector<CCValAssign, 16> ArgLocs;
2688   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2689                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2690   CCInfo.AnalyzeFormalArguments(Ins,
2691                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2692                                                   isVarArg));
2693
2694   SmallVector<SDValue, 16> ArgValues;
2695   int lastInsIndex = -1;
2696   SDValue ArgValue;
2697   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2698   unsigned CurArgIdx = 0;
2699   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2700     CCValAssign &VA = ArgLocs[i];
2701     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2702     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2703     // Arguments stored in registers.
2704     if (VA.isRegLoc()) {
2705       EVT RegVT = VA.getLocVT();
2706
2707       if (VA.needsCustom()) {
2708         // f64 and vector types are split up into multiple registers or
2709         // combinations of registers and stack slots.
2710         if (VA.getLocVT() == MVT::v2f64) {
2711           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2712                                                    Chain, DAG, dl);
2713           VA = ArgLocs[++i]; // skip ahead to next loc
2714           SDValue ArgValue2;
2715           if (VA.isMemLoc()) {
2716             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2717             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2718             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2719                                     MachinePointerInfo::getFixedStack(FI),
2720                                     false, false, false, 0);
2721           } else {
2722             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2723                                              Chain, DAG, dl);
2724           }
2725           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2726           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2727                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2728           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2729                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2730         } else
2731           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2732
2733       } else {
2734         const TargetRegisterClass *RC;
2735
2736         if (RegVT == MVT::f32)
2737           RC = &ARM::SPRRegClass;
2738         else if (RegVT == MVT::f64)
2739           RC = &ARM::DPRRegClass;
2740         else if (RegVT == MVT::v2f64)
2741           RC = &ARM::QPRRegClass;
2742         else if (RegVT == MVT::i32)
2743           RC = AFI->isThumb1OnlyFunction() ?
2744             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2745             (const TargetRegisterClass*)&ARM::GPRRegClass;
2746         else
2747           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2748
2749         // Transform the arguments in physical registers into virtual ones.
2750         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2751         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2752       }
2753
2754       // If this is an 8 or 16-bit value, it is really passed promoted
2755       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2756       // truncate to the right size.
2757       switch (VA.getLocInfo()) {
2758       default: llvm_unreachable("Unknown loc info!");
2759       case CCValAssign::Full: break;
2760       case CCValAssign::BCvt:
2761         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2762         break;
2763       case CCValAssign::SExt:
2764         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2765                                DAG.getValueType(VA.getValVT()));
2766         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2767         break;
2768       case CCValAssign::ZExt:
2769         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2770                                DAG.getValueType(VA.getValVT()));
2771         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2772         break;
2773       }
2774
2775       InVals.push_back(ArgValue);
2776
2777     } else { // VA.isRegLoc()
2778
2779       // sanity check
2780       assert(VA.isMemLoc());
2781       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2782
2783       int index = ArgLocs[i].getValNo();
2784
2785       // Some Ins[] entries become multiple ArgLoc[] entries.
2786       // Process them only once.
2787       if (index != lastInsIndex)
2788         {
2789           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2790           // FIXME: For now, all byval parameter objects are marked mutable.
2791           // This can be changed with more analysis.
2792           // In case of tail call optimization mark all arguments mutable.
2793           // Since they could be overwritten by lowering of arguments in case of
2794           // a tail call.
2795           if (Flags.isByVal()) {
2796             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2797             if (!AFI->getVarArgsFrameIndex()) {
2798               VarArgStyleRegisters(CCInfo, DAG,
2799                                    dl, Chain, CurOrigArg,
2800                                    Ins[VA.getValNo()].PartOffset,
2801                                    VA.getLocMemOffset(),
2802                                    true /*force mutable frames*/);
2803               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2804               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2805             } else {
2806               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2807                                               VA.getLocMemOffset(), false);
2808               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2809             }
2810           } else {
2811             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2812                                             VA.getLocMemOffset(), true);
2813
2814             // Create load nodes to retrieve arguments from the stack.
2815             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2816             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2817                                          MachinePointerInfo::getFixedStack(FI),
2818                                          false, false, false, 0));
2819           }
2820           lastInsIndex = index;
2821         }
2822     }
2823   }
2824
2825   // varargs
2826   if (isVarArg)
2827     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2828                          CCInfo.getNextStackOffset());
2829
2830   return Chain;
2831 }
2832
2833 /// isFloatingPointZero - Return true if this is +0.0.
2834 static bool isFloatingPointZero(SDValue Op) {
2835   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2836     return CFP->getValueAPF().isPosZero();
2837   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2838     // Maybe this has already been legalized into the constant pool?
2839     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2840       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2841       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2842         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2843           return CFP->getValueAPF().isPosZero();
2844     }
2845   }
2846   return false;
2847 }
2848
2849 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2850 /// the given operands.
2851 SDValue
2852 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2853                              SDValue &ARMcc, SelectionDAG &DAG,
2854                              DebugLoc dl) const {
2855   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2856     unsigned C = RHSC->getZExtValue();
2857     if (!isLegalICmpImmediate(C)) {
2858       // Constant does not fit, try adjusting it by one?
2859       switch (CC) {
2860       default: break;
2861       case ISD::SETLT:
2862       case ISD::SETGE:
2863         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2864           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2865           RHS = DAG.getConstant(C-1, MVT::i32);
2866         }
2867         break;
2868       case ISD::SETULT:
2869       case ISD::SETUGE:
2870         if (C != 0 && isLegalICmpImmediate(C-1)) {
2871           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2872           RHS = DAG.getConstant(C-1, MVT::i32);
2873         }
2874         break;
2875       case ISD::SETLE:
2876       case ISD::SETGT:
2877         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2878           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2879           RHS = DAG.getConstant(C+1, MVT::i32);
2880         }
2881         break;
2882       case ISD::SETULE:
2883       case ISD::SETUGT:
2884         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2885           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2886           RHS = DAG.getConstant(C+1, MVT::i32);
2887         }
2888         break;
2889       }
2890     }
2891   }
2892
2893   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2894   ARMISD::NodeType CompareType;
2895   switch (CondCode) {
2896   default:
2897     CompareType = ARMISD::CMP;
2898     break;
2899   case ARMCC::EQ:
2900   case ARMCC::NE:
2901     // Uses only Z Flag
2902     CompareType = ARMISD::CMPZ;
2903     break;
2904   }
2905   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2906   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2907 }
2908
2909 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2910 SDValue
2911 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2912                              DebugLoc dl) const {
2913   SDValue Cmp;
2914   if (!isFloatingPointZero(RHS))
2915     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2916   else
2917     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2918   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2919 }
2920
2921 /// duplicateCmp - Glue values can have only one use, so this function
2922 /// duplicates a comparison node.
2923 SDValue
2924 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2925   unsigned Opc = Cmp.getOpcode();
2926   DebugLoc DL = Cmp.getDebugLoc();
2927   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2928     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2929
2930   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2931   Cmp = Cmp.getOperand(0);
2932   Opc = Cmp.getOpcode();
2933   if (Opc == ARMISD::CMPFP)
2934     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2935   else {
2936     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2937     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2938   }
2939   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2940 }
2941
2942 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2943   SDValue Cond = Op.getOperand(0);
2944   SDValue SelectTrue = Op.getOperand(1);
2945   SDValue SelectFalse = Op.getOperand(2);
2946   DebugLoc dl = Op.getDebugLoc();
2947
2948   // Convert:
2949   //
2950   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2951   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2952   //
2953   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2954     const ConstantSDNode *CMOVTrue =
2955       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2956     const ConstantSDNode *CMOVFalse =
2957       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2958
2959     if (CMOVTrue && CMOVFalse) {
2960       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2961       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2962
2963       SDValue True;
2964       SDValue False;
2965       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2966         True = SelectTrue;
2967         False = SelectFalse;
2968       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2969         True = SelectFalse;
2970         False = SelectTrue;
2971       }
2972
2973       if (True.getNode() && False.getNode()) {
2974         EVT VT = Op.getValueType();
2975         SDValue ARMcc = Cond.getOperand(2);
2976         SDValue CCR = Cond.getOperand(3);
2977         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2978         assert(True.getValueType() == VT);
2979         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2980       }
2981     }
2982   }
2983
2984   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2985   // undefined bits before doing a full-word comparison with zero.
2986   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2987                      DAG.getConstant(1, Cond.getValueType()));
2988
2989   return DAG.getSelectCC(dl, Cond,
2990                          DAG.getConstant(0, Cond.getValueType()),
2991                          SelectTrue, SelectFalse, ISD::SETNE);
2992 }
2993
2994 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2995   EVT VT = Op.getValueType();
2996   SDValue LHS = Op.getOperand(0);
2997   SDValue RHS = Op.getOperand(1);
2998   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2999   SDValue TrueVal = Op.getOperand(2);
3000   SDValue FalseVal = Op.getOperand(3);
3001   DebugLoc dl = Op.getDebugLoc();
3002
3003   if (LHS.getValueType() == MVT::i32) {
3004     SDValue ARMcc;
3005     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3006     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3007     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3008   }
3009
3010   ARMCC::CondCodes CondCode, CondCode2;
3011   FPCCToARMCC(CC, CondCode, CondCode2);
3012
3013   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3014   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3015   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3016   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3017                                ARMcc, CCR, Cmp);
3018   if (CondCode2 != ARMCC::AL) {
3019     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3020     // FIXME: Needs another CMP because flag can have but one use.
3021     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3022     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3023                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3024   }
3025   return Result;
3026 }
3027
3028 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3029 /// to morph to an integer compare sequence.
3030 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3031                            const ARMSubtarget *Subtarget) {
3032   SDNode *N = Op.getNode();
3033   if (!N->hasOneUse())
3034     // Otherwise it requires moving the value from fp to integer registers.
3035     return false;
3036   if (!N->getNumValues())
3037     return false;
3038   EVT VT = Op.getValueType();
3039   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3040     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3041     // vmrs are very slow, e.g. cortex-a8.
3042     return false;
3043
3044   if (isFloatingPointZero(Op)) {
3045     SeenZero = true;
3046     return true;
3047   }
3048   return ISD::isNormalLoad(N);
3049 }
3050
3051 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3052   if (isFloatingPointZero(Op))
3053     return DAG.getConstant(0, MVT::i32);
3054
3055   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3056     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3057                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3058                        Ld->isVolatile(), Ld->isNonTemporal(),
3059                        Ld->isInvariant(), Ld->getAlignment());
3060
3061   llvm_unreachable("Unknown VFP cmp argument!");
3062 }
3063
3064 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3065                            SDValue &RetVal1, SDValue &RetVal2) {
3066   if (isFloatingPointZero(Op)) {
3067     RetVal1 = DAG.getConstant(0, MVT::i32);
3068     RetVal2 = DAG.getConstant(0, MVT::i32);
3069     return;
3070   }
3071
3072   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3073     SDValue Ptr = Ld->getBasePtr();
3074     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3075                           Ld->getChain(), Ptr,
3076                           Ld->getPointerInfo(),
3077                           Ld->isVolatile(), Ld->isNonTemporal(),
3078                           Ld->isInvariant(), Ld->getAlignment());
3079
3080     EVT PtrType = Ptr.getValueType();
3081     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3082     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3083                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3084     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3085                           Ld->getChain(), NewPtr,
3086                           Ld->getPointerInfo().getWithOffset(4),
3087                           Ld->isVolatile(), Ld->isNonTemporal(),
3088                           Ld->isInvariant(), NewAlign);
3089     return;
3090   }
3091
3092   llvm_unreachable("Unknown VFP cmp argument!");
3093 }
3094
3095 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3096 /// f32 and even f64 comparisons to integer ones.
3097 SDValue
3098 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3099   SDValue Chain = Op.getOperand(0);
3100   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3101   SDValue LHS = Op.getOperand(2);
3102   SDValue RHS = Op.getOperand(3);
3103   SDValue Dest = Op.getOperand(4);
3104   DebugLoc dl = Op.getDebugLoc();
3105
3106   bool LHSSeenZero = false;
3107   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3108   bool RHSSeenZero = false;
3109   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3110   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3111     // If unsafe fp math optimization is enabled and there are no other uses of
3112     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3113     // to an integer comparison.
3114     if (CC == ISD::SETOEQ)
3115       CC = ISD::SETEQ;
3116     else if (CC == ISD::SETUNE)
3117       CC = ISD::SETNE;
3118
3119     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3120     SDValue ARMcc;
3121     if (LHS.getValueType() == MVT::f32) {
3122       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3123                         bitcastf32Toi32(LHS, DAG), Mask);
3124       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3125                         bitcastf32Toi32(RHS, DAG), Mask);
3126       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3127       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3128       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3129                          Chain, Dest, ARMcc, CCR, Cmp);
3130     }
3131
3132     SDValue LHS1, LHS2;
3133     SDValue RHS1, RHS2;
3134     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3135     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3136     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3137     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3138     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3139     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3140     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3141     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3142     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3143   }
3144
3145   return SDValue();
3146 }
3147
3148 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3149   SDValue Chain = Op.getOperand(0);
3150   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3151   SDValue LHS = Op.getOperand(2);
3152   SDValue RHS = Op.getOperand(3);
3153   SDValue Dest = Op.getOperand(4);
3154   DebugLoc dl = Op.getDebugLoc();
3155
3156   if (LHS.getValueType() == MVT::i32) {
3157     SDValue ARMcc;
3158     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3159     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3160     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3161                        Chain, Dest, ARMcc, CCR, Cmp);
3162   }
3163
3164   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3165
3166   if (getTargetMachine().Options.UnsafeFPMath &&
3167       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3168        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3169     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3170     if (Result.getNode())
3171       return Result;
3172   }
3173
3174   ARMCC::CondCodes CondCode, CondCode2;
3175   FPCCToARMCC(CC, CondCode, CondCode2);
3176
3177   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3178   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3179   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3180   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3181   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3182   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3183   if (CondCode2 != ARMCC::AL) {
3184     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3185     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3186     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3187   }
3188   return Res;
3189 }
3190
3191 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3192   SDValue Chain = Op.getOperand(0);
3193   SDValue Table = Op.getOperand(1);
3194   SDValue Index = Op.getOperand(2);
3195   DebugLoc dl = Op.getDebugLoc();
3196
3197   EVT PTy = getPointerTy();
3198   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3199   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3200   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3201   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3202   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3203   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3204   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3205   if (Subtarget->isThumb2()) {
3206     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3207     // which does another jump to the destination. This also makes it easier
3208     // to translate it to TBB / TBH later.
3209     // FIXME: This might not work if the function is extremely large.
3210     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3211                        Addr, Op.getOperand(2), JTI, UId);
3212   }
3213   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3214     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3215                        MachinePointerInfo::getJumpTable(),
3216                        false, false, false, 0);
3217     Chain = Addr.getValue(1);
3218     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3219     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3220   } else {
3221     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3222                        MachinePointerInfo::getJumpTable(),
3223                        false, false, false, 0);
3224     Chain = Addr.getValue(1);
3225     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3226   }
3227 }
3228
3229 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3230   EVT VT = Op.getValueType();
3231   DebugLoc dl = Op.getDebugLoc();
3232
3233   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3234     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3235       return Op;
3236     return DAG.UnrollVectorOp(Op.getNode());
3237   }
3238
3239   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3240          "Invalid type for custom lowering!");
3241   if (VT != MVT::v4i16)
3242     return DAG.UnrollVectorOp(Op.getNode());
3243
3244   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3245   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3246 }
3247
3248 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3249   EVT VT = Op.getValueType();
3250   if (VT.isVector())
3251     return LowerVectorFP_TO_INT(Op, DAG);
3252
3253   DebugLoc dl = Op.getDebugLoc();
3254   unsigned Opc;
3255
3256   switch (Op.getOpcode()) {
3257   default: llvm_unreachable("Invalid opcode!");
3258   case ISD::FP_TO_SINT:
3259     Opc = ARMISD::FTOSI;
3260     break;
3261   case ISD::FP_TO_UINT:
3262     Opc = ARMISD::FTOUI;
3263     break;
3264   }
3265   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3266   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3267 }
3268
3269 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3270   EVT VT = Op.getValueType();
3271   DebugLoc dl = Op.getDebugLoc();
3272
3273   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3274     if (VT.getVectorElementType() == MVT::f32)
3275       return Op;
3276     return DAG.UnrollVectorOp(Op.getNode());
3277   }
3278
3279   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3280          "Invalid type for custom lowering!");
3281   if (VT != MVT::v4f32)
3282     return DAG.UnrollVectorOp(Op.getNode());
3283
3284   unsigned CastOpc;
3285   unsigned Opc;
3286   switch (Op.getOpcode()) {
3287   default: llvm_unreachable("Invalid opcode!");
3288   case ISD::SINT_TO_FP:
3289     CastOpc = ISD::SIGN_EXTEND;
3290     Opc = ISD::SINT_TO_FP;
3291     break;
3292   case ISD::UINT_TO_FP:
3293     CastOpc = ISD::ZERO_EXTEND;
3294     Opc = ISD::UINT_TO_FP;
3295     break;
3296   }
3297
3298   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3299   return DAG.getNode(Opc, dl, VT, Op);
3300 }
3301
3302 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3303   EVT VT = Op.getValueType();
3304   if (VT.isVector())
3305     return LowerVectorINT_TO_FP(Op, DAG);
3306
3307   DebugLoc dl = Op.getDebugLoc();
3308   unsigned Opc;
3309
3310   switch (Op.getOpcode()) {
3311   default: llvm_unreachable("Invalid opcode!");
3312   case ISD::SINT_TO_FP:
3313     Opc = ARMISD::SITOF;
3314     break;
3315   case ISD::UINT_TO_FP:
3316     Opc = ARMISD::UITOF;
3317     break;
3318   }
3319
3320   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3321   return DAG.getNode(Opc, dl, VT, Op);
3322 }
3323
3324 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3325   // Implement fcopysign with a fabs and a conditional fneg.
3326   SDValue Tmp0 = Op.getOperand(0);
3327   SDValue Tmp1 = Op.getOperand(1);
3328   DebugLoc dl = Op.getDebugLoc();
3329   EVT VT = Op.getValueType();
3330   EVT SrcVT = Tmp1.getValueType();
3331   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3332     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3333   bool UseNEON = !InGPR && Subtarget->hasNEON();
3334
3335   if (UseNEON) {
3336     // Use VBSL to copy the sign bit.
3337     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3338     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3339                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3340     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3341     if (VT == MVT::f64)
3342       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3343                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3344                          DAG.getConstant(32, MVT::i32));
3345     else /*if (VT == MVT::f32)*/
3346       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3347     if (SrcVT == MVT::f32) {
3348       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3349       if (VT == MVT::f64)
3350         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3351                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3352                            DAG.getConstant(32, MVT::i32));
3353     } else if (VT == MVT::f32)
3354       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3355                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3356                          DAG.getConstant(32, MVT::i32));
3357     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3358     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3359
3360     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3361                                             MVT::i32);
3362     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3363     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3364                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3365
3366     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3367                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3368                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3369     if (VT == MVT::f32) {
3370       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3371       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3372                         DAG.getConstant(0, MVT::i32));
3373     } else {
3374       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3375     }
3376
3377     return Res;
3378   }
3379
3380   // Bitcast operand 1 to i32.
3381   if (SrcVT == MVT::f64)
3382     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3383                        &Tmp1, 1).getValue(1);
3384   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3385
3386   // Or in the signbit with integer operations.
3387   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3388   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3389   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3390   if (VT == MVT::f32) {
3391     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3392                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3393     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3394                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3395   }
3396
3397   // f64: Or the high part with signbit and then combine two parts.
3398   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3399                      &Tmp0, 1);
3400   SDValue Lo = Tmp0.getValue(0);
3401   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3402   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3403   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3404 }
3405
3406 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3407   MachineFunction &MF = DAG.getMachineFunction();
3408   MachineFrameInfo *MFI = MF.getFrameInfo();
3409   MFI->setReturnAddressIsTaken(true);
3410
3411   EVT VT = Op.getValueType();
3412   DebugLoc dl = Op.getDebugLoc();
3413   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3414   if (Depth) {
3415     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3416     SDValue Offset = DAG.getConstant(4, MVT::i32);
3417     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3418                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3419                        MachinePointerInfo(), false, false, false, 0);
3420   }
3421
3422   // Return LR, which contains the return address. Mark it an implicit live-in.
3423   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3424   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3425 }
3426
3427 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3428   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3429   MFI->setFrameAddressIsTaken(true);
3430
3431   EVT VT = Op.getValueType();
3432   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3433   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3434   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3435     ? ARM::R7 : ARM::R11;
3436   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3437   while (Depth--)
3438     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3439                             MachinePointerInfo(),
3440                             false, false, false, 0);
3441   return FrameAddr;
3442 }
3443
3444 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3445 /// and size(DestVec) > 128-bits.
3446 /// This is achieved by doing the one extension from the SrcVec, splitting the
3447 /// result, extending these parts, and then concatenating these into the
3448 /// destination.
3449 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3450   SDValue Op = N->getOperand(0);
3451   EVT SrcVT = Op.getValueType();
3452   EVT DestVT = N->getValueType(0);
3453
3454   assert(DestVT.getSizeInBits() > 128 &&
3455          "Custom sext/zext expansion needs >128-bit vector.");
3456   // If this is a normal length extension, use the default expansion.
3457   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3458       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3459     return SDValue();
3460
3461   DebugLoc dl = N->getDebugLoc();
3462   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3463   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3464   unsigned NumElts = SrcVT.getVectorNumElements();
3465   LLVMContext &Ctx = *DAG.getContext();
3466   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3467
3468   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3469                                NumElts);
3470   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3471                                  NumElts/2);
3472   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3473                                NumElts/2);
3474
3475   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3476   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3477                         DAG.getIntPtrConstant(0));
3478   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3479                         DAG.getIntPtrConstant(NumElts/2));
3480   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3481   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3482   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3483 }
3484
3485 /// ExpandBITCAST - If the target supports VFP, this function is called to
3486 /// expand a bit convert where either the source or destination type is i64 to
3487 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3488 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3489 /// vectors), since the legalizer won't know what to do with that.
3490 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3492   DebugLoc dl = N->getDebugLoc();
3493   SDValue Op = N->getOperand(0);
3494
3495   // This function is only supposed to be called for i64 types, either as the
3496   // source or destination of the bit convert.
3497   EVT SrcVT = Op.getValueType();
3498   EVT DstVT = N->getValueType(0);
3499   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3500          "ExpandBITCAST called for non-i64 type");
3501
3502   // Turn i64->f64 into VMOVDRR.
3503   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3504     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3505                              DAG.getConstant(0, MVT::i32));
3506     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3507                              DAG.getConstant(1, MVT::i32));
3508     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3509                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3510   }
3511
3512   // Turn f64->i64 into VMOVRRD.
3513   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3514     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3515                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3516     // Merge the pieces into a single i64 value.
3517     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3518   }
3519
3520   return SDValue();
3521 }
3522
3523 /// getZeroVector - Returns a vector of specified type with all zero elements.
3524 /// Zero vectors are used to represent vector negation and in those cases
3525 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3526 /// not support i64 elements, so sometimes the zero vectors will need to be
3527 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3528 /// zero vector.
3529 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3530   assert(VT.isVector() && "Expected a vector type");
3531   // The canonical modified immediate encoding of a zero vector is....0!
3532   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3533   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3534   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3535   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3536 }
3537
3538 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3539 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3540 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3541                                                 SelectionDAG &DAG) const {
3542   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3543   EVT VT = Op.getValueType();
3544   unsigned VTBits = VT.getSizeInBits();
3545   DebugLoc dl = Op.getDebugLoc();
3546   SDValue ShOpLo = Op.getOperand(0);
3547   SDValue ShOpHi = Op.getOperand(1);
3548   SDValue ShAmt  = Op.getOperand(2);
3549   SDValue ARMcc;
3550   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3551
3552   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3553
3554   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3555                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3556   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3557   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3558                                    DAG.getConstant(VTBits, MVT::i32));
3559   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3560   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3561   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3562
3563   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3564   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3565                           ARMcc, DAG, dl);
3566   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3567   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3568                            CCR, Cmp);
3569
3570   SDValue Ops[2] = { Lo, Hi };
3571   return DAG.getMergeValues(Ops, 2, dl);
3572 }
3573
3574 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3575 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3576 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3577                                                SelectionDAG &DAG) const {
3578   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3579   EVT VT = Op.getValueType();
3580   unsigned VTBits = VT.getSizeInBits();
3581   DebugLoc dl = Op.getDebugLoc();
3582   SDValue ShOpLo = Op.getOperand(0);
3583   SDValue ShOpHi = Op.getOperand(1);
3584   SDValue ShAmt  = Op.getOperand(2);
3585   SDValue ARMcc;
3586
3587   assert(Op.getOpcode() == ISD::SHL_PARTS);
3588   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3589                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3590   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3591   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3592                                    DAG.getConstant(VTBits, MVT::i32));
3593   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3594   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3595
3596   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3597   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3598   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3599                           ARMcc, DAG, dl);
3600   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3601   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3602                            CCR, Cmp);
3603
3604   SDValue Ops[2] = { Lo, Hi };
3605   return DAG.getMergeValues(Ops, 2, dl);
3606 }
3607
3608 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3609                                             SelectionDAG &DAG) const {
3610   // The rounding mode is in bits 23:22 of the FPSCR.
3611   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3612   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3613   // so that the shift + and get folded into a bitfield extract.
3614   DebugLoc dl = Op.getDebugLoc();
3615   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3616                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3617                                               MVT::i32));
3618   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3619                                   DAG.getConstant(1U << 22, MVT::i32));
3620   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3621                               DAG.getConstant(22, MVT::i32));
3622   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3623                      DAG.getConstant(3, MVT::i32));
3624 }
3625
3626 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3627                          const ARMSubtarget *ST) {
3628   EVT VT = N->getValueType(0);
3629   DebugLoc dl = N->getDebugLoc();
3630
3631   if (!ST->hasV6T2Ops())
3632     return SDValue();
3633
3634   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3635   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3636 }
3637
3638 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3639 /// for each 16-bit element from operand, repeated.  The basic idea is to
3640 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3641 ///
3642 /// Trace for v4i16:
3643 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3644 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3645 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3646 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3647 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3648 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3649 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3650 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3651 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3652   EVT VT = N->getValueType(0);
3653   DebugLoc DL = N->getDebugLoc();
3654
3655   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3656   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3657   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3658   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3659   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3660   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3661 }
3662
3663 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3664 /// bit-count for each 16-bit element from the operand.  We need slightly
3665 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3666 /// 64/128-bit registers.
3667 ///
3668 /// Trace for v4i16:
3669 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3670 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3671 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3672 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3673 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3674   EVT VT = N->getValueType(0);
3675   DebugLoc DL = N->getDebugLoc();
3676
3677   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3678   if (VT.is64BitVector()) {
3679     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3680     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3681                        DAG.getIntPtrConstant(0));
3682   } else {
3683     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3684                                     BitCounts, DAG.getIntPtrConstant(0));
3685     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3686   }
3687 }
3688
3689 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3690 /// bit-count for each 32-bit element from the operand.  The idea here is
3691 /// to split the vector into 16-bit elements, leverage the 16-bit count
3692 /// routine, and then combine the results.
3693 ///
3694 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3695 /// input    = [v0    v1    ] (vi: 32-bit elements)
3696 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3697 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3698 /// vrev: N0 = [k1 k0 k3 k2 ]
3699 ///            [k0 k1 k2 k3 ]
3700 ///       N1 =+[k1 k0 k3 k2 ]
3701 ///            [k0 k2 k1 k3 ]
3702 ///       N2 =+[k1 k3 k0 k2 ]
3703 ///            [k0    k2    k1    k3    ]
3704 /// Extended =+[k1    k3    k0    k2    ]
3705 ///            [k0    k2    ]
3706 /// Extracted=+[k1    k3    ]
3707 ///
3708 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3709   EVT VT = N->getValueType(0);
3710   DebugLoc DL = N->getDebugLoc();
3711
3712   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3713
3714   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3715   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3716   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3717   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3718   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3719
3720   if (VT.is64BitVector()) {
3721     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3722     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3723                        DAG.getIntPtrConstant(0));
3724   } else {
3725     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3726                                     DAG.getIntPtrConstant(0));
3727     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3728   }
3729 }
3730
3731 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3732                           const ARMSubtarget *ST) {
3733   EVT VT = N->getValueType(0);
3734
3735   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3736   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3737           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3738          "Unexpected type for custom ctpop lowering");
3739
3740   if (VT.getVectorElementType() == MVT::i32)
3741     return lowerCTPOP32BitElements(N, DAG);
3742   else
3743     return lowerCTPOP16BitElements(N, DAG);
3744 }
3745
3746 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3747                           const ARMSubtarget *ST) {
3748   EVT VT = N->getValueType(0);
3749   DebugLoc dl = N->getDebugLoc();
3750
3751   if (!VT.isVector())
3752     return SDValue();
3753
3754   // Lower vector shifts on NEON to use VSHL.
3755   assert(ST->hasNEON() && "unexpected vector shift");
3756
3757   // Left shifts translate directly to the vshiftu intrinsic.
3758   if (N->getOpcode() == ISD::SHL)
3759     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3760                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3761                        N->getOperand(0), N->getOperand(1));
3762
3763   assert((N->getOpcode() == ISD::SRA ||
3764           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3765
3766   // NEON uses the same intrinsics for both left and right shifts.  For
3767   // right shifts, the shift amounts are negative, so negate the vector of
3768   // shift amounts.
3769   EVT ShiftVT = N->getOperand(1).getValueType();
3770   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3771                                      getZeroVector(ShiftVT, DAG, dl),
3772                                      N->getOperand(1));
3773   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3774                              Intrinsic::arm_neon_vshifts :
3775                              Intrinsic::arm_neon_vshiftu);
3776   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3777                      DAG.getConstant(vshiftInt, MVT::i32),
3778                      N->getOperand(0), NegatedCount);
3779 }
3780
3781 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3782                                 const ARMSubtarget *ST) {
3783   EVT VT = N->getValueType(0);
3784   DebugLoc dl = N->getDebugLoc();
3785
3786   // We can get here for a node like i32 = ISD::SHL i32, i64
3787   if (VT != MVT::i64)
3788     return SDValue();
3789
3790   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3791          "Unknown shift to lower!");
3792
3793   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3794   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3795       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3796     return SDValue();
3797
3798   // If we are in thumb mode, we don't have RRX.
3799   if (ST->isThumb1Only()) return SDValue();
3800
3801   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3802   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3803                            DAG.getConstant(0, MVT::i32));
3804   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3805                            DAG.getConstant(1, MVT::i32));
3806
3807   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3808   // captures the result into a carry flag.
3809   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3810   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3811
3812   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3813   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3814
3815   // Merge the pieces into a single i64 value.
3816  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3817 }
3818
3819 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3820   SDValue TmpOp0, TmpOp1;
3821   bool Invert = false;
3822   bool Swap = false;
3823   unsigned Opc = 0;
3824
3825   SDValue Op0 = Op.getOperand(0);
3826   SDValue Op1 = Op.getOperand(1);
3827   SDValue CC = Op.getOperand(2);
3828   EVT VT = Op.getValueType();
3829   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3830   DebugLoc dl = Op.getDebugLoc();
3831
3832   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3833     switch (SetCCOpcode) {
3834     default: llvm_unreachable("Illegal FP comparison");
3835     case ISD::SETUNE:
3836     case ISD::SETNE:  Invert = true; // Fallthrough
3837     case ISD::SETOEQ:
3838     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3839     case ISD::SETOLT:
3840     case ISD::SETLT: Swap = true; // Fallthrough
3841     case ISD::SETOGT:
3842     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3843     case ISD::SETOLE:
3844     case ISD::SETLE:  Swap = true; // Fallthrough
3845     case ISD::SETOGE:
3846     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3847     case ISD::SETUGE: Swap = true; // Fallthrough
3848     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3849     case ISD::SETUGT: Swap = true; // Fallthrough
3850     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3851     case ISD::SETUEQ: Invert = true; // Fallthrough
3852     case ISD::SETONE:
3853       // Expand this to (OLT | OGT).
3854       TmpOp0 = Op0;
3855       TmpOp1 = Op1;
3856       Opc = ISD::OR;
3857       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3858       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3859       break;
3860     case ISD::SETUO: Invert = true; // Fallthrough
3861     case ISD::SETO:
3862       // Expand this to (OLT | OGE).
3863       TmpOp0 = Op0;
3864       TmpOp1 = Op1;
3865       Opc = ISD::OR;
3866       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3867       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3868       break;
3869     }
3870   } else {
3871     // Integer comparisons.
3872     switch (SetCCOpcode) {
3873     default: llvm_unreachable("Illegal integer comparison");
3874     case ISD::SETNE:  Invert = true;
3875     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3876     case ISD::SETLT:  Swap = true;
3877     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3878     case ISD::SETLE:  Swap = true;
3879     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3880     case ISD::SETULT: Swap = true;
3881     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3882     case ISD::SETULE: Swap = true;
3883     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3884     }
3885
3886     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3887     if (Opc == ARMISD::VCEQ) {
3888
3889       SDValue AndOp;
3890       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3891         AndOp = Op0;
3892       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3893         AndOp = Op1;
3894
3895       // Ignore bitconvert.
3896       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3897         AndOp = AndOp.getOperand(0);
3898
3899       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3900         Opc = ARMISD::VTST;
3901         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3902         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3903         Invert = !Invert;
3904       }
3905     }
3906   }
3907
3908   if (Swap)
3909     std::swap(Op0, Op1);
3910
3911   // If one of the operands is a constant vector zero, attempt to fold the
3912   // comparison to a specialized compare-against-zero form.
3913   SDValue SingleOp;
3914   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3915     SingleOp = Op0;
3916   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3917     if (Opc == ARMISD::VCGE)
3918       Opc = ARMISD::VCLEZ;
3919     else if (Opc == ARMISD::VCGT)
3920       Opc = ARMISD::VCLTZ;
3921     SingleOp = Op1;
3922   }
3923
3924   SDValue Result;
3925   if (SingleOp.getNode()) {
3926     switch (Opc) {
3927     case ARMISD::VCEQ:
3928       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3929     case ARMISD::VCGE:
3930       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3931     case ARMISD::VCLEZ:
3932       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3933     case ARMISD::VCGT:
3934       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3935     case ARMISD::VCLTZ:
3936       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3937     default:
3938       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3939     }
3940   } else {
3941      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3942   }
3943
3944   if (Invert)
3945     Result = DAG.getNOT(dl, Result, VT);
3946
3947   return Result;
3948 }
3949
3950 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3951 /// valid vector constant for a NEON instruction with a "modified immediate"
3952 /// operand (e.g., VMOV).  If so, return the encoded value.
3953 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3954                                  unsigned SplatBitSize, SelectionDAG &DAG,
3955                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3956   unsigned OpCmode, Imm;
3957
3958   // SplatBitSize is set to the smallest size that splats the vector, so a
3959   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3960   // immediate instructions others than VMOV do not support the 8-bit encoding
3961   // of a zero vector, and the default encoding of zero is supposed to be the
3962   // 32-bit version.
3963   if (SplatBits == 0)
3964     SplatBitSize = 32;
3965
3966   switch (SplatBitSize) {
3967   case 8:
3968     if (type != VMOVModImm)
3969       return SDValue();
3970     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3971     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3972     OpCmode = 0xe;
3973     Imm = SplatBits;
3974     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3975     break;
3976
3977   case 16:
3978     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3979     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3980     if ((SplatBits & ~0xff) == 0) {
3981       // Value = 0x00nn: Op=x, Cmode=100x.
3982       OpCmode = 0x8;
3983       Imm = SplatBits;
3984       break;
3985     }
3986     if ((SplatBits & ~0xff00) == 0) {
3987       // Value = 0xnn00: Op=x, Cmode=101x.
3988       OpCmode = 0xa;
3989       Imm = SplatBits >> 8;
3990       break;
3991     }
3992     return SDValue();
3993
3994   case 32:
3995     // NEON's 32-bit VMOV supports splat values where:
3996     // * only one byte is nonzero, or
3997     // * the least significant byte is 0xff and the second byte is nonzero, or
3998     // * the least significant 2 bytes are 0xff and the third is nonzero.
3999     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4000     if ((SplatBits & ~0xff) == 0) {
4001       // Value = 0x000000nn: Op=x, Cmode=000x.
4002       OpCmode = 0;
4003       Imm = SplatBits;
4004       break;
4005     }
4006     if ((SplatBits & ~0xff00) == 0) {
4007       // Value = 0x0000nn00: Op=x, Cmode=001x.
4008       OpCmode = 0x2;
4009       Imm = SplatBits >> 8;
4010       break;
4011     }
4012     if ((SplatBits & ~0xff0000) == 0) {
4013       // Value = 0x00nn0000: Op=x, Cmode=010x.
4014       OpCmode = 0x4;
4015       Imm = SplatBits >> 16;
4016       break;
4017     }
4018     if ((SplatBits & ~0xff000000) == 0) {
4019       // Value = 0xnn000000: Op=x, Cmode=011x.
4020       OpCmode = 0x6;
4021       Imm = SplatBits >> 24;
4022       break;
4023     }
4024
4025     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4026     if (type == OtherModImm) return SDValue();
4027
4028     if ((SplatBits & ~0xffff) == 0 &&
4029         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4030       // Value = 0x0000nnff: Op=x, Cmode=1100.
4031       OpCmode = 0xc;
4032       Imm = SplatBits >> 8;
4033       SplatBits |= 0xff;
4034       break;
4035     }
4036
4037     if ((SplatBits & ~0xffffff) == 0 &&
4038         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4039       // Value = 0x00nnffff: Op=x, Cmode=1101.
4040       OpCmode = 0xd;
4041       Imm = SplatBits >> 16;
4042       SplatBits |= 0xffff;
4043       break;
4044     }
4045
4046     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4047     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4048     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4049     // and fall through here to test for a valid 64-bit splat.  But, then the
4050     // caller would also need to check and handle the change in size.
4051     return SDValue();
4052
4053   case 64: {
4054     if (type != VMOVModImm)
4055       return SDValue();
4056     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4057     uint64_t BitMask = 0xff;
4058     uint64_t Val = 0;
4059     unsigned ImmMask = 1;
4060     Imm = 0;
4061     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4062       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4063         Val |= BitMask;
4064         Imm |= ImmMask;
4065       } else if ((SplatBits & BitMask) != 0) {
4066         return SDValue();
4067       }
4068       BitMask <<= 8;
4069       ImmMask <<= 1;
4070     }
4071     // Op=1, Cmode=1110.
4072     OpCmode = 0x1e;
4073     SplatBits = Val;
4074     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4075     break;
4076   }
4077
4078   default:
4079     llvm_unreachable("unexpected size for isNEONModifiedImm");
4080   }
4081
4082   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4083   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4084 }
4085
4086 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4087                                            const ARMSubtarget *ST) const {
4088   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4089     return SDValue();
4090
4091   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4092   assert(Op.getValueType() == MVT::f32 &&
4093          "ConstantFP custom lowering should only occur for f32.");
4094
4095   // Try splatting with a VMOV.f32...
4096   APFloat FPVal = CFP->getValueAPF();
4097   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4098   if (ImmVal != -1) {
4099     DebugLoc DL = Op.getDebugLoc();
4100     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4101     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4102                                       NewVal);
4103     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4104                        DAG.getConstant(0, MVT::i32));
4105   }
4106
4107   // If that fails, try a VMOV.i32
4108   EVT VMovVT;
4109   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4110   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4111                                      VMOVModImm);
4112   if (NewVal != SDValue()) {
4113     DebugLoc DL = Op.getDebugLoc();
4114     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4115                                       NewVal);
4116     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4117                                        VecConstant);
4118     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4119                        DAG.getConstant(0, MVT::i32));
4120   }
4121
4122   // Finally, try a VMVN.i32
4123   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4124                              VMVNModImm);
4125   if (NewVal != SDValue()) {
4126     DebugLoc DL = Op.getDebugLoc();
4127     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4128     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4129                                        VecConstant);
4130     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4131                        DAG.getConstant(0, MVT::i32));
4132   }
4133
4134   return SDValue();
4135 }
4136
4137 // check if an VEXT instruction can handle the shuffle mask when the
4138 // vector sources of the shuffle are the same.
4139 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4140   unsigned NumElts = VT.getVectorNumElements();
4141
4142   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4143   if (M[0] < 0)
4144     return false;
4145
4146   Imm = M[0];
4147
4148   // If this is a VEXT shuffle, the immediate value is the index of the first
4149   // element.  The other shuffle indices must be the successive elements after
4150   // the first one.
4151   unsigned ExpectedElt = Imm;
4152   for (unsigned i = 1; i < NumElts; ++i) {
4153     // Increment the expected index.  If it wraps around, just follow it
4154     // back to index zero and keep going.
4155     ++ExpectedElt;
4156     if (ExpectedElt == NumElts)
4157       ExpectedElt = 0;
4158
4159     if (M[i] < 0) continue; // ignore UNDEF indices
4160     if (ExpectedElt != static_cast<unsigned>(M[i]))
4161       return false;
4162   }
4163
4164   return true;
4165 }
4166
4167
4168 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4169                        bool &ReverseVEXT, unsigned &Imm) {
4170   unsigned NumElts = VT.getVectorNumElements();
4171   ReverseVEXT = false;
4172
4173   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4174   if (M[0] < 0)
4175     return false;
4176
4177   Imm = M[0];
4178
4179   // If this is a VEXT shuffle, the immediate value is the index of the first
4180   // element.  The other shuffle indices must be the successive elements after
4181   // the first one.
4182   unsigned ExpectedElt = Imm;
4183   for (unsigned i = 1; i < NumElts; ++i) {
4184     // Increment the expected index.  If it wraps around, it may still be
4185     // a VEXT but the source vectors must be swapped.
4186     ExpectedElt += 1;
4187     if (ExpectedElt == NumElts * 2) {
4188       ExpectedElt = 0;
4189       ReverseVEXT = true;
4190     }
4191
4192     if (M[i] < 0) continue; // ignore UNDEF indices
4193     if (ExpectedElt != static_cast<unsigned>(M[i]))
4194       return false;
4195   }
4196
4197   // Adjust the index value if the source operands will be swapped.
4198   if (ReverseVEXT)
4199     Imm -= NumElts;
4200
4201   return true;
4202 }
4203
4204 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4205 /// instruction with the specified blocksize.  (The order of the elements
4206 /// within each block of the vector is reversed.)
4207 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4208   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4209          "Only possible block sizes for VREV are: 16, 32, 64");
4210
4211   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4212   if (EltSz == 64)
4213     return false;
4214
4215   unsigned NumElts = VT.getVectorNumElements();
4216   unsigned BlockElts = M[0] + 1;
4217   // If the first shuffle index is UNDEF, be optimistic.
4218   if (M[0] < 0)
4219     BlockElts = BlockSize / EltSz;
4220
4221   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4222     return false;
4223
4224   for (unsigned i = 0; i < NumElts; ++i) {
4225     if (M[i] < 0) continue; // ignore UNDEF indices
4226     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4227       return false;
4228   }
4229
4230   return true;
4231 }
4232
4233 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4234   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4235   // range, then 0 is placed into the resulting vector. So pretty much any mask
4236   // of 8 elements can work here.
4237   return VT == MVT::v8i8 && M.size() == 8;
4238 }
4239
4240 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4241   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4242   if (EltSz == 64)
4243     return false;
4244
4245   unsigned NumElts = VT.getVectorNumElements();
4246   WhichResult = (M[0] == 0 ? 0 : 1);
4247   for (unsigned i = 0; i < NumElts; i += 2) {
4248     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4249         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4250       return false;
4251   }
4252   return true;
4253 }
4254
4255 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4256 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4257 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4258 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4259   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4260   if (EltSz == 64)
4261     return false;
4262
4263   unsigned NumElts = VT.getVectorNumElements();
4264   WhichResult = (M[0] == 0 ? 0 : 1);
4265   for (unsigned i = 0; i < NumElts; i += 2) {
4266     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4267         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4268       return false;
4269   }
4270   return true;
4271 }
4272
4273 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4274   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4275   if (EltSz == 64)
4276     return false;
4277
4278   unsigned NumElts = VT.getVectorNumElements();
4279   WhichResult = (M[0] == 0 ? 0 : 1);
4280   for (unsigned i = 0; i != NumElts; ++i) {
4281     if (M[i] < 0) continue; // ignore UNDEF indices
4282     if ((unsigned) M[i] != 2 * i + WhichResult)
4283       return false;
4284   }
4285
4286   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4287   if (VT.is64BitVector() && EltSz == 32)
4288     return false;
4289
4290   return true;
4291 }
4292
4293 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4294 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4295 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4296 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4297   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4298   if (EltSz == 64)
4299     return false;
4300
4301   unsigned Half = VT.getVectorNumElements() / 2;
4302   WhichResult = (M[0] == 0 ? 0 : 1);
4303   for (unsigned j = 0; j != 2; ++j) {
4304     unsigned Idx = WhichResult;
4305     for (unsigned i = 0; i != Half; ++i) {
4306       int MIdx = M[i + j * Half];
4307       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4308         return false;
4309       Idx += 2;
4310     }
4311   }
4312
4313   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4314   if (VT.is64BitVector() && EltSz == 32)
4315     return false;
4316
4317   return true;
4318 }
4319
4320 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4321   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4322   if (EltSz == 64)
4323     return false;
4324
4325   unsigned NumElts = VT.getVectorNumElements();
4326   WhichResult = (M[0] == 0 ? 0 : 1);
4327   unsigned Idx = WhichResult * NumElts / 2;
4328   for (unsigned i = 0; i != NumElts; i += 2) {
4329     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4330         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4331       return false;
4332     Idx += 1;
4333   }
4334
4335   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4336   if (VT.is64BitVector() && EltSz == 32)
4337     return false;
4338
4339   return true;
4340 }
4341
4342 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4343 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4344 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4345 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4346   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4347   if (EltSz == 64)
4348     return false;
4349
4350   unsigned NumElts = VT.getVectorNumElements();
4351   WhichResult = (M[0] == 0 ? 0 : 1);
4352   unsigned Idx = WhichResult * NumElts / 2;
4353   for (unsigned i = 0; i != NumElts; i += 2) {
4354     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4355         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4356       return false;
4357     Idx += 1;
4358   }
4359
4360   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4361   if (VT.is64BitVector() && EltSz == 32)
4362     return false;
4363
4364   return true;
4365 }
4366
4367 /// \return true if this is a reverse operation on an vector.
4368 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4369   unsigned NumElts = VT.getVectorNumElements();
4370   // Make sure the mask has the right size.
4371   if (NumElts != M.size())
4372       return false;
4373
4374   // Look for <15, ..., 3, -1, 1, 0>.
4375   for (unsigned i = 0; i != NumElts; ++i)
4376     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4377       return false;
4378
4379   return true;
4380 }
4381
4382 // If N is an integer constant that can be moved into a register in one
4383 // instruction, return an SDValue of such a constant (will become a MOV
4384 // instruction).  Otherwise return null.
4385 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4386                                      const ARMSubtarget *ST, DebugLoc dl) {
4387   uint64_t Val;
4388   if (!isa<ConstantSDNode>(N))
4389     return SDValue();
4390   Val = cast<ConstantSDNode>(N)->getZExtValue();
4391
4392   if (ST->isThumb1Only()) {
4393     if (Val <= 255 || ~Val <= 255)
4394       return DAG.getConstant(Val, MVT::i32);
4395   } else {
4396     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4397       return DAG.getConstant(Val, MVT::i32);
4398   }
4399   return SDValue();
4400 }
4401
4402 // If this is a case we can't handle, return null and let the default
4403 // expansion code take care of it.
4404 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4405                                              const ARMSubtarget *ST) const {
4406   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4407   DebugLoc dl = Op.getDebugLoc();
4408   EVT VT = Op.getValueType();
4409
4410   APInt SplatBits, SplatUndef;
4411   unsigned SplatBitSize;
4412   bool HasAnyUndefs;
4413   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4414     if (SplatBitSize <= 64) {
4415       // Check if an immediate VMOV works.
4416       EVT VmovVT;
4417       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4418                                       SplatUndef.getZExtValue(), SplatBitSize,
4419                                       DAG, VmovVT, VT.is128BitVector(),
4420                                       VMOVModImm);
4421       if (Val.getNode()) {
4422         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4423         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4424       }
4425
4426       // Try an immediate VMVN.
4427       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4428       Val = isNEONModifiedImm(NegatedImm,
4429                                       SplatUndef.getZExtValue(), SplatBitSize,
4430                                       DAG, VmovVT, VT.is128BitVector(),
4431                                       VMVNModImm);
4432       if (Val.getNode()) {
4433         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4434         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4435       }
4436
4437       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4438       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4439         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4440         if (ImmVal != -1) {
4441           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4442           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4443         }
4444       }
4445     }
4446   }
4447
4448   // Scan through the operands to see if only one value is used.
4449   //
4450   // As an optimisation, even if more than one value is used it may be more
4451   // profitable to splat with one value then change some lanes.
4452   //
4453   // Heuristically we decide to do this if the vector has a "dominant" value,
4454   // defined as splatted to more than half of the lanes.
4455   unsigned NumElts = VT.getVectorNumElements();
4456   bool isOnlyLowElement = true;
4457   bool usesOnlyOneValue = true;
4458   bool hasDominantValue = false;
4459   bool isConstant = true;
4460
4461   // Map of the number of times a particular SDValue appears in the
4462   // element list.
4463   DenseMap<SDValue, unsigned> ValueCounts;
4464   SDValue Value;
4465   for (unsigned i = 0; i < NumElts; ++i) {
4466     SDValue V = Op.getOperand(i);
4467     if (V.getOpcode() == ISD::UNDEF)
4468       continue;
4469     if (i > 0)
4470       isOnlyLowElement = false;
4471     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4472       isConstant = false;
4473
4474     ValueCounts.insert(std::make_pair(V, 0));
4475     unsigned &Count = ValueCounts[V];
4476
4477     // Is this value dominant? (takes up more than half of the lanes)
4478     if (++Count > (NumElts / 2)) {
4479       hasDominantValue = true;
4480       Value = V;
4481     }
4482   }
4483   if (ValueCounts.size() != 1)
4484     usesOnlyOneValue = false;
4485   if (!Value.getNode() && ValueCounts.size() > 0)
4486     Value = ValueCounts.begin()->first;
4487
4488   if (ValueCounts.size() == 0)
4489     return DAG.getUNDEF(VT);
4490
4491   if (isOnlyLowElement)
4492     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4493
4494   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4495
4496   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4497   // i32 and try again.
4498   if (hasDominantValue && EltSize <= 32) {
4499     if (!isConstant) {
4500       SDValue N;
4501
4502       // If we are VDUPing a value that comes directly from a vector, that will
4503       // cause an unnecessary move to and from a GPR, where instead we could
4504       // just use VDUPLANE. We can only do this if the lane being extracted
4505       // is at a constant index, as the VDUP from lane instructions only have
4506       // constant-index forms.
4507       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4508           isa<ConstantSDNode>(Value->getOperand(1))) {
4509         // We need to create a new undef vector to use for the VDUPLANE if the
4510         // size of the vector from which we get the value is different than the
4511         // size of the vector that we need to create. We will insert the element
4512         // such that the register coalescer will remove unnecessary copies.
4513         if (VT != Value->getOperand(0).getValueType()) {
4514           ConstantSDNode *constIndex;
4515           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4516           assert(constIndex && "The index is not a constant!");
4517           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4518                              VT.getVectorNumElements();
4519           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4520                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4521                         Value, DAG.getConstant(index, MVT::i32)),
4522                            DAG.getConstant(index, MVT::i32));
4523         } else
4524           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4525                         Value->getOperand(0), Value->getOperand(1));
4526       } else
4527         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4528
4529       if (!usesOnlyOneValue) {
4530         // The dominant value was splatted as 'N', but we now have to insert
4531         // all differing elements.
4532         for (unsigned I = 0; I < NumElts; ++I) {
4533           if (Op.getOperand(I) == Value)
4534             continue;
4535           SmallVector<SDValue, 3> Ops;
4536           Ops.push_back(N);
4537           Ops.push_back(Op.getOperand(I));
4538           Ops.push_back(DAG.getConstant(I, MVT::i32));
4539           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4540         }
4541       }
4542       return N;
4543     }
4544     if (VT.getVectorElementType().isFloatingPoint()) {
4545       SmallVector<SDValue, 8> Ops;
4546       for (unsigned i = 0; i < NumElts; ++i)
4547         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4548                                   Op.getOperand(i)));
4549       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4550       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4551       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4552       if (Val.getNode())
4553         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4554     }
4555     if (usesOnlyOneValue) {
4556       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4557       if (isConstant && Val.getNode())
4558         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4559     }
4560   }
4561
4562   // If all elements are constants and the case above didn't get hit, fall back
4563   // to the default expansion, which will generate a load from the constant
4564   // pool.
4565   if (isConstant)
4566     return SDValue();
4567
4568   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4569   if (NumElts >= 4) {
4570     SDValue shuffle = ReconstructShuffle(Op, DAG);
4571     if (shuffle != SDValue())
4572       return shuffle;
4573   }
4574
4575   // Vectors with 32- or 64-bit elements can be built by directly assigning
4576   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4577   // will be legalized.
4578   if (EltSize >= 32) {
4579     // Do the expansion with floating-point types, since that is what the VFP
4580     // registers are defined to use, and since i64 is not legal.
4581     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4582     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4583     SmallVector<SDValue, 8> Ops;
4584     for (unsigned i = 0; i < NumElts; ++i)
4585       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4586     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4587     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4588   }
4589
4590   return SDValue();
4591 }
4592
4593 // Gather data to see if the operation can be modelled as a
4594 // shuffle in combination with VEXTs.
4595 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4596                                               SelectionDAG &DAG) const {
4597   DebugLoc dl = Op.getDebugLoc();
4598   EVT VT = Op.getValueType();
4599   unsigned NumElts = VT.getVectorNumElements();
4600
4601   SmallVector<SDValue, 2> SourceVecs;
4602   SmallVector<unsigned, 2> MinElts;
4603   SmallVector<unsigned, 2> MaxElts;
4604
4605   for (unsigned i = 0; i < NumElts; ++i) {
4606     SDValue V = Op.getOperand(i);
4607     if (V.getOpcode() == ISD::UNDEF)
4608       continue;
4609     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4610       // A shuffle can only come from building a vector from various
4611       // elements of other vectors.
4612       return SDValue();
4613     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4614                VT.getVectorElementType()) {
4615       // This code doesn't know how to handle shuffles where the vector
4616       // element types do not match (this happens because type legalization
4617       // promotes the return type of EXTRACT_VECTOR_ELT).
4618       // FIXME: It might be appropriate to extend this code to handle
4619       // mismatched types.
4620       return SDValue();
4621     }
4622
4623     // Record this extraction against the appropriate vector if possible...
4624     SDValue SourceVec = V.getOperand(0);
4625     // If the element number isn't a constant, we can't effectively
4626     // analyze what's going on.
4627     if (!isa<ConstantSDNode>(V.getOperand(1)))
4628       return SDValue();
4629     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4630     bool FoundSource = false;
4631     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4632       if (SourceVecs[j] == SourceVec) {
4633         if (MinElts[j] > EltNo)
4634           MinElts[j] = EltNo;
4635         if (MaxElts[j] < EltNo)
4636           MaxElts[j] = EltNo;
4637         FoundSource = true;
4638         break;
4639       }
4640     }
4641
4642     // Or record a new source if not...
4643     if (!FoundSource) {
4644       SourceVecs.push_back(SourceVec);
4645       MinElts.push_back(EltNo);
4646       MaxElts.push_back(EltNo);
4647     }
4648   }
4649
4650   // Currently only do something sane when at most two source vectors
4651   // involved.
4652   if (SourceVecs.size() > 2)
4653     return SDValue();
4654
4655   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4656   int VEXTOffsets[2] = {0, 0};
4657
4658   // This loop extracts the usage patterns of the source vectors
4659   // and prepares appropriate SDValues for a shuffle if possible.
4660   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4661     if (SourceVecs[i].getValueType() == VT) {
4662       // No VEXT necessary
4663       ShuffleSrcs[i] = SourceVecs[i];
4664       VEXTOffsets[i] = 0;
4665       continue;
4666     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4667       // It probably isn't worth padding out a smaller vector just to
4668       // break it down again in a shuffle.
4669       return SDValue();
4670     }
4671
4672     // Since only 64-bit and 128-bit vectors are legal on ARM and
4673     // we've eliminated the other cases...
4674     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4675            "unexpected vector sizes in ReconstructShuffle");
4676
4677     if (MaxElts[i] - MinElts[i] >= NumElts) {
4678       // Span too large for a VEXT to cope
4679       return SDValue();
4680     }
4681
4682     if (MinElts[i] >= NumElts) {
4683       // The extraction can just take the second half
4684       VEXTOffsets[i] = NumElts;
4685       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4686                                    SourceVecs[i],
4687                                    DAG.getIntPtrConstant(NumElts));
4688     } else if (MaxElts[i] < NumElts) {
4689       // The extraction can just take the first half
4690       VEXTOffsets[i] = 0;
4691       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4692                                    SourceVecs[i],
4693                                    DAG.getIntPtrConstant(0));
4694     } else {
4695       // An actual VEXT is needed
4696       VEXTOffsets[i] = MinElts[i];
4697       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4698                                      SourceVecs[i],
4699                                      DAG.getIntPtrConstant(0));
4700       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4701                                      SourceVecs[i],
4702                                      DAG.getIntPtrConstant(NumElts));
4703       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4704                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4705     }
4706   }
4707
4708   SmallVector<int, 8> Mask;
4709
4710   for (unsigned i = 0; i < NumElts; ++i) {
4711     SDValue Entry = Op.getOperand(i);
4712     if (Entry.getOpcode() == ISD::UNDEF) {
4713       Mask.push_back(-1);
4714       continue;
4715     }
4716
4717     SDValue ExtractVec = Entry.getOperand(0);
4718     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4719                                           .getOperand(1))->getSExtValue();
4720     if (ExtractVec == SourceVecs[0]) {
4721       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4722     } else {
4723       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4724     }
4725   }
4726
4727   // Final check before we try to produce nonsense...
4728   if (isShuffleMaskLegal(Mask, VT))
4729     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4730                                 &Mask[0]);
4731
4732   return SDValue();
4733 }
4734
4735 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4736 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4737 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4738 /// are assumed to be legal.
4739 bool
4740 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4741                                       EVT VT) const {
4742   if (VT.getVectorNumElements() == 4 &&
4743       (VT.is128BitVector() || VT.is64BitVector())) {
4744     unsigned PFIndexes[4];
4745     for (unsigned i = 0; i != 4; ++i) {
4746       if (M[i] < 0)
4747         PFIndexes[i] = 8;
4748       else
4749         PFIndexes[i] = M[i];
4750     }
4751
4752     // Compute the index in the perfect shuffle table.
4753     unsigned PFTableIndex =
4754       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4755     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4756     unsigned Cost = (PFEntry >> 30);
4757
4758     if (Cost <= 4)
4759       return true;
4760   }
4761
4762   bool ReverseVEXT;
4763   unsigned Imm, WhichResult;
4764
4765   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4766   return (EltSize >= 32 ||
4767           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4768           isVREVMask(M, VT, 64) ||
4769           isVREVMask(M, VT, 32) ||
4770           isVREVMask(M, VT, 16) ||
4771           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4772           isVTBLMask(M, VT) ||
4773           isVTRNMask(M, VT, WhichResult) ||
4774           isVUZPMask(M, VT, WhichResult) ||
4775           isVZIPMask(M, VT, WhichResult) ||
4776           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4777           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4778           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4779           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4780 }
4781
4782 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4783 /// the specified operations to build the shuffle.
4784 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4785                                       SDValue RHS, SelectionDAG &DAG,
4786                                       DebugLoc dl) {
4787   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4788   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4789   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4790
4791   enum {
4792     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4793     OP_VREV,
4794     OP_VDUP0,
4795     OP_VDUP1,
4796     OP_VDUP2,
4797     OP_VDUP3,
4798     OP_VEXT1,
4799     OP_VEXT2,
4800     OP_VEXT3,
4801     OP_VUZPL, // VUZP, left result
4802     OP_VUZPR, // VUZP, right result
4803     OP_VZIPL, // VZIP, left result
4804     OP_VZIPR, // VZIP, right result
4805     OP_VTRNL, // VTRN, left result
4806     OP_VTRNR  // VTRN, right result
4807   };
4808
4809   if (OpNum == OP_COPY) {
4810     if (LHSID == (1*9+2)*9+3) return LHS;
4811     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4812     return RHS;
4813   }
4814
4815   SDValue OpLHS, OpRHS;
4816   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4817   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4818   EVT VT = OpLHS.getValueType();
4819
4820   switch (OpNum) {
4821   default: llvm_unreachable("Unknown shuffle opcode!");
4822   case OP_VREV:
4823     // VREV divides the vector in half and swaps within the half.
4824     if (VT.getVectorElementType() == MVT::i32 ||
4825         VT.getVectorElementType() == MVT::f32)
4826       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4827     // vrev <4 x i16> -> VREV32
4828     if (VT.getVectorElementType() == MVT::i16)
4829       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4830     // vrev <4 x i8> -> VREV16
4831     assert(VT.getVectorElementType() == MVT::i8);
4832     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4833   case OP_VDUP0:
4834   case OP_VDUP1:
4835   case OP_VDUP2:
4836   case OP_VDUP3:
4837     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4838                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4839   case OP_VEXT1:
4840   case OP_VEXT2:
4841   case OP_VEXT3:
4842     return DAG.getNode(ARMISD::VEXT, dl, VT,
4843                        OpLHS, OpRHS,
4844                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4845   case OP_VUZPL:
4846   case OP_VUZPR:
4847     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4848                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4849   case OP_VZIPL:
4850   case OP_VZIPR:
4851     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4852                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4853   case OP_VTRNL:
4854   case OP_VTRNR:
4855     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4856                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4857   }
4858 }
4859
4860 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4861                                        ArrayRef<int> ShuffleMask,
4862                                        SelectionDAG &DAG) {
4863   // Check to see if we can use the VTBL instruction.
4864   SDValue V1 = Op.getOperand(0);
4865   SDValue V2 = Op.getOperand(1);
4866   DebugLoc DL = Op.getDebugLoc();
4867
4868   SmallVector<SDValue, 8> VTBLMask;
4869   for (ArrayRef<int>::iterator
4870          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4871     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4872
4873   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4874     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4875                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4876                                    &VTBLMask[0], 8));
4877
4878   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4879                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4880                                  &VTBLMask[0], 8));
4881 }
4882
4883 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4884                                                       SelectionDAG &DAG) {
4885   DebugLoc DL = Op.getDebugLoc();
4886   SDValue OpLHS = Op.getOperand(0);
4887   EVT VT = OpLHS.getValueType();
4888
4889   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4890          "Expect an v8i16/v16i8 type");
4891   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4892   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4893   // extract the first 8 bytes into the top double word and the last 8 bytes
4894   // into the bottom double word. The v8i16 case is similar.
4895   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4896   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4897                      DAG.getConstant(ExtractNum, MVT::i32));
4898 }
4899
4900 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4901   SDValue V1 = Op.getOperand(0);
4902   SDValue V2 = Op.getOperand(1);
4903   DebugLoc dl = Op.getDebugLoc();
4904   EVT VT = Op.getValueType();
4905   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4906
4907   // Convert shuffles that are directly supported on NEON to target-specific
4908   // DAG nodes, instead of keeping them as shuffles and matching them again
4909   // during code selection.  This is more efficient and avoids the possibility
4910   // of inconsistencies between legalization and selection.
4911   // FIXME: floating-point vectors should be canonicalized to integer vectors
4912   // of the same time so that they get CSEd properly.
4913   ArrayRef<int> ShuffleMask = SVN->getMask();
4914
4915   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4916   if (EltSize <= 32) {
4917     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4918       int Lane = SVN->getSplatIndex();
4919       // If this is undef splat, generate it via "just" vdup, if possible.
4920       if (Lane == -1) Lane = 0;
4921
4922       // Test if V1 is a SCALAR_TO_VECTOR.
4923       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4924         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4925       }
4926       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4927       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4928       // reaches it).
4929       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4930           !isa<ConstantSDNode>(V1.getOperand(0))) {
4931         bool IsScalarToVector = true;
4932         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4933           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4934             IsScalarToVector = false;
4935             break;
4936           }
4937         if (IsScalarToVector)
4938           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4939       }
4940       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4941                          DAG.getConstant(Lane, MVT::i32));
4942     }
4943
4944     bool ReverseVEXT;
4945     unsigned Imm;
4946     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4947       if (ReverseVEXT)
4948         std::swap(V1, V2);
4949       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4950                          DAG.getConstant(Imm, MVT::i32));
4951     }
4952
4953     if (isVREVMask(ShuffleMask, VT, 64))
4954       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4955     if (isVREVMask(ShuffleMask, VT, 32))
4956       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4957     if (isVREVMask(ShuffleMask, VT, 16))
4958       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4959
4960     if (V2->getOpcode() == ISD::UNDEF &&
4961         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4962       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4963                          DAG.getConstant(Imm, MVT::i32));
4964     }
4965
4966     // Check for Neon shuffles that modify both input vectors in place.
4967     // If both results are used, i.e., if there are two shuffles with the same
4968     // source operands and with masks corresponding to both results of one of
4969     // these operations, DAG memoization will ensure that a single node is
4970     // used for both shuffles.
4971     unsigned WhichResult;
4972     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4973       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4974                          V1, V2).getValue(WhichResult);
4975     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4976       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4977                          V1, V2).getValue(WhichResult);
4978     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4979       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4980                          V1, V2).getValue(WhichResult);
4981
4982     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4983       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4984                          V1, V1).getValue(WhichResult);
4985     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4986       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4987                          V1, V1).getValue(WhichResult);
4988     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4989       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4990                          V1, V1).getValue(WhichResult);
4991   }
4992
4993   // If the shuffle is not directly supported and it has 4 elements, use
4994   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4995   unsigned NumElts = VT.getVectorNumElements();
4996   if (NumElts == 4) {
4997     unsigned PFIndexes[4];
4998     for (unsigned i = 0; i != 4; ++i) {
4999       if (ShuffleMask[i] < 0)
5000         PFIndexes[i] = 8;
5001       else
5002         PFIndexes[i] = ShuffleMask[i];
5003     }
5004
5005     // Compute the index in the perfect shuffle table.
5006     unsigned PFTableIndex =
5007       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5008     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5009     unsigned Cost = (PFEntry >> 30);
5010
5011     if (Cost <= 4)
5012       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5013   }
5014
5015   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5016   if (EltSize >= 32) {
5017     // Do the expansion with floating-point types, since that is what the VFP
5018     // registers are defined to use, and since i64 is not legal.
5019     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5020     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5021     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5022     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5023     SmallVector<SDValue, 8> Ops;
5024     for (unsigned i = 0; i < NumElts; ++i) {
5025       if (ShuffleMask[i] < 0)
5026         Ops.push_back(DAG.getUNDEF(EltVT));
5027       else
5028         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5029                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5030                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5031                                                   MVT::i32)));
5032     }
5033     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5034     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5035   }
5036
5037   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5038     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5039
5040   if (VT == MVT::v8i8) {
5041     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5042     if (NewOp.getNode())
5043       return NewOp;
5044   }
5045
5046   return SDValue();
5047 }
5048
5049 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5050   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5051   SDValue Lane = Op.getOperand(2);
5052   if (!isa<ConstantSDNode>(Lane))
5053     return SDValue();
5054
5055   return Op;
5056 }
5057
5058 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5059   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5060   SDValue Lane = Op.getOperand(1);
5061   if (!isa<ConstantSDNode>(Lane))
5062     return SDValue();
5063
5064   SDValue Vec = Op.getOperand(0);
5065   if (Op.getValueType() == MVT::i32 &&
5066       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5067     DebugLoc dl = Op.getDebugLoc();
5068     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5069   }
5070
5071   return Op;
5072 }
5073
5074 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5075   // The only time a CONCAT_VECTORS operation can have legal types is when
5076   // two 64-bit vectors are concatenated to a 128-bit vector.
5077   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5078          "unexpected CONCAT_VECTORS");
5079   DebugLoc dl = Op.getDebugLoc();
5080   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5081   SDValue Op0 = Op.getOperand(0);
5082   SDValue Op1 = Op.getOperand(1);
5083   if (Op0.getOpcode() != ISD::UNDEF)
5084     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5085                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5086                       DAG.getIntPtrConstant(0));
5087   if (Op1.getOpcode() != ISD::UNDEF)
5088     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5089                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5090                       DAG.getIntPtrConstant(1));
5091   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5092 }
5093
5094 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5095 /// element has been zero/sign-extended, depending on the isSigned parameter,
5096 /// from an integer type half its size.
5097 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5098                                    bool isSigned) {
5099   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5100   EVT VT = N->getValueType(0);
5101   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5102     SDNode *BVN = N->getOperand(0).getNode();
5103     if (BVN->getValueType(0) != MVT::v4i32 ||
5104         BVN->getOpcode() != ISD::BUILD_VECTOR)
5105       return false;
5106     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5107     unsigned HiElt = 1 - LoElt;
5108     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5109     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5110     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5111     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5112     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5113       return false;
5114     if (isSigned) {
5115       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5116           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5117         return true;
5118     } else {
5119       if (Hi0->isNullValue() && Hi1->isNullValue())
5120         return true;
5121     }
5122     return false;
5123   }
5124
5125   if (N->getOpcode() != ISD::BUILD_VECTOR)
5126     return false;
5127
5128   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5129     SDNode *Elt = N->getOperand(i).getNode();
5130     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5131       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5132       unsigned HalfSize = EltSize / 2;
5133       if (isSigned) {
5134         if (!isIntN(HalfSize, C->getSExtValue()))
5135           return false;
5136       } else {
5137         if (!isUIntN(HalfSize, C->getZExtValue()))
5138           return false;
5139       }
5140       continue;
5141     }
5142     return false;
5143   }
5144
5145   return true;
5146 }
5147
5148 /// isSignExtended - Check if a node is a vector value that is sign-extended
5149 /// or a constant BUILD_VECTOR with sign-extended elements.
5150 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5151   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5152     return true;
5153   if (isExtendedBUILD_VECTOR(N, DAG, true))
5154     return true;
5155   return false;
5156 }
5157
5158 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5159 /// or a constant BUILD_VECTOR with zero-extended elements.
5160 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5161   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5162     return true;
5163   if (isExtendedBUILD_VECTOR(N, DAG, false))
5164     return true;
5165   return false;
5166 }
5167
5168 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5169 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5170 /// We insert the required extension here to get the vector to fill a D register.
5171 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5172                                             const EVT &OrigTy,
5173                                             const EVT &ExtTy,
5174                                             unsigned ExtOpcode) {
5175   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5176   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5177   // 64-bits we need to insert a new extension so that it will be 64-bits.
5178   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5179   if (OrigTy.getSizeInBits() >= 64)
5180     return N;
5181
5182   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5183   MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5184   EVT NewVT;
5185   switch (OrigSimpleTy) {
5186   default: llvm_unreachable("Unexpected Orig Vector Type");
5187   case MVT::v2i8:
5188   case MVT::v2i16:
5189     NewVT = MVT::v2i32;
5190     break;
5191   case MVT::v4i8:
5192     NewVT = MVT::v4i16;
5193     break;
5194   }
5195   return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5196 }
5197
5198 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5199 /// does not do any sign/zero extension. If the original vector is less
5200 /// than 64 bits, an appropriate extension will be added after the load to
5201 /// reach a total size of 64 bits. We have to add the extension separately
5202 /// because ARM does not have a sign/zero extending load for vectors.
5203 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5204   SDValue NonExtendingLoad =
5205     DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5206                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5207                 LD->isNonTemporal(), LD->isInvariant(),
5208                 LD->getAlignment());
5209   unsigned ExtOp = 0;
5210   switch (LD->getExtensionType()) {
5211   default: llvm_unreachable("Unexpected LoadExtType");
5212   case ISD::EXTLOAD:
5213   case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5214   case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5215   }
5216   MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5217   MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5218   return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5219                                       MemType, ExtType, ExtOp);
5220 }
5221
5222 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5223 /// extending load, or BUILD_VECTOR with extended elements, return the
5224 /// unextended value. The unextended vector should be 64 bits so that it can
5225 /// be used as an operand to a VMULL instruction. If the original vector size
5226 /// before extension is less than 64 bits we add a an extension to resize
5227 /// the vector to 64 bits.
5228 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5229   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5230     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5231                                         N->getOperand(0)->getValueType(0),
5232                                         N->getValueType(0),
5233                                         N->getOpcode());
5234
5235   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5236     return SkipLoadExtensionForVMULL(LD, DAG);
5237
5238   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5239   // have been legalized as a BITCAST from v4i32.
5240   if (N->getOpcode() == ISD::BITCAST) {
5241     SDNode *BVN = N->getOperand(0).getNode();
5242     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5243            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5244     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5245     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5246                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5247   }
5248   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5249   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5250   EVT VT = N->getValueType(0);
5251   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5252   unsigned NumElts = VT.getVectorNumElements();
5253   MVT TruncVT = MVT::getIntegerVT(EltSize);
5254   SmallVector<SDValue, 8> Ops;
5255   for (unsigned i = 0; i != NumElts; ++i) {
5256     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5257     const APInt &CInt = C->getAPIntValue();
5258     // Element types smaller than 32 bits are not legal, so use i32 elements.
5259     // The values are implicitly truncated so sext vs. zext doesn't matter.
5260     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5261   }
5262   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5263                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5264 }
5265
5266 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5267   unsigned Opcode = N->getOpcode();
5268   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5269     SDNode *N0 = N->getOperand(0).getNode();
5270     SDNode *N1 = N->getOperand(1).getNode();
5271     return N0->hasOneUse() && N1->hasOneUse() &&
5272       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5273   }
5274   return false;
5275 }
5276
5277 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5278   unsigned Opcode = N->getOpcode();
5279   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5280     SDNode *N0 = N->getOperand(0).getNode();
5281     SDNode *N1 = N->getOperand(1).getNode();
5282     return N0->hasOneUse() && N1->hasOneUse() &&
5283       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5284   }
5285   return false;
5286 }
5287
5288 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5289   // Multiplications are only custom-lowered for 128-bit vectors so that
5290   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5291   EVT VT = Op.getValueType();
5292   assert(VT.is128BitVector() && VT.isInteger() &&
5293          "unexpected type for custom-lowering ISD::MUL");
5294   SDNode *N0 = Op.getOperand(0).getNode();
5295   SDNode *N1 = Op.getOperand(1).getNode();
5296   unsigned NewOpc = 0;
5297   bool isMLA = false;
5298   bool isN0SExt = isSignExtended(N0, DAG);
5299   bool isN1SExt = isSignExtended(N1, DAG);
5300   if (isN0SExt && isN1SExt)
5301     NewOpc = ARMISD::VMULLs;
5302   else {
5303     bool isN0ZExt = isZeroExtended(N0, DAG);
5304     bool isN1ZExt = isZeroExtended(N1, DAG);
5305     if (isN0ZExt && isN1ZExt)
5306       NewOpc = ARMISD::VMULLu;
5307     else if (isN1SExt || isN1ZExt) {
5308       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5309       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5310       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5311         NewOpc = ARMISD::VMULLs;
5312         isMLA = true;
5313       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5314         NewOpc = ARMISD::VMULLu;
5315         isMLA = true;
5316       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5317         std::swap(N0, N1);
5318         NewOpc = ARMISD::VMULLu;
5319         isMLA = true;
5320       }
5321     }
5322
5323     if (!NewOpc) {
5324       if (VT == MVT::v2i64)
5325         // Fall through to expand this.  It is not legal.
5326         return SDValue();
5327       else
5328         // Other vector multiplications are legal.
5329         return Op;
5330     }
5331   }
5332
5333   // Legalize to a VMULL instruction.
5334   DebugLoc DL = Op.getDebugLoc();
5335   SDValue Op0;
5336   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5337   if (!isMLA) {
5338     Op0 = SkipExtensionForVMULL(N0, DAG);
5339     assert(Op0.getValueType().is64BitVector() &&
5340            Op1.getValueType().is64BitVector() &&
5341            "unexpected types for extended operands to VMULL");
5342     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5343   }
5344
5345   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5346   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5347   //   vmull q0, d4, d6
5348   //   vmlal q0, d5, d6
5349   // is faster than
5350   //   vaddl q0, d4, d5
5351   //   vmovl q1, d6
5352   //   vmul  q0, q0, q1
5353   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5354   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5355   EVT Op1VT = Op1.getValueType();
5356   return DAG.getNode(N0->getOpcode(), DL, VT,
5357                      DAG.getNode(NewOpc, DL, VT,
5358                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5359                      DAG.getNode(NewOpc, DL, VT,
5360                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5361 }
5362
5363 static SDValue
5364 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5365   // Convert to float
5366   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5367   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5368   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5369   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5370   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5371   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5372   // Get reciprocal estimate.
5373   // float4 recip = vrecpeq_f32(yf);
5374   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5375                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5376   // Because char has a smaller range than uchar, we can actually get away
5377   // without any newton steps.  This requires that we use a weird bias
5378   // of 0xb000, however (again, this has been exhaustively tested).
5379   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5380   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5381   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5382   Y = DAG.getConstant(0xb000, MVT::i32);
5383   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5384   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5385   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5386   // Convert back to short.
5387   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5388   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5389   return X;
5390 }
5391
5392 static SDValue
5393 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5394   SDValue N2;
5395   // Convert to float.
5396   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5397   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5398   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5399   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5400   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5401   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5402
5403   // Use reciprocal estimate and one refinement step.
5404   // float4 recip = vrecpeq_f32(yf);
5405   // recip *= vrecpsq_f32(yf, recip);
5406   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5407                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5408   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5409                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5410                    N1, N2);
5411   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5412   // Because short has a smaller range than ushort, we can actually get away
5413   // with only a single newton step.  This requires that we use a weird bias
5414   // of 89, however (again, this has been exhaustively tested).
5415   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5416   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5417   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5418   N1 = DAG.getConstant(0x89, MVT::i32);
5419   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5420   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5421   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5422   // Convert back to integer and return.
5423   // return vmovn_s32(vcvt_s32_f32(result));
5424   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5425   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5426   return N0;
5427 }
5428
5429 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5430   EVT VT = Op.getValueType();
5431   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5432          "unexpected type for custom-lowering ISD::SDIV");
5433
5434   DebugLoc dl = Op.getDebugLoc();
5435   SDValue N0 = Op.getOperand(0);
5436   SDValue N1 = Op.getOperand(1);
5437   SDValue N2, N3;
5438
5439   if (VT == MVT::v8i8) {
5440     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5441     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5442
5443     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5444                      DAG.getIntPtrConstant(4));
5445     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5446                      DAG.getIntPtrConstant(4));
5447     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5448                      DAG.getIntPtrConstant(0));
5449     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5450                      DAG.getIntPtrConstant(0));
5451
5452     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5453     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5454
5455     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5456     N0 = LowerCONCAT_VECTORS(N0, DAG);
5457
5458     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5459     return N0;
5460   }
5461   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5462 }
5463
5464 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5465   EVT VT = Op.getValueType();
5466   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5467          "unexpected type for custom-lowering ISD::UDIV");
5468
5469   DebugLoc dl = Op.getDebugLoc();
5470   SDValue N0 = Op.getOperand(0);
5471   SDValue N1 = Op.getOperand(1);
5472   SDValue N2, N3;
5473
5474   if (VT == MVT::v8i8) {
5475     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5476     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5477
5478     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5479                      DAG.getIntPtrConstant(4));
5480     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5481                      DAG.getIntPtrConstant(4));
5482     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5483                      DAG.getIntPtrConstant(0));
5484     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5485                      DAG.getIntPtrConstant(0));
5486
5487     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5488     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5489
5490     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5491     N0 = LowerCONCAT_VECTORS(N0, DAG);
5492
5493     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5494                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5495                      N0);
5496     return N0;
5497   }
5498
5499   // v4i16 sdiv ... Convert to float.
5500   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5501   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5502   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5503   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5504   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5505   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5506
5507   // Use reciprocal estimate and two refinement steps.
5508   // float4 recip = vrecpeq_f32(yf);
5509   // recip *= vrecpsq_f32(yf, recip);
5510   // recip *= vrecpsq_f32(yf, recip);
5511   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5512                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5513   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5514                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5515                    BN1, N2);
5516   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5517   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5518                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5519                    BN1, N2);
5520   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5521   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5522   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5523   // and that it will never cause us to return an answer too large).
5524   // float4 result = as_float4(as_int4(xf*recip) + 2);
5525   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5526   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5527   N1 = DAG.getConstant(2, MVT::i32);
5528   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5529   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5530   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5531   // Convert back to integer and return.
5532   // return vmovn_u32(vcvt_s32_f32(result));
5533   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5534   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5535   return N0;
5536 }
5537
5538 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5539   EVT VT = Op.getNode()->getValueType(0);
5540   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5541
5542   unsigned Opc;
5543   bool ExtraOp = false;
5544   switch (Op.getOpcode()) {
5545   default: llvm_unreachable("Invalid code");
5546   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5547   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5548   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5549   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5550   }
5551
5552   if (!ExtraOp)
5553     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5554                        Op.getOperand(1));
5555   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5556                      Op.getOperand(1), Op.getOperand(2));
5557 }
5558
5559 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5560   // Monotonic load/store is legal for all targets
5561   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5562     return Op;
5563
5564   // Aquire/Release load/store is not legal for targets without a
5565   // dmb or equivalent available.
5566   return SDValue();
5567 }
5568
5569
5570 static void
5571 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5572                     SelectionDAG &DAG, unsigned NewOp) {
5573   DebugLoc dl = Node->getDebugLoc();
5574   assert (Node->getValueType(0) == MVT::i64 &&
5575           "Only know how to expand i64 atomics");
5576
5577   SmallVector<SDValue, 6> Ops;
5578   Ops.push_back(Node->getOperand(0)); // Chain
5579   Ops.push_back(Node->getOperand(1)); // Ptr
5580   // Low part of Val1
5581   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5582                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5583   // High part of Val1
5584   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5585                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5586   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5587     // High part of Val1
5588     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5589                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5590     // High part of Val2
5591     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5592                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5593   }
5594   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5595   SDValue Result =
5596     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5597                             cast<MemSDNode>(Node)->getMemOperand());
5598   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5599   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5600   Results.push_back(Result.getValue(2));
5601 }
5602
5603 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5604   switch (Op.getOpcode()) {
5605   default: llvm_unreachable("Don't know how to custom lower this!");
5606   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5607   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5608   case ISD::GlobalAddress:
5609     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5610       LowerGlobalAddressELF(Op, DAG);
5611   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5612   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5613   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5614   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5615   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5616   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5617   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5618   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5619   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5620   case ISD::SINT_TO_FP:
5621   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5622   case ISD::FP_TO_SINT:
5623   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5624   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5625   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5626   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5627   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5628   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5629   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5630   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5631                                                                Subtarget);
5632   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5633   case ISD::SHL:
5634   case ISD::SRL:
5635   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5636   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5637   case ISD::SRL_PARTS:
5638   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5639   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5640   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5641   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5642   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5643   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5644   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5645   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5646   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5647   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5648   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5649   case ISD::MUL:           return LowerMUL(Op, DAG);
5650   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5651   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5652   case ISD::ADDC:
5653   case ISD::ADDE:
5654   case ISD::SUBC:
5655   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5656   case ISD::ATOMIC_LOAD:
5657   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5658   }
5659 }
5660
5661 /// ReplaceNodeResults - Replace the results of node with an illegal result
5662 /// type with new values built out of custom code.
5663 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5664                                            SmallVectorImpl<SDValue>&Results,
5665                                            SelectionDAG &DAG) const {
5666   SDValue Res;
5667   switch (N->getOpcode()) {
5668   default:
5669     llvm_unreachable("Don't know how to custom expand this!");
5670   case ISD::BITCAST:
5671     Res = ExpandBITCAST(N, DAG);
5672     break;
5673   case ISD::SIGN_EXTEND:
5674   case ISD::ZERO_EXTEND:
5675     Res = ExpandVectorExtension(N, DAG);
5676     break;
5677   case ISD::SRL:
5678   case ISD::SRA:
5679     Res = Expand64BitShift(N, DAG, Subtarget);
5680     break;
5681   case ISD::ATOMIC_LOAD_ADD:
5682     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5683     return;
5684   case ISD::ATOMIC_LOAD_AND:
5685     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5686     return;
5687   case ISD::ATOMIC_LOAD_NAND:
5688     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5689     return;
5690   case ISD::ATOMIC_LOAD_OR:
5691     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5692     return;
5693   case ISD::ATOMIC_LOAD_SUB:
5694     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5695     return;
5696   case ISD::ATOMIC_LOAD_XOR:
5697     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5698     return;
5699   case ISD::ATOMIC_SWAP:
5700     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5701     return;
5702   case ISD::ATOMIC_CMP_SWAP:
5703     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5704     return;
5705   case ISD::ATOMIC_LOAD_MIN:
5706     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5707     return;
5708   case ISD::ATOMIC_LOAD_UMIN:
5709     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5710     return;
5711   case ISD::ATOMIC_LOAD_MAX:
5712     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5713     return;
5714   case ISD::ATOMIC_LOAD_UMAX:
5715     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5716     return;
5717   }
5718   if (Res.getNode())
5719     Results.push_back(Res);
5720 }
5721
5722 //===----------------------------------------------------------------------===//
5723 //                           ARM Scheduler Hooks
5724 //===----------------------------------------------------------------------===//
5725
5726 MachineBasicBlock *
5727 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5728                                      MachineBasicBlock *BB,
5729                                      unsigned Size) const {
5730   unsigned dest    = MI->getOperand(0).getReg();
5731   unsigned ptr     = MI->getOperand(1).getReg();
5732   unsigned oldval  = MI->getOperand(2).getReg();
5733   unsigned newval  = MI->getOperand(3).getReg();
5734   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5735   DebugLoc dl = MI->getDebugLoc();
5736   bool isThumb2 = Subtarget->isThumb2();
5737
5738   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5739   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5740     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5741     (const TargetRegisterClass*)&ARM::GPRRegClass);
5742
5743   if (isThumb2) {
5744     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5745     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5746     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5747   }
5748
5749   unsigned ldrOpc, strOpc;
5750   switch (Size) {
5751   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5752   case 1:
5753     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5754     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5755     break;
5756   case 2:
5757     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5758     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5759     break;
5760   case 4:
5761     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5762     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5763     break;
5764   }
5765
5766   MachineFunction *MF = BB->getParent();
5767   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5768   MachineFunction::iterator It = BB;
5769   ++It; // insert the new blocks after the current block
5770
5771   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5772   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5773   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5774   MF->insert(It, loop1MBB);
5775   MF->insert(It, loop2MBB);
5776   MF->insert(It, exitMBB);
5777
5778   // Transfer the remainder of BB and its successor edges to exitMBB.
5779   exitMBB->splice(exitMBB->begin(), BB,
5780                   llvm::next(MachineBasicBlock::iterator(MI)),
5781                   BB->end());
5782   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5783
5784   //  thisMBB:
5785   //   ...
5786   //   fallthrough --> loop1MBB
5787   BB->addSuccessor(loop1MBB);
5788
5789   // loop1MBB:
5790   //   ldrex dest, [ptr]
5791   //   cmp dest, oldval
5792   //   bne exitMBB
5793   BB = loop1MBB;
5794   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5795   if (ldrOpc == ARM::t2LDREX)
5796     MIB.addImm(0);
5797   AddDefaultPred(MIB);
5798   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5799                  .addReg(dest).addReg(oldval));
5800   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5801     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5802   BB->addSuccessor(loop2MBB);
5803   BB->addSuccessor(exitMBB);
5804
5805   // loop2MBB:
5806   //   strex scratch, newval, [ptr]
5807   //   cmp scratch, #0
5808   //   bne loop1MBB
5809   BB = loop2MBB;
5810   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5811   if (strOpc == ARM::t2STREX)
5812     MIB.addImm(0);
5813   AddDefaultPred(MIB);
5814   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5815                  .addReg(scratch).addImm(0));
5816   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5817     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5818   BB->addSuccessor(loop1MBB);
5819   BB->addSuccessor(exitMBB);
5820
5821   //  exitMBB:
5822   //   ...
5823   BB = exitMBB;
5824
5825   MI->eraseFromParent();   // The instruction is gone now.
5826
5827   return BB;
5828 }
5829
5830 MachineBasicBlock *
5831 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5832                                     unsigned Size, unsigned BinOpcode) const {
5833   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5834   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5835
5836   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5837   MachineFunction *MF = BB->getParent();
5838   MachineFunction::iterator It = BB;
5839   ++It;
5840
5841   unsigned dest = MI->getOperand(0).getReg();
5842   unsigned ptr = MI->getOperand(1).getReg();
5843   unsigned incr = MI->getOperand(2).getReg();
5844   DebugLoc dl = MI->getDebugLoc();
5845   bool isThumb2 = Subtarget->isThumb2();
5846
5847   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5848   if (isThumb2) {
5849     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5850     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5851   }
5852
5853   unsigned ldrOpc, strOpc;
5854   switch (Size) {
5855   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5856   case 1:
5857     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5858     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5859     break;
5860   case 2:
5861     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5862     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5863     break;
5864   case 4:
5865     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5866     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5867     break;
5868   }
5869
5870   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5871   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5872   MF->insert(It, loopMBB);
5873   MF->insert(It, exitMBB);
5874
5875   // Transfer the remainder of BB and its successor edges to exitMBB.
5876   exitMBB->splice(exitMBB->begin(), BB,
5877                   llvm::next(MachineBasicBlock::iterator(MI)),
5878                   BB->end());
5879   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5880
5881   const TargetRegisterClass *TRC = isThumb2 ?
5882     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5883     (const TargetRegisterClass*)&ARM::GPRRegClass;
5884   unsigned scratch = MRI.createVirtualRegister(TRC);
5885   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5886
5887   //  thisMBB:
5888   //   ...
5889   //   fallthrough --> loopMBB
5890   BB->addSuccessor(loopMBB);
5891
5892   //  loopMBB:
5893   //   ldrex dest, ptr
5894   //   <binop> scratch2, dest, incr
5895   //   strex scratch, scratch2, ptr
5896   //   cmp scratch, #0
5897   //   bne- loopMBB
5898   //   fallthrough --> exitMBB
5899   BB = loopMBB;
5900   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5901   if (ldrOpc == ARM::t2LDREX)
5902     MIB.addImm(0);
5903   AddDefaultPred(MIB);
5904   if (BinOpcode) {
5905     // operand order needs to go the other way for NAND
5906     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5907       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5908                      addReg(incr).addReg(dest)).addReg(0);
5909     else
5910       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5911                      addReg(dest).addReg(incr)).addReg(0);
5912   }
5913
5914   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5915   if (strOpc == ARM::t2STREX)
5916     MIB.addImm(0);
5917   AddDefaultPred(MIB);
5918   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5919                  .addReg(scratch).addImm(0));
5920   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5921     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5922
5923   BB->addSuccessor(loopMBB);
5924   BB->addSuccessor(exitMBB);
5925
5926   //  exitMBB:
5927   //   ...
5928   BB = exitMBB;
5929
5930   MI->eraseFromParent();   // The instruction is gone now.
5931
5932   return BB;
5933 }
5934
5935 MachineBasicBlock *
5936 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5937                                           MachineBasicBlock *BB,
5938                                           unsigned Size,
5939                                           bool signExtend,
5940                                           ARMCC::CondCodes Cond) const {
5941   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5942
5943   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5944   MachineFunction *MF = BB->getParent();
5945   MachineFunction::iterator It = BB;
5946   ++It;
5947
5948   unsigned dest = MI->getOperand(0).getReg();
5949   unsigned ptr = MI->getOperand(1).getReg();
5950   unsigned incr = MI->getOperand(2).getReg();
5951   unsigned oldval = dest;
5952   DebugLoc dl = MI->getDebugLoc();
5953   bool isThumb2 = Subtarget->isThumb2();
5954
5955   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5956   if (isThumb2) {
5957     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5958     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5959   }
5960
5961   unsigned ldrOpc, strOpc, extendOpc;
5962   switch (Size) {
5963   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5964   case 1:
5965     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5966     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5967     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5968     break;
5969   case 2:
5970     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5971     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5972     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5973     break;
5974   case 4:
5975     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5976     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5977     extendOpc = 0;
5978     break;
5979   }
5980
5981   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5982   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5983   MF->insert(It, loopMBB);
5984   MF->insert(It, exitMBB);
5985
5986   // Transfer the remainder of BB and its successor edges to exitMBB.
5987   exitMBB->splice(exitMBB->begin(), BB,
5988                   llvm::next(MachineBasicBlock::iterator(MI)),
5989                   BB->end());
5990   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5991
5992   const TargetRegisterClass *TRC = isThumb2 ?
5993     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5994     (const TargetRegisterClass*)&ARM::GPRRegClass;
5995   unsigned scratch = MRI.createVirtualRegister(TRC);
5996   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5997
5998   //  thisMBB:
5999   //   ...
6000   //   fallthrough --> loopMBB
6001   BB->addSuccessor(loopMBB);
6002
6003   //  loopMBB:
6004   //   ldrex dest, ptr
6005   //   (sign extend dest, if required)
6006   //   cmp dest, incr
6007   //   cmov.cond scratch2, incr, dest
6008   //   strex scratch, scratch2, ptr
6009   //   cmp scratch, #0
6010   //   bne- loopMBB
6011   //   fallthrough --> exitMBB
6012   BB = loopMBB;
6013   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6014   if (ldrOpc == ARM::t2LDREX)
6015     MIB.addImm(0);
6016   AddDefaultPred(MIB);
6017
6018   // Sign extend the value, if necessary.
6019   if (signExtend && extendOpc) {
6020     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6021     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6022                      .addReg(dest)
6023                      .addImm(0));
6024   }
6025
6026   // Build compare and cmov instructions.
6027   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6028                  .addReg(oldval).addReg(incr));
6029   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6030          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6031
6032   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6033   if (strOpc == ARM::t2STREX)
6034     MIB.addImm(0);
6035   AddDefaultPred(MIB);
6036   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6037                  .addReg(scratch).addImm(0));
6038   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6039     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6040
6041   BB->addSuccessor(loopMBB);
6042   BB->addSuccessor(exitMBB);
6043
6044   //  exitMBB:
6045   //   ...
6046   BB = exitMBB;
6047
6048   MI->eraseFromParent();   // The instruction is gone now.
6049
6050   return BB;
6051 }
6052
6053 MachineBasicBlock *
6054 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6055                                       unsigned Op1, unsigned Op2,
6056                                       bool NeedsCarry, bool IsCmpxchg,
6057                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6058   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6059   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6060
6061   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6062   MachineFunction *MF = BB->getParent();
6063   MachineFunction::iterator It = BB;
6064   ++It;
6065
6066   unsigned destlo = MI->getOperand(0).getReg();
6067   unsigned desthi = MI->getOperand(1).getReg();
6068   unsigned ptr = MI->getOperand(2).getReg();
6069   unsigned vallo = MI->getOperand(3).getReg();
6070   unsigned valhi = MI->getOperand(4).getReg();
6071   DebugLoc dl = MI->getDebugLoc();
6072   bool isThumb2 = Subtarget->isThumb2();
6073
6074   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6075   if (isThumb2) {
6076     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6077     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6078     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6079   }
6080
6081   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6082   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6083   if (IsCmpxchg || IsMinMax)
6084     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6085   if (IsCmpxchg)
6086     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6087   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6088
6089   MF->insert(It, loopMBB);
6090   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6091   if (IsCmpxchg) MF->insert(It, cont2BB);
6092   MF->insert(It, exitMBB);
6093
6094   // Transfer the remainder of BB and its successor edges to exitMBB.
6095   exitMBB->splice(exitMBB->begin(), BB,
6096                   llvm::next(MachineBasicBlock::iterator(MI)),
6097                   BB->end());
6098   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6099
6100   const TargetRegisterClass *TRC = isThumb2 ?
6101     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6102     (const TargetRegisterClass*)&ARM::GPRRegClass;
6103   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6104
6105   //  thisMBB:
6106   //   ...
6107   //   fallthrough --> loopMBB
6108   BB->addSuccessor(loopMBB);
6109
6110   //  loopMBB:
6111   //   ldrexd r2, r3, ptr
6112   //   <binopa> r0, r2, incr
6113   //   <binopb> r1, r3, incr
6114   //   strexd storesuccess, r0, r1, ptr
6115   //   cmp storesuccess, #0
6116   //   bne- loopMBB
6117   //   fallthrough --> exitMBB
6118   BB = loopMBB;
6119
6120   // Load
6121   if (isThumb2) {
6122     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6123                    .addReg(destlo, RegState::Define)
6124                    .addReg(desthi, RegState::Define)
6125                    .addReg(ptr));
6126   } else {
6127     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6128     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6129                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6130     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6131     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6132       .addReg(GPRPair0, 0, ARM::gsub_0);
6133     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6134       .addReg(GPRPair0, 0, ARM::gsub_1);
6135   }
6136
6137   unsigned StoreLo, StoreHi;
6138   if (IsCmpxchg) {
6139     // Add early exit
6140     for (unsigned i = 0; i < 2; i++) {
6141       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6142                                                          ARM::CMPrr))
6143                      .addReg(i == 0 ? destlo : desthi)
6144                      .addReg(i == 0 ? vallo : valhi));
6145       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6146         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6147       BB->addSuccessor(exitMBB);
6148       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6149       BB = (i == 0 ? contBB : cont2BB);
6150     }
6151
6152     // Copy to physregs for strexd
6153     StoreLo = MI->getOperand(5).getReg();
6154     StoreHi = MI->getOperand(6).getReg();
6155   } else if (Op1) {
6156     // Perform binary operation
6157     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6158     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6159                    .addReg(destlo).addReg(vallo))
6160         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6161     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6162     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6163                    .addReg(desthi).addReg(valhi))
6164         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6165
6166     StoreLo = tmpRegLo;
6167     StoreHi = tmpRegHi;
6168   } else {
6169     // Copy to physregs for strexd
6170     StoreLo = vallo;
6171     StoreHi = valhi;
6172   }
6173   if (IsMinMax) {
6174     // Compare and branch to exit block.
6175     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6176       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6177     BB->addSuccessor(exitMBB);
6178     BB->addSuccessor(contBB);
6179     BB = contBB;
6180     StoreLo = vallo;
6181     StoreHi = valhi;
6182   }
6183
6184   // Store
6185   if (isThumb2) {
6186     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6187                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6188   } else {
6189     // Marshal a pair...
6190     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6191     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6192     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6193     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6194     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6195       .addReg(UndefPair)
6196       .addReg(StoreLo)
6197       .addImm(ARM::gsub_0);
6198     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6199       .addReg(r1)
6200       .addReg(StoreHi)
6201       .addImm(ARM::gsub_1);
6202
6203     // ...and store it
6204     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6205                    .addReg(StorePair).addReg(ptr));
6206   }
6207   // Cmp+jump
6208   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6209                  .addReg(storesuccess).addImm(0));
6210   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6211     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6212
6213   BB->addSuccessor(loopMBB);
6214   BB->addSuccessor(exitMBB);
6215
6216   //  exitMBB:
6217   //   ...
6218   BB = exitMBB;
6219
6220   MI->eraseFromParent();   // The instruction is gone now.
6221
6222   return BB;
6223 }
6224
6225 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6226 /// registers the function context.
6227 void ARMTargetLowering::
6228 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6229                        MachineBasicBlock *DispatchBB, int FI) const {
6230   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6231   DebugLoc dl = MI->getDebugLoc();
6232   MachineFunction *MF = MBB->getParent();
6233   MachineRegisterInfo *MRI = &MF->getRegInfo();
6234   MachineConstantPool *MCP = MF->getConstantPool();
6235   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6236   const Function *F = MF->getFunction();
6237
6238   bool isThumb = Subtarget->isThumb();
6239   bool isThumb2 = Subtarget->isThumb2();
6240
6241   unsigned PCLabelId = AFI->createPICLabelUId();
6242   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6243   ARMConstantPoolValue *CPV =
6244     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6245   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6246
6247   const TargetRegisterClass *TRC = isThumb ?
6248     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6249     (const TargetRegisterClass*)&ARM::GPRRegClass;
6250
6251   // Grab constant pool and fixed stack memory operands.
6252   MachineMemOperand *CPMMO =
6253     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6254                              MachineMemOperand::MOLoad, 4, 4);
6255
6256   MachineMemOperand *FIMMOSt =
6257     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6258                              MachineMemOperand::MOStore, 4, 4);
6259
6260   // Load the address of the dispatch MBB into the jump buffer.
6261   if (isThumb2) {
6262     // Incoming value: jbuf
6263     //   ldr.n  r5, LCPI1_1
6264     //   orr    r5, r5, #1
6265     //   add    r5, pc
6266     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6267     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6268     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6269                    .addConstantPoolIndex(CPI)
6270                    .addMemOperand(CPMMO));
6271     // Set the low bit because of thumb mode.
6272     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6273     AddDefaultCC(
6274       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6275                      .addReg(NewVReg1, RegState::Kill)
6276                      .addImm(0x01)));
6277     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6278     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6279       .addReg(NewVReg2, RegState::Kill)
6280       .addImm(PCLabelId);
6281     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6282                    .addReg(NewVReg3, RegState::Kill)
6283                    .addFrameIndex(FI)
6284                    .addImm(36)  // &jbuf[1] :: pc
6285                    .addMemOperand(FIMMOSt));
6286   } else if (isThumb) {
6287     // Incoming value: jbuf
6288     //   ldr.n  r1, LCPI1_4
6289     //   add    r1, pc
6290     //   mov    r2, #1
6291     //   orrs   r1, r2
6292     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6293     //   str    r1, [r2]
6294     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6295     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6296                    .addConstantPoolIndex(CPI)
6297                    .addMemOperand(CPMMO));
6298     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6299     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6300       .addReg(NewVReg1, RegState::Kill)
6301       .addImm(PCLabelId);
6302     // Set the low bit because of thumb mode.
6303     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6304     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6305                    .addReg(ARM::CPSR, RegState::Define)
6306                    .addImm(1));
6307     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6308     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6309                    .addReg(ARM::CPSR, RegState::Define)
6310                    .addReg(NewVReg2, RegState::Kill)
6311                    .addReg(NewVReg3, RegState::Kill));
6312     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6313     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6314                    .addFrameIndex(FI)
6315                    .addImm(36)); // &jbuf[1] :: pc
6316     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6317                    .addReg(NewVReg4, RegState::Kill)
6318                    .addReg(NewVReg5, RegState::Kill)
6319                    .addImm(0)
6320                    .addMemOperand(FIMMOSt));
6321   } else {
6322     // Incoming value: jbuf
6323     //   ldr  r1, LCPI1_1
6324     //   add  r1, pc, r1
6325     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6326     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6327     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6328                    .addConstantPoolIndex(CPI)
6329                    .addImm(0)
6330                    .addMemOperand(CPMMO));
6331     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6332     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6333                    .addReg(NewVReg1, RegState::Kill)
6334                    .addImm(PCLabelId));
6335     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6336                    .addReg(NewVReg2, RegState::Kill)
6337                    .addFrameIndex(FI)
6338                    .addImm(36)  // &jbuf[1] :: pc
6339                    .addMemOperand(FIMMOSt));
6340   }
6341 }
6342
6343 MachineBasicBlock *ARMTargetLowering::
6344 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6345   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6346   DebugLoc dl = MI->getDebugLoc();
6347   MachineFunction *MF = MBB->getParent();
6348   MachineRegisterInfo *MRI = &MF->getRegInfo();
6349   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6350   MachineFrameInfo *MFI = MF->getFrameInfo();
6351   int FI = MFI->getFunctionContextIndex();
6352
6353   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6354     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6355     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6356
6357   // Get a mapping of the call site numbers to all of the landing pads they're
6358   // associated with.
6359   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6360   unsigned MaxCSNum = 0;
6361   MachineModuleInfo &MMI = MF->getMMI();
6362   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6363        ++BB) {
6364     if (!BB->isLandingPad()) continue;
6365
6366     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6367     // pad.
6368     for (MachineBasicBlock::iterator
6369            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6370       if (!II->isEHLabel()) continue;
6371
6372       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6373       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6374
6375       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6376       for (SmallVectorImpl<unsigned>::iterator
6377              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6378            CSI != CSE; ++CSI) {
6379         CallSiteNumToLPad[*CSI].push_back(BB);
6380         MaxCSNum = std::max(MaxCSNum, *CSI);
6381       }
6382       break;
6383     }
6384   }
6385
6386   // Get an ordered list of the machine basic blocks for the jump table.
6387   std::vector<MachineBasicBlock*> LPadList;
6388   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6389   LPadList.reserve(CallSiteNumToLPad.size());
6390   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6391     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6392     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6393            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6394       LPadList.push_back(*II);
6395       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6396     }
6397   }
6398
6399   assert(!LPadList.empty() &&
6400          "No landing pad destinations for the dispatch jump table!");
6401
6402   // Create the jump table and associated information.
6403   MachineJumpTableInfo *JTI =
6404     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6405   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6406   unsigned UId = AFI->createJumpTableUId();
6407   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6408
6409   // Create the MBBs for the dispatch code.
6410
6411   // Shove the dispatch's address into the return slot in the function context.
6412   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6413   DispatchBB->setIsLandingPad();
6414
6415   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6416   unsigned trap_opcode;
6417   if (Subtarget->isThumb())
6418     trap_opcode = ARM::tTRAP;
6419   else
6420     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6421
6422   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6423   DispatchBB->addSuccessor(TrapBB);
6424
6425   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6426   DispatchBB->addSuccessor(DispContBB);
6427
6428   // Insert and MBBs.
6429   MF->insert(MF->end(), DispatchBB);
6430   MF->insert(MF->end(), DispContBB);
6431   MF->insert(MF->end(), TrapBB);
6432
6433   // Insert code into the entry block that creates and registers the function
6434   // context.
6435   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6436
6437   MachineMemOperand *FIMMOLd =
6438     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6439                              MachineMemOperand::MOLoad |
6440                              MachineMemOperand::MOVolatile, 4, 4);
6441
6442   MachineInstrBuilder MIB;
6443   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6444
6445   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6446   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6447
6448   // Add a register mask with no preserved registers.  This results in all
6449   // registers being marked as clobbered.
6450   MIB.addRegMask(RI.getNoPreservedMask());
6451
6452   unsigned NumLPads = LPadList.size();
6453   if (Subtarget->isThumb2()) {
6454     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6455     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6456                    .addFrameIndex(FI)
6457                    .addImm(4)
6458                    .addMemOperand(FIMMOLd));
6459
6460     if (NumLPads < 256) {
6461       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6462                      .addReg(NewVReg1)
6463                      .addImm(LPadList.size()));
6464     } else {
6465       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6466       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6467                      .addImm(NumLPads & 0xFFFF));
6468
6469       unsigned VReg2 = VReg1;
6470       if ((NumLPads & 0xFFFF0000) != 0) {
6471         VReg2 = MRI->createVirtualRegister(TRC);
6472         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6473                        .addReg(VReg1)
6474                        .addImm(NumLPads >> 16));
6475       }
6476
6477       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6478                      .addReg(NewVReg1)
6479                      .addReg(VReg2));
6480     }
6481
6482     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6483       .addMBB(TrapBB)
6484       .addImm(ARMCC::HI)
6485       .addReg(ARM::CPSR);
6486
6487     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6488     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6489                    .addJumpTableIndex(MJTI)
6490                    .addImm(UId));
6491
6492     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6493     AddDefaultCC(
6494       AddDefaultPred(
6495         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6496         .addReg(NewVReg3, RegState::Kill)
6497         .addReg(NewVReg1)
6498         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6499
6500     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6501       .addReg(NewVReg4, RegState::Kill)
6502       .addReg(NewVReg1)
6503       .addJumpTableIndex(MJTI)
6504       .addImm(UId);
6505   } else if (Subtarget->isThumb()) {
6506     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6507     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6508                    .addFrameIndex(FI)
6509                    .addImm(1)
6510                    .addMemOperand(FIMMOLd));
6511
6512     if (NumLPads < 256) {
6513       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6514                      .addReg(NewVReg1)
6515                      .addImm(NumLPads));
6516     } else {
6517       MachineConstantPool *ConstantPool = MF->getConstantPool();
6518       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6519       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6520
6521       // MachineConstantPool wants an explicit alignment.
6522       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6523       if (Align == 0)
6524         Align = getDataLayout()->getTypeAllocSize(C->getType());
6525       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6526
6527       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6528       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6529                      .addReg(VReg1, RegState::Define)
6530                      .addConstantPoolIndex(Idx));
6531       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6532                      .addReg(NewVReg1)
6533                      .addReg(VReg1));
6534     }
6535
6536     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6537       .addMBB(TrapBB)
6538       .addImm(ARMCC::HI)
6539       .addReg(ARM::CPSR);
6540
6541     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6542     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6543                    .addReg(ARM::CPSR, RegState::Define)
6544                    .addReg(NewVReg1)
6545                    .addImm(2));
6546
6547     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6548     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6549                    .addJumpTableIndex(MJTI)
6550                    .addImm(UId));
6551
6552     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6553     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6554                    .addReg(ARM::CPSR, RegState::Define)
6555                    .addReg(NewVReg2, RegState::Kill)
6556                    .addReg(NewVReg3));
6557
6558     MachineMemOperand *JTMMOLd =
6559       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6560                                MachineMemOperand::MOLoad, 4, 4);
6561
6562     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6563     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6564                    .addReg(NewVReg4, RegState::Kill)
6565                    .addImm(0)
6566                    .addMemOperand(JTMMOLd));
6567
6568     unsigned NewVReg6 = NewVReg5;
6569     if (RelocM == Reloc::PIC_) {
6570       NewVReg6 = MRI->createVirtualRegister(TRC);
6571       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6572                      .addReg(ARM::CPSR, RegState::Define)
6573                      .addReg(NewVReg5, RegState::Kill)
6574                      .addReg(NewVReg3));
6575     }
6576
6577     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6578       .addReg(NewVReg6, RegState::Kill)
6579       .addJumpTableIndex(MJTI)
6580       .addImm(UId);
6581   } else {
6582     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6583     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6584                    .addFrameIndex(FI)
6585                    .addImm(4)
6586                    .addMemOperand(FIMMOLd));
6587
6588     if (NumLPads < 256) {
6589       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6590                      .addReg(NewVReg1)
6591                      .addImm(NumLPads));
6592     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6593       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6594       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6595                      .addImm(NumLPads & 0xFFFF));
6596
6597       unsigned VReg2 = VReg1;
6598       if ((NumLPads & 0xFFFF0000) != 0) {
6599         VReg2 = MRI->createVirtualRegister(TRC);
6600         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6601                        .addReg(VReg1)
6602                        .addImm(NumLPads >> 16));
6603       }
6604
6605       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6606                      .addReg(NewVReg1)
6607                      .addReg(VReg2));
6608     } else {
6609       MachineConstantPool *ConstantPool = MF->getConstantPool();
6610       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6611       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6612
6613       // MachineConstantPool wants an explicit alignment.
6614       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6615       if (Align == 0)
6616         Align = getDataLayout()->getTypeAllocSize(C->getType());
6617       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6618
6619       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6620       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6621                      .addReg(VReg1, RegState::Define)
6622                      .addConstantPoolIndex(Idx)
6623                      .addImm(0));
6624       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6625                      .addReg(NewVReg1)
6626                      .addReg(VReg1, RegState::Kill));
6627     }
6628
6629     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6630       .addMBB(TrapBB)
6631       .addImm(ARMCC::HI)
6632       .addReg(ARM::CPSR);
6633
6634     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6635     AddDefaultCC(
6636       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6637                      .addReg(NewVReg1)
6638                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6639     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6640     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6641                    .addJumpTableIndex(MJTI)
6642                    .addImm(UId));
6643
6644     MachineMemOperand *JTMMOLd =
6645       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6646                                MachineMemOperand::MOLoad, 4, 4);
6647     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6648     AddDefaultPred(
6649       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6650       .addReg(NewVReg3, RegState::Kill)
6651       .addReg(NewVReg4)
6652       .addImm(0)
6653       .addMemOperand(JTMMOLd));
6654
6655     if (RelocM == Reloc::PIC_) {
6656       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6657         .addReg(NewVReg5, RegState::Kill)
6658         .addReg(NewVReg4)
6659         .addJumpTableIndex(MJTI)
6660         .addImm(UId);
6661     } else {
6662       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6663         .addReg(NewVReg5, RegState::Kill)
6664         .addJumpTableIndex(MJTI)
6665         .addImm(UId);
6666     }
6667   }
6668
6669   // Add the jump table entries as successors to the MBB.
6670   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6671   for (std::vector<MachineBasicBlock*>::iterator
6672          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6673     MachineBasicBlock *CurMBB = *I;
6674     if (SeenMBBs.insert(CurMBB))
6675       DispContBB->addSuccessor(CurMBB);
6676   }
6677
6678   // N.B. the order the invoke BBs are processed in doesn't matter here.
6679   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6680   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6681   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6682          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6683     MachineBasicBlock *BB = *I;
6684
6685     // Remove the landing pad successor from the invoke block and replace it
6686     // with the new dispatch block.
6687     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6688                                                   BB->succ_end());
6689     while (!Successors.empty()) {
6690       MachineBasicBlock *SMBB = Successors.pop_back_val();
6691       if (SMBB->isLandingPad()) {
6692         BB->removeSuccessor(SMBB);
6693         MBBLPads.push_back(SMBB);
6694       }
6695     }
6696
6697     BB->addSuccessor(DispatchBB);
6698
6699     // Find the invoke call and mark all of the callee-saved registers as
6700     // 'implicit defined' so that they're spilled. This prevents code from
6701     // moving instructions to before the EH block, where they will never be
6702     // executed.
6703     for (MachineBasicBlock::reverse_iterator
6704            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6705       if (!II->isCall()) continue;
6706
6707       DenseMap<unsigned, bool> DefRegs;
6708       for (MachineInstr::mop_iterator
6709              OI = II->operands_begin(), OE = II->operands_end();
6710            OI != OE; ++OI) {
6711         if (!OI->isReg()) continue;
6712         DefRegs[OI->getReg()] = true;
6713       }
6714
6715       MachineInstrBuilder MIB(*MF, &*II);
6716
6717       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6718         unsigned Reg = SavedRegs[i];
6719         if (Subtarget->isThumb2() &&
6720             !ARM::tGPRRegClass.contains(Reg) &&
6721             !ARM::hGPRRegClass.contains(Reg))
6722           continue;
6723         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6724           continue;
6725         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6726           continue;
6727         if (!DefRegs[Reg])
6728           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6729       }
6730
6731       break;
6732     }
6733   }
6734
6735   // Mark all former landing pads as non-landing pads. The dispatch is the only
6736   // landing pad now.
6737   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6738          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6739     (*I)->setIsLandingPad(false);
6740
6741   // The instruction is gone now.
6742   MI->eraseFromParent();
6743
6744   return MBB;
6745 }
6746
6747 static
6748 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6749   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6750        E = MBB->succ_end(); I != E; ++I)
6751     if (*I != Succ)
6752       return *I;
6753   llvm_unreachable("Expecting a BB with two successors!");
6754 }
6755
6756 MachineBasicBlock *ARMTargetLowering::
6757 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6758   // This pseudo instruction has 3 operands: dst, src, size
6759   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6760   // Otherwise, we will generate unrolled scalar copies.
6761   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6762   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6763   MachineFunction::iterator It = BB;
6764   ++It;
6765
6766   unsigned dest = MI->getOperand(0).getReg();
6767   unsigned src = MI->getOperand(1).getReg();
6768   unsigned SizeVal = MI->getOperand(2).getImm();
6769   unsigned Align = MI->getOperand(3).getImm();
6770   DebugLoc dl = MI->getDebugLoc();
6771
6772   bool isThumb2 = Subtarget->isThumb2();
6773   MachineFunction *MF = BB->getParent();
6774   MachineRegisterInfo &MRI = MF->getRegInfo();
6775   unsigned ldrOpc, strOpc, UnitSize = 0;
6776
6777   const TargetRegisterClass *TRC = isThumb2 ?
6778     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6779     (const TargetRegisterClass*)&ARM::GPRRegClass;
6780   const TargetRegisterClass *TRC_Vec = 0;
6781
6782   if (Align & 1) {
6783     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6784     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6785     UnitSize = 1;
6786   } else if (Align & 2) {
6787     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6788     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6789     UnitSize = 2;
6790   } else {
6791     // Check whether we can use NEON instructions.
6792     if (!MF->getFunction()->getAttributes().
6793           hasAttribute(AttributeSet::FunctionIndex,
6794                        Attribute::NoImplicitFloat) &&
6795         Subtarget->hasNEON()) {
6796       if ((Align % 16 == 0) && SizeVal >= 16) {
6797         ldrOpc = ARM::VLD1q32wb_fixed;
6798         strOpc = ARM::VST1q32wb_fixed;
6799         UnitSize = 16;
6800         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6801       }
6802       else if ((Align % 8 == 0) && SizeVal >= 8) {
6803         ldrOpc = ARM::VLD1d32wb_fixed;
6804         strOpc = ARM::VST1d32wb_fixed;
6805         UnitSize = 8;
6806         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6807       }
6808     }
6809     // Can't use NEON instructions.
6810     if (UnitSize == 0) {
6811       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6812       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6813       UnitSize = 4;
6814     }
6815   }
6816
6817   unsigned BytesLeft = SizeVal % UnitSize;
6818   unsigned LoopSize = SizeVal - BytesLeft;
6819
6820   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6821     // Use LDR and STR to copy.
6822     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6823     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6824     unsigned srcIn = src;
6825     unsigned destIn = dest;
6826     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6827       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6828       unsigned srcOut = MRI.createVirtualRegister(TRC);
6829       unsigned destOut = MRI.createVirtualRegister(TRC);
6830       if (UnitSize >= 8) {
6831         AddDefaultPred(BuildMI(*BB, MI, dl,
6832           TII->get(ldrOpc), scratch)
6833           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6834
6835         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6836           .addReg(destIn).addImm(0).addReg(scratch));
6837       } else if (isThumb2) {
6838         AddDefaultPred(BuildMI(*BB, MI, dl,
6839           TII->get(ldrOpc), scratch)
6840           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6841
6842         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6843           .addReg(scratch).addReg(destIn)
6844           .addImm(UnitSize));
6845       } else {
6846         AddDefaultPred(BuildMI(*BB, MI, dl,
6847           TII->get(ldrOpc), scratch)
6848           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6849           .addImm(UnitSize));
6850
6851         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6852           .addReg(scratch).addReg(destIn)
6853           .addReg(0).addImm(UnitSize));
6854       }
6855       srcIn = srcOut;
6856       destIn = destOut;
6857     }
6858
6859     // Handle the leftover bytes with LDRB and STRB.
6860     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6861     // [destOut] = STRB_POST(scratch, destIn, 1)
6862     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6863     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6864     for (unsigned i = 0; i < BytesLeft; i++) {
6865       unsigned scratch = MRI.createVirtualRegister(TRC);
6866       unsigned srcOut = MRI.createVirtualRegister(TRC);
6867       unsigned destOut = MRI.createVirtualRegister(TRC);
6868       if (isThumb2) {
6869         AddDefaultPred(BuildMI(*BB, MI, dl,
6870           TII->get(ldrOpc),scratch)
6871           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6872
6873         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6874           .addReg(scratch).addReg(destIn)
6875           .addReg(0).addImm(1));
6876       } else {
6877         AddDefaultPred(BuildMI(*BB, MI, dl,
6878           TII->get(ldrOpc),scratch)
6879           .addReg(srcOut, RegState::Define).addReg(srcIn)
6880           .addReg(0).addImm(1));
6881
6882         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6883           .addReg(scratch).addReg(destIn)
6884           .addReg(0).addImm(1));
6885       }
6886       srcIn = srcOut;
6887       destIn = destOut;
6888     }
6889     MI->eraseFromParent();   // The instruction is gone now.
6890     return BB;
6891   }
6892
6893   // Expand the pseudo op to a loop.
6894   // thisMBB:
6895   //   ...
6896   //   movw varEnd, # --> with thumb2
6897   //   movt varEnd, #
6898   //   ldrcp varEnd, idx --> without thumb2
6899   //   fallthrough --> loopMBB
6900   // loopMBB:
6901   //   PHI varPhi, varEnd, varLoop
6902   //   PHI srcPhi, src, srcLoop
6903   //   PHI destPhi, dst, destLoop
6904   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6905   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6906   //   subs varLoop, varPhi, #UnitSize
6907   //   bne loopMBB
6908   //   fallthrough --> exitMBB
6909   // exitMBB:
6910   //   epilogue to handle left-over bytes
6911   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6912   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6913   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6914   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6915   MF->insert(It, loopMBB);
6916   MF->insert(It, exitMBB);
6917
6918   // Transfer the remainder of BB and its successor edges to exitMBB.
6919   exitMBB->splice(exitMBB->begin(), BB,
6920                   llvm::next(MachineBasicBlock::iterator(MI)),
6921                   BB->end());
6922   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6923
6924   // Load an immediate to varEnd.
6925   unsigned varEnd = MRI.createVirtualRegister(TRC);
6926   if (isThumb2) {
6927     unsigned VReg1 = varEnd;
6928     if ((LoopSize & 0xFFFF0000) != 0)
6929       VReg1 = MRI.createVirtualRegister(TRC);
6930     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6931                    .addImm(LoopSize & 0xFFFF));
6932
6933     if ((LoopSize & 0xFFFF0000) != 0)
6934       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6935                      .addReg(VReg1)
6936                      .addImm(LoopSize >> 16));
6937   } else {
6938     MachineConstantPool *ConstantPool = MF->getConstantPool();
6939     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6940     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6941
6942     // MachineConstantPool wants an explicit alignment.
6943     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6944     if (Align == 0)
6945       Align = getDataLayout()->getTypeAllocSize(C->getType());
6946     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6947
6948     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6949                    .addReg(varEnd, RegState::Define)
6950                    .addConstantPoolIndex(Idx)
6951                    .addImm(0));
6952   }
6953   BB->addSuccessor(loopMBB);
6954
6955   // Generate the loop body:
6956   //   varPhi = PHI(varLoop, varEnd)
6957   //   srcPhi = PHI(srcLoop, src)
6958   //   destPhi = PHI(destLoop, dst)
6959   MachineBasicBlock *entryBB = BB;
6960   BB = loopMBB;
6961   unsigned varLoop = MRI.createVirtualRegister(TRC);
6962   unsigned varPhi = MRI.createVirtualRegister(TRC);
6963   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6964   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6965   unsigned destLoop = MRI.createVirtualRegister(TRC);
6966   unsigned destPhi = MRI.createVirtualRegister(TRC);
6967
6968   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6969     .addReg(varLoop).addMBB(loopMBB)
6970     .addReg(varEnd).addMBB(entryBB);
6971   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6972     .addReg(srcLoop).addMBB(loopMBB)
6973     .addReg(src).addMBB(entryBB);
6974   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6975     .addReg(destLoop).addMBB(loopMBB)
6976     .addReg(dest).addMBB(entryBB);
6977
6978   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6979   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6980   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6981   if (UnitSize >= 8) {
6982     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6983       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6984
6985     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6986       .addReg(destPhi).addImm(0).addReg(scratch));
6987   } else if (isThumb2) {
6988     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6989       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6990
6991     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6992       .addReg(scratch).addReg(destPhi)
6993       .addImm(UnitSize));
6994   } else {
6995     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6996       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6997       .addImm(UnitSize));
6998
6999     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7000       .addReg(scratch).addReg(destPhi)
7001       .addReg(0).addImm(UnitSize));
7002   }
7003
7004   // Decrement loop variable by UnitSize.
7005   MachineInstrBuilder MIB = BuildMI(BB, dl,
7006     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7007   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7008   MIB->getOperand(5).setReg(ARM::CPSR);
7009   MIB->getOperand(5).setIsDef(true);
7010
7011   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7012     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7013
7014   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7015   BB->addSuccessor(loopMBB);
7016   BB->addSuccessor(exitMBB);
7017
7018   // Add epilogue to handle BytesLeft.
7019   BB = exitMBB;
7020   MachineInstr *StartOfExit = exitMBB->begin();
7021   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7022   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7023
7024   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7025   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7026   unsigned srcIn = srcLoop;
7027   unsigned destIn = destLoop;
7028   for (unsigned i = 0; i < BytesLeft; i++) {
7029     unsigned scratch = MRI.createVirtualRegister(TRC);
7030     unsigned srcOut = MRI.createVirtualRegister(TRC);
7031     unsigned destOut = MRI.createVirtualRegister(TRC);
7032     if (isThumb2) {
7033       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7034         TII->get(ldrOpc),scratch)
7035         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7036
7037       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7038         .addReg(scratch).addReg(destIn)
7039         .addImm(1));
7040     } else {
7041       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7042         TII->get(ldrOpc),scratch)
7043         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7044
7045       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7046         .addReg(scratch).addReg(destIn)
7047         .addReg(0).addImm(1));
7048     }
7049     srcIn = srcOut;
7050     destIn = destOut;
7051   }
7052
7053   MI->eraseFromParent();   // The instruction is gone now.
7054   return BB;
7055 }
7056
7057 MachineBasicBlock *
7058 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7059                                                MachineBasicBlock *BB) const {
7060   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7061   DebugLoc dl = MI->getDebugLoc();
7062   bool isThumb2 = Subtarget->isThumb2();
7063   switch (MI->getOpcode()) {
7064   default: {
7065     MI->dump();
7066     llvm_unreachable("Unexpected instr type to insert");
7067   }
7068   // The Thumb2 pre-indexed stores have the same MI operands, they just
7069   // define them differently in the .td files from the isel patterns, so
7070   // they need pseudos.
7071   case ARM::t2STR_preidx:
7072     MI->setDesc(TII->get(ARM::t2STR_PRE));
7073     return BB;
7074   case ARM::t2STRB_preidx:
7075     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7076     return BB;
7077   case ARM::t2STRH_preidx:
7078     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7079     return BB;
7080
7081   case ARM::STRi_preidx:
7082   case ARM::STRBi_preidx: {
7083     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7084       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7085     // Decode the offset.
7086     unsigned Offset = MI->getOperand(4).getImm();
7087     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7088     Offset = ARM_AM::getAM2Offset(Offset);
7089     if (isSub)
7090       Offset = -Offset;
7091
7092     MachineMemOperand *MMO = *MI->memoperands_begin();
7093     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7094       .addOperand(MI->getOperand(0))  // Rn_wb
7095       .addOperand(MI->getOperand(1))  // Rt
7096       .addOperand(MI->getOperand(2))  // Rn
7097       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7098       .addOperand(MI->getOperand(5))  // pred
7099       .addOperand(MI->getOperand(6))
7100       .addMemOperand(MMO);
7101     MI->eraseFromParent();
7102     return BB;
7103   }
7104   case ARM::STRr_preidx:
7105   case ARM::STRBr_preidx:
7106   case ARM::STRH_preidx: {
7107     unsigned NewOpc;
7108     switch (MI->getOpcode()) {
7109     default: llvm_unreachable("unexpected opcode!");
7110     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7111     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7112     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7113     }
7114     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7115     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7116       MIB.addOperand(MI->getOperand(i));
7117     MI->eraseFromParent();
7118     return BB;
7119   }
7120   case ARM::ATOMIC_LOAD_ADD_I8:
7121      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7122   case ARM::ATOMIC_LOAD_ADD_I16:
7123      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7124   case ARM::ATOMIC_LOAD_ADD_I32:
7125      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7126
7127   case ARM::ATOMIC_LOAD_AND_I8:
7128      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7129   case ARM::ATOMIC_LOAD_AND_I16:
7130      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7131   case ARM::ATOMIC_LOAD_AND_I32:
7132      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7133
7134   case ARM::ATOMIC_LOAD_OR_I8:
7135      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7136   case ARM::ATOMIC_LOAD_OR_I16:
7137      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7138   case ARM::ATOMIC_LOAD_OR_I32:
7139      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7140
7141   case ARM::ATOMIC_LOAD_XOR_I8:
7142      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7143   case ARM::ATOMIC_LOAD_XOR_I16:
7144      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7145   case ARM::ATOMIC_LOAD_XOR_I32:
7146      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7147
7148   case ARM::ATOMIC_LOAD_NAND_I8:
7149      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7150   case ARM::ATOMIC_LOAD_NAND_I16:
7151      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7152   case ARM::ATOMIC_LOAD_NAND_I32:
7153      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7154
7155   case ARM::ATOMIC_LOAD_SUB_I8:
7156      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7157   case ARM::ATOMIC_LOAD_SUB_I16:
7158      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7159   case ARM::ATOMIC_LOAD_SUB_I32:
7160      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7161
7162   case ARM::ATOMIC_LOAD_MIN_I8:
7163      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7164   case ARM::ATOMIC_LOAD_MIN_I16:
7165      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7166   case ARM::ATOMIC_LOAD_MIN_I32:
7167      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7168
7169   case ARM::ATOMIC_LOAD_MAX_I8:
7170      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7171   case ARM::ATOMIC_LOAD_MAX_I16:
7172      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7173   case ARM::ATOMIC_LOAD_MAX_I32:
7174      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7175
7176   case ARM::ATOMIC_LOAD_UMIN_I8:
7177      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7178   case ARM::ATOMIC_LOAD_UMIN_I16:
7179      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7180   case ARM::ATOMIC_LOAD_UMIN_I32:
7181      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7182
7183   case ARM::ATOMIC_LOAD_UMAX_I8:
7184      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7185   case ARM::ATOMIC_LOAD_UMAX_I16:
7186      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7187   case ARM::ATOMIC_LOAD_UMAX_I32:
7188      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7189
7190   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7191   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7192   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7193
7194   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7195   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7196   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7197
7198
7199   case ARM::ATOMADD6432:
7200     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7201                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7202                               /*NeedsCarry*/ true);
7203   case ARM::ATOMSUB6432:
7204     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7205                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7206                               /*NeedsCarry*/ true);
7207   case ARM::ATOMOR6432:
7208     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7209                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7210   case ARM::ATOMXOR6432:
7211     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7212                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7213   case ARM::ATOMAND6432:
7214     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7215                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7216   case ARM::ATOMSWAP6432:
7217     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7218   case ARM::ATOMCMPXCHG6432:
7219     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7220                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7221                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7222   case ARM::ATOMMIN6432:
7223     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7224                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7225                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7226                               /*IsMinMax*/ true, ARMCC::LT);
7227   case ARM::ATOMMAX6432:
7228     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7229                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7230                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7231                               /*IsMinMax*/ true, ARMCC::GE);
7232   case ARM::ATOMUMIN6432:
7233     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7234                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7235                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7236                               /*IsMinMax*/ true, ARMCC::LO);
7237   case ARM::ATOMUMAX6432:
7238     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7239                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7240                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7241                               /*IsMinMax*/ true, ARMCC::HS);
7242
7243   case ARM::tMOVCCr_pseudo: {
7244     // To "insert" a SELECT_CC instruction, we actually have to insert the
7245     // diamond control-flow pattern.  The incoming instruction knows the
7246     // destination vreg to set, the condition code register to branch on, the
7247     // true/false values to select between, and a branch opcode to use.
7248     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7249     MachineFunction::iterator It = BB;
7250     ++It;
7251
7252     //  thisMBB:
7253     //  ...
7254     //   TrueVal = ...
7255     //   cmpTY ccX, r1, r2
7256     //   bCC copy1MBB
7257     //   fallthrough --> copy0MBB
7258     MachineBasicBlock *thisMBB  = BB;
7259     MachineFunction *F = BB->getParent();
7260     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7261     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7262     F->insert(It, copy0MBB);
7263     F->insert(It, sinkMBB);
7264
7265     // Transfer the remainder of BB and its successor edges to sinkMBB.
7266     sinkMBB->splice(sinkMBB->begin(), BB,
7267                     llvm::next(MachineBasicBlock::iterator(MI)),
7268                     BB->end());
7269     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7270
7271     BB->addSuccessor(copy0MBB);
7272     BB->addSuccessor(sinkMBB);
7273
7274     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7275       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7276
7277     //  copy0MBB:
7278     //   %FalseValue = ...
7279     //   # fallthrough to sinkMBB
7280     BB = copy0MBB;
7281
7282     // Update machine-CFG edges
7283     BB->addSuccessor(sinkMBB);
7284
7285     //  sinkMBB:
7286     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7287     //  ...
7288     BB = sinkMBB;
7289     BuildMI(*BB, BB->begin(), dl,
7290             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7291       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7292       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7293
7294     MI->eraseFromParent();   // The pseudo instruction is gone now.
7295     return BB;
7296   }
7297
7298   case ARM::BCCi64:
7299   case ARM::BCCZi64: {
7300     // If there is an unconditional branch to the other successor, remove it.
7301     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7302
7303     // Compare both parts that make up the double comparison separately for
7304     // equality.
7305     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7306
7307     unsigned LHS1 = MI->getOperand(1).getReg();
7308     unsigned LHS2 = MI->getOperand(2).getReg();
7309     if (RHSisZero) {
7310       AddDefaultPred(BuildMI(BB, dl,
7311                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7312                      .addReg(LHS1).addImm(0));
7313       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7314         .addReg(LHS2).addImm(0)
7315         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7316     } else {
7317       unsigned RHS1 = MI->getOperand(3).getReg();
7318       unsigned RHS2 = MI->getOperand(4).getReg();
7319       AddDefaultPred(BuildMI(BB, dl,
7320                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7321                      .addReg(LHS1).addReg(RHS1));
7322       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7323         .addReg(LHS2).addReg(RHS2)
7324         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7325     }
7326
7327     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7328     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7329     if (MI->getOperand(0).getImm() == ARMCC::NE)
7330       std::swap(destMBB, exitMBB);
7331
7332     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7333       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7334     if (isThumb2)
7335       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7336     else
7337       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7338
7339     MI->eraseFromParent();   // The pseudo instruction is gone now.
7340     return BB;
7341   }
7342
7343   case ARM::Int_eh_sjlj_setjmp:
7344   case ARM::Int_eh_sjlj_setjmp_nofp:
7345   case ARM::tInt_eh_sjlj_setjmp:
7346   case ARM::t2Int_eh_sjlj_setjmp:
7347   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7348     EmitSjLjDispatchBlock(MI, BB);
7349     return BB;
7350
7351   case ARM::ABS:
7352   case ARM::t2ABS: {
7353     // To insert an ABS instruction, we have to insert the
7354     // diamond control-flow pattern.  The incoming instruction knows the
7355     // source vreg to test against 0, the destination vreg to set,
7356     // the condition code register to branch on, the
7357     // true/false values to select between, and a branch opcode to use.
7358     // It transforms
7359     //     V1 = ABS V0
7360     // into
7361     //     V2 = MOVS V0
7362     //     BCC                      (branch to SinkBB if V0 >= 0)
7363     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7364     //     SinkBB: V1 = PHI(V2, V3)
7365     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7366     MachineFunction::iterator BBI = BB;
7367     ++BBI;
7368     MachineFunction *Fn = BB->getParent();
7369     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7370     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7371     Fn->insert(BBI, RSBBB);
7372     Fn->insert(BBI, SinkBB);
7373
7374     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7375     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7376     bool isThumb2 = Subtarget->isThumb2();
7377     MachineRegisterInfo &MRI = Fn->getRegInfo();
7378     // In Thumb mode S must not be specified if source register is the SP or
7379     // PC and if destination register is the SP, so restrict register class
7380     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7381       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7382       (const TargetRegisterClass*)&ARM::GPRRegClass);
7383
7384     // Transfer the remainder of BB and its successor edges to sinkMBB.
7385     SinkBB->splice(SinkBB->begin(), BB,
7386       llvm::next(MachineBasicBlock::iterator(MI)),
7387       BB->end());
7388     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7389
7390     BB->addSuccessor(RSBBB);
7391     BB->addSuccessor(SinkBB);
7392
7393     // fall through to SinkMBB
7394     RSBBB->addSuccessor(SinkBB);
7395
7396     // insert a cmp at the end of BB
7397     AddDefaultPred(BuildMI(BB, dl,
7398                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7399                    .addReg(ABSSrcReg).addImm(0));
7400
7401     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7402     BuildMI(BB, dl,
7403       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7404       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7405
7406     // insert rsbri in RSBBB
7407     // Note: BCC and rsbri will be converted into predicated rsbmi
7408     // by if-conversion pass
7409     BuildMI(*RSBBB, RSBBB->begin(), dl,
7410       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7411       .addReg(ABSSrcReg, RegState::Kill)
7412       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7413
7414     // insert PHI in SinkBB,
7415     // reuse ABSDstReg to not change uses of ABS instruction
7416     BuildMI(*SinkBB, SinkBB->begin(), dl,
7417       TII->get(ARM::PHI), ABSDstReg)
7418       .addReg(NewRsbDstReg).addMBB(RSBBB)
7419       .addReg(ABSSrcReg).addMBB(BB);
7420
7421     // remove ABS instruction
7422     MI->eraseFromParent();
7423
7424     // return last added BB
7425     return SinkBB;
7426   }
7427   case ARM::COPY_STRUCT_BYVAL_I32:
7428     ++NumLoopByVals;
7429     return EmitStructByval(MI, BB);
7430   }
7431 }
7432
7433 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7434                                                       SDNode *Node) const {
7435   if (!MI->hasPostISelHook()) {
7436     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7437            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7438     return;
7439   }
7440
7441   const MCInstrDesc *MCID = &MI->getDesc();
7442   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7443   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7444   // operand is still set to noreg. If needed, set the optional operand's
7445   // register to CPSR, and remove the redundant implicit def.
7446   //
7447   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7448
7449   // Rename pseudo opcodes.
7450   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7451   if (NewOpc) {
7452     const ARMBaseInstrInfo *TII =
7453       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7454     MCID = &TII->get(NewOpc);
7455
7456     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7457            "converted opcode should be the same except for cc_out");
7458
7459     MI->setDesc(*MCID);
7460
7461     // Add the optional cc_out operand
7462     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7463   }
7464   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7465
7466   // Any ARM instruction that sets the 's' bit should specify an optional
7467   // "cc_out" operand in the last operand position.
7468   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7469     assert(!NewOpc && "Optional cc_out operand required");
7470     return;
7471   }
7472   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7473   // since we already have an optional CPSR def.
7474   bool definesCPSR = false;
7475   bool deadCPSR = false;
7476   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7477        i != e; ++i) {
7478     const MachineOperand &MO = MI->getOperand(i);
7479     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7480       definesCPSR = true;
7481       if (MO.isDead())
7482         deadCPSR = true;
7483       MI->RemoveOperand(i);
7484       break;
7485     }
7486   }
7487   if (!definesCPSR) {
7488     assert(!NewOpc && "Optional cc_out operand required");
7489     return;
7490   }
7491   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7492   if (deadCPSR) {
7493     assert(!MI->getOperand(ccOutIdx).getReg() &&
7494            "expect uninitialized optional cc_out operand");
7495     return;
7496   }
7497
7498   // If this instruction was defined with an optional CPSR def and its dag node
7499   // had a live implicit CPSR def, then activate the optional CPSR def.
7500   MachineOperand &MO = MI->getOperand(ccOutIdx);
7501   MO.setReg(ARM::CPSR);
7502   MO.setIsDef(true);
7503 }
7504
7505 //===----------------------------------------------------------------------===//
7506 //                           ARM Optimization Hooks
7507 //===----------------------------------------------------------------------===//
7508
7509 // Helper function that checks if N is a null or all ones constant.
7510 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7511   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7512   if (!C)
7513     return false;
7514   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7515 }
7516
7517 // Return true if N is conditionally 0 or all ones.
7518 // Detects these expressions where cc is an i1 value:
7519 //
7520 //   (select cc 0, y)   [AllOnes=0]
7521 //   (select cc y, 0)   [AllOnes=0]
7522 //   (zext cc)          [AllOnes=0]
7523 //   (sext cc)          [AllOnes=0/1]
7524 //   (select cc -1, y)  [AllOnes=1]
7525 //   (select cc y, -1)  [AllOnes=1]
7526 //
7527 // Invert is set when N is the null/all ones constant when CC is false.
7528 // OtherOp is set to the alternative value of N.
7529 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7530                                        SDValue &CC, bool &Invert,
7531                                        SDValue &OtherOp,
7532                                        SelectionDAG &DAG) {
7533   switch (N->getOpcode()) {
7534   default: return false;
7535   case ISD::SELECT: {
7536     CC = N->getOperand(0);
7537     SDValue N1 = N->getOperand(1);
7538     SDValue N2 = N->getOperand(2);
7539     if (isZeroOrAllOnes(N1, AllOnes)) {
7540       Invert = false;
7541       OtherOp = N2;
7542       return true;
7543     }
7544     if (isZeroOrAllOnes(N2, AllOnes)) {
7545       Invert = true;
7546       OtherOp = N1;
7547       return true;
7548     }
7549     return false;
7550   }
7551   case ISD::ZERO_EXTEND:
7552     // (zext cc) can never be the all ones value.
7553     if (AllOnes)
7554       return false;
7555     // Fall through.
7556   case ISD::SIGN_EXTEND: {
7557     EVT VT = N->getValueType(0);
7558     CC = N->getOperand(0);
7559     if (CC.getValueType() != MVT::i1)
7560       return false;
7561     Invert = !AllOnes;
7562     if (AllOnes)
7563       // When looking for an AllOnes constant, N is an sext, and the 'other'
7564       // value is 0.
7565       OtherOp = DAG.getConstant(0, VT);
7566     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7567       // When looking for a 0 constant, N can be zext or sext.
7568       OtherOp = DAG.getConstant(1, VT);
7569     else
7570       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7571     return true;
7572   }
7573   }
7574 }
7575
7576 // Combine a constant select operand into its use:
7577 //
7578 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7579 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7580 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7581 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7582 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7583 //
7584 // The transform is rejected if the select doesn't have a constant operand that
7585 // is null, or all ones when AllOnes is set.
7586 //
7587 // Also recognize sext/zext from i1:
7588 //
7589 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7590 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7591 //
7592 // These transformations eventually create predicated instructions.
7593 //
7594 // @param N       The node to transform.
7595 // @param Slct    The N operand that is a select.
7596 // @param OtherOp The other N operand (x above).
7597 // @param DCI     Context.
7598 // @param AllOnes Require the select constant to be all ones instead of null.
7599 // @returns The new node, or SDValue() on failure.
7600 static
7601 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7602                             TargetLowering::DAGCombinerInfo &DCI,
7603                             bool AllOnes = false) {
7604   SelectionDAG &DAG = DCI.DAG;
7605   EVT VT = N->getValueType(0);
7606   SDValue NonConstantVal;
7607   SDValue CCOp;
7608   bool SwapSelectOps;
7609   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7610                                   NonConstantVal, DAG))
7611     return SDValue();
7612
7613   // Slct is now know to be the desired identity constant when CC is true.
7614   SDValue TrueVal = OtherOp;
7615   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7616                                  OtherOp, NonConstantVal);
7617   // Unless SwapSelectOps says CC should be false.
7618   if (SwapSelectOps)
7619     std::swap(TrueVal, FalseVal);
7620
7621   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7622                      CCOp, TrueVal, FalseVal);
7623 }
7624
7625 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7626 static
7627 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7628                                        TargetLowering::DAGCombinerInfo &DCI) {
7629   SDValue N0 = N->getOperand(0);
7630   SDValue N1 = N->getOperand(1);
7631   if (N0.getNode()->hasOneUse()) {
7632     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7633     if (Result.getNode())
7634       return Result;
7635   }
7636   if (N1.getNode()->hasOneUse()) {
7637     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7638     if (Result.getNode())
7639       return Result;
7640   }
7641   return SDValue();
7642 }
7643
7644 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7645 // (only after legalization).
7646 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7647                                  TargetLowering::DAGCombinerInfo &DCI,
7648                                  const ARMSubtarget *Subtarget) {
7649
7650   // Only perform optimization if after legalize, and if NEON is available. We
7651   // also expected both operands to be BUILD_VECTORs.
7652   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7653       || N0.getOpcode() != ISD::BUILD_VECTOR
7654       || N1.getOpcode() != ISD::BUILD_VECTOR)
7655     return SDValue();
7656
7657   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7658   EVT VT = N->getValueType(0);
7659   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7660     return SDValue();
7661
7662   // Check that the vector operands are of the right form.
7663   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7664   // operands, where N is the size of the formed vector.
7665   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7666   // index such that we have a pair wise add pattern.
7667
7668   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7669   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7670     return SDValue();
7671   SDValue Vec = N0->getOperand(0)->getOperand(0);
7672   SDNode *V = Vec.getNode();
7673   unsigned nextIndex = 0;
7674
7675   // For each operands to the ADD which are BUILD_VECTORs,
7676   // check to see if each of their operands are an EXTRACT_VECTOR with
7677   // the same vector and appropriate index.
7678   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7679     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7680         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7681
7682       SDValue ExtVec0 = N0->getOperand(i);
7683       SDValue ExtVec1 = N1->getOperand(i);
7684
7685       // First operand is the vector, verify its the same.
7686       if (V != ExtVec0->getOperand(0).getNode() ||
7687           V != ExtVec1->getOperand(0).getNode())
7688         return SDValue();
7689
7690       // Second is the constant, verify its correct.
7691       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7692       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7693
7694       // For the constant, we want to see all the even or all the odd.
7695       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7696           || C1->getZExtValue() != nextIndex+1)
7697         return SDValue();
7698
7699       // Increment index.
7700       nextIndex+=2;
7701     } else
7702       return SDValue();
7703   }
7704
7705   // Create VPADDL node.
7706   SelectionDAG &DAG = DCI.DAG;
7707   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7708
7709   // Build operand list.
7710   SmallVector<SDValue, 8> Ops;
7711   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7712                                 TLI.getPointerTy()));
7713
7714   // Input is the vector.
7715   Ops.push_back(Vec);
7716
7717   // Get widened type and narrowed type.
7718   MVT widenType;
7719   unsigned numElem = VT.getVectorNumElements();
7720   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7721     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7722     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7723     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7724     default:
7725       llvm_unreachable("Invalid vector element type for padd optimization.");
7726   }
7727
7728   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7729                             widenType, &Ops[0], Ops.size());
7730   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7731 }
7732
7733 static SDValue findMUL_LOHI(SDValue V) {
7734   if (V->getOpcode() == ISD::UMUL_LOHI ||
7735       V->getOpcode() == ISD::SMUL_LOHI)
7736     return V;
7737   return SDValue();
7738 }
7739
7740 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7741                                      TargetLowering::DAGCombinerInfo &DCI,
7742                                      const ARMSubtarget *Subtarget) {
7743
7744   if (Subtarget->isThumb1Only()) return SDValue();
7745
7746   // Only perform the checks after legalize when the pattern is available.
7747   if (DCI.isBeforeLegalize()) return SDValue();
7748
7749   // Look for multiply add opportunities.
7750   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7751   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7752   // a glue link from the first add to the second add.
7753   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7754   // a S/UMLAL instruction.
7755   //          loAdd   UMUL_LOHI
7756   //            \    / :lo    \ :hi
7757   //             \  /          \          [no multiline comment]
7758   //              ADDC         |  hiAdd
7759   //                 \ :glue  /  /
7760   //                  \      /  /
7761   //                    ADDE
7762   //
7763   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7764   SDValue AddcOp0 = AddcNode->getOperand(0);
7765   SDValue AddcOp1 = AddcNode->getOperand(1);
7766
7767   // Check if the two operands are from the same mul_lohi node.
7768   if (AddcOp0.getNode() == AddcOp1.getNode())
7769     return SDValue();
7770
7771   assert(AddcNode->getNumValues() == 2 &&
7772          AddcNode->getValueType(0) == MVT::i32 &&
7773          AddcNode->getValueType(1) == MVT::Glue &&
7774          "Expect ADDC with two result values: i32, glue");
7775
7776   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7777   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7778       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7779       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7780       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7781     return SDValue();
7782
7783   // Look for the glued ADDE.
7784   SDNode* AddeNode = AddcNode->getGluedUser();
7785   if (AddeNode == NULL)
7786     return SDValue();
7787
7788   // Make sure it is really an ADDE.
7789   if (AddeNode->getOpcode() != ISD::ADDE)
7790     return SDValue();
7791
7792   assert(AddeNode->getNumOperands() == 3 &&
7793          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7794          "ADDE node has the wrong inputs");
7795
7796   // Check for the triangle shape.
7797   SDValue AddeOp0 = AddeNode->getOperand(0);
7798   SDValue AddeOp1 = AddeNode->getOperand(1);
7799
7800   // Make sure that the ADDE operands are not coming from the same node.
7801   if (AddeOp0.getNode() == AddeOp1.getNode())
7802     return SDValue();
7803
7804   // Find the MUL_LOHI node walking up ADDE's operands.
7805   bool IsLeftOperandMUL = false;
7806   SDValue MULOp = findMUL_LOHI(AddeOp0);
7807   if (MULOp == SDValue())
7808    MULOp = findMUL_LOHI(AddeOp1);
7809   else
7810     IsLeftOperandMUL = true;
7811   if (MULOp == SDValue())
7812      return SDValue();
7813
7814   // Figure out the right opcode.
7815   unsigned Opc = MULOp->getOpcode();
7816   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7817
7818   // Figure out the high and low input values to the MLAL node.
7819   SDValue* HiMul = &MULOp;
7820   SDValue* HiAdd = NULL;
7821   SDValue* LoMul = NULL;
7822   SDValue* LowAdd = NULL;
7823
7824   if (IsLeftOperandMUL)
7825     HiAdd = &AddeOp1;
7826   else
7827     HiAdd = &AddeOp0;
7828
7829
7830   if (AddcOp0->getOpcode() == Opc) {
7831     LoMul = &AddcOp0;
7832     LowAdd = &AddcOp1;
7833   }
7834   if (AddcOp1->getOpcode() == Opc) {
7835     LoMul = &AddcOp1;
7836     LowAdd = &AddcOp0;
7837   }
7838
7839   if (LoMul == NULL)
7840     return SDValue();
7841
7842   if (LoMul->getNode() != HiMul->getNode())
7843     return SDValue();
7844
7845   // Create the merged node.
7846   SelectionDAG &DAG = DCI.DAG;
7847
7848   // Build operand list.
7849   SmallVector<SDValue, 8> Ops;
7850   Ops.push_back(LoMul->getOperand(0));
7851   Ops.push_back(LoMul->getOperand(1));
7852   Ops.push_back(*LowAdd);
7853   Ops.push_back(*HiAdd);
7854
7855   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7856                                  DAG.getVTList(MVT::i32, MVT::i32),
7857                                  &Ops[0], Ops.size());
7858
7859   // Replace the ADDs' nodes uses by the MLA node's values.
7860   SDValue HiMLALResult(MLALNode.getNode(), 1);
7861   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7862
7863   SDValue LoMLALResult(MLALNode.getNode(), 0);
7864   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7865
7866   // Return original node to notify the driver to stop replacing.
7867   SDValue resNode(AddcNode, 0);
7868   return resNode;
7869 }
7870
7871 /// PerformADDCCombine - Target-specific dag combine transform from
7872 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7873 static SDValue PerformADDCCombine(SDNode *N,
7874                                  TargetLowering::DAGCombinerInfo &DCI,
7875                                  const ARMSubtarget *Subtarget) {
7876
7877   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7878
7879 }
7880
7881 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7882 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7883 /// called with the default operands, and if that fails, with commuted
7884 /// operands.
7885 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7886                                           TargetLowering::DAGCombinerInfo &DCI,
7887                                           const ARMSubtarget *Subtarget){
7888
7889   // Attempt to create vpaddl for this add.
7890   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7891   if (Result.getNode())
7892     return Result;
7893
7894   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7895   if (N0.getNode()->hasOneUse()) {
7896     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7897     if (Result.getNode()) return Result;
7898   }
7899   return SDValue();
7900 }
7901
7902 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7903 ///
7904 static SDValue PerformADDCombine(SDNode *N,
7905                                  TargetLowering::DAGCombinerInfo &DCI,
7906                                  const ARMSubtarget *Subtarget) {
7907   SDValue N0 = N->getOperand(0);
7908   SDValue N1 = N->getOperand(1);
7909
7910   // First try with the default operand order.
7911   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7912   if (Result.getNode())
7913     return Result;
7914
7915   // If that didn't work, try again with the operands commuted.
7916   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7917 }
7918
7919 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7920 ///
7921 static SDValue PerformSUBCombine(SDNode *N,
7922                                  TargetLowering::DAGCombinerInfo &DCI) {
7923   SDValue N0 = N->getOperand(0);
7924   SDValue N1 = N->getOperand(1);
7925
7926   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7927   if (N1.getNode()->hasOneUse()) {
7928     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7929     if (Result.getNode()) return Result;
7930   }
7931
7932   return SDValue();
7933 }
7934
7935 /// PerformVMULCombine
7936 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7937 /// special multiplier accumulator forwarding.
7938 ///   vmul d3, d0, d2
7939 ///   vmla d3, d1, d2
7940 /// is faster than
7941 ///   vadd d3, d0, d1
7942 ///   vmul d3, d3, d2
7943 static SDValue PerformVMULCombine(SDNode *N,
7944                                   TargetLowering::DAGCombinerInfo &DCI,
7945                                   const ARMSubtarget *Subtarget) {
7946   if (!Subtarget->hasVMLxForwarding())
7947     return SDValue();
7948
7949   SelectionDAG &DAG = DCI.DAG;
7950   SDValue N0 = N->getOperand(0);
7951   SDValue N1 = N->getOperand(1);
7952   unsigned Opcode = N0.getOpcode();
7953   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7954       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7955     Opcode = N1.getOpcode();
7956     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7957         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7958       return SDValue();
7959     std::swap(N0, N1);
7960   }
7961
7962   EVT VT = N->getValueType(0);
7963   DebugLoc DL = N->getDebugLoc();
7964   SDValue N00 = N0->getOperand(0);
7965   SDValue N01 = N0->getOperand(1);
7966   return DAG.getNode(Opcode, DL, VT,
7967                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7968                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7969 }
7970
7971 static SDValue PerformMULCombine(SDNode *N,
7972                                  TargetLowering::DAGCombinerInfo &DCI,
7973                                  const ARMSubtarget *Subtarget) {
7974   SelectionDAG &DAG = DCI.DAG;
7975
7976   if (Subtarget->isThumb1Only())
7977     return SDValue();
7978
7979   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7980     return SDValue();
7981
7982   EVT VT = N->getValueType(0);
7983   if (VT.is64BitVector() || VT.is128BitVector())
7984     return PerformVMULCombine(N, DCI, Subtarget);
7985   if (VT != MVT::i32)
7986     return SDValue();
7987
7988   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7989   if (!C)
7990     return SDValue();
7991
7992   int64_t MulAmt = C->getSExtValue();
7993   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7994
7995   ShiftAmt = ShiftAmt & (32 - 1);
7996   SDValue V = N->getOperand(0);
7997   DebugLoc DL = N->getDebugLoc();
7998
7999   SDValue Res;
8000   MulAmt >>= ShiftAmt;
8001
8002   if (MulAmt >= 0) {
8003     if (isPowerOf2_32(MulAmt - 1)) {
8004       // (mul x, 2^N + 1) => (add (shl x, N), x)
8005       Res = DAG.getNode(ISD::ADD, DL, VT,
8006                         V,
8007                         DAG.getNode(ISD::SHL, DL, VT,
8008                                     V,
8009                                     DAG.getConstant(Log2_32(MulAmt - 1),
8010                                                     MVT::i32)));
8011     } else if (isPowerOf2_32(MulAmt + 1)) {
8012       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8013       Res = DAG.getNode(ISD::SUB, DL, VT,
8014                         DAG.getNode(ISD::SHL, DL, VT,
8015                                     V,
8016                                     DAG.getConstant(Log2_32(MulAmt + 1),
8017                                                     MVT::i32)),
8018                         V);
8019     } else
8020       return SDValue();
8021   } else {
8022     uint64_t MulAmtAbs = -MulAmt;
8023     if (isPowerOf2_32(MulAmtAbs + 1)) {
8024       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8025       Res = DAG.getNode(ISD::SUB, DL, VT,
8026                         V,
8027                         DAG.getNode(ISD::SHL, DL, VT,
8028                                     V,
8029                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8030                                                     MVT::i32)));
8031     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8032       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8033       Res = DAG.getNode(ISD::ADD, DL, VT,
8034                         V,
8035                         DAG.getNode(ISD::SHL, DL, VT,
8036                                     V,
8037                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8038                                                     MVT::i32)));
8039       Res = DAG.getNode(ISD::SUB, DL, VT,
8040                         DAG.getConstant(0, MVT::i32),Res);
8041
8042     } else
8043       return SDValue();
8044   }
8045
8046   if (ShiftAmt != 0)
8047     Res = DAG.getNode(ISD::SHL, DL, VT,
8048                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8049
8050   // Do not add new nodes to DAG combiner worklist.
8051   DCI.CombineTo(N, Res, false);
8052   return SDValue();
8053 }
8054
8055 static SDValue PerformANDCombine(SDNode *N,
8056                                  TargetLowering::DAGCombinerInfo &DCI,
8057                                  const ARMSubtarget *Subtarget) {
8058
8059   // Attempt to use immediate-form VBIC
8060   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8061   DebugLoc dl = N->getDebugLoc();
8062   EVT VT = N->getValueType(0);
8063   SelectionDAG &DAG = DCI.DAG;
8064
8065   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8066     return SDValue();
8067
8068   APInt SplatBits, SplatUndef;
8069   unsigned SplatBitSize;
8070   bool HasAnyUndefs;
8071   if (BVN &&
8072       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8073     if (SplatBitSize <= 64) {
8074       EVT VbicVT;
8075       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8076                                       SplatUndef.getZExtValue(), SplatBitSize,
8077                                       DAG, VbicVT, VT.is128BitVector(),
8078                                       OtherModImm);
8079       if (Val.getNode()) {
8080         SDValue Input =
8081           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8082         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8083         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8084       }
8085     }
8086   }
8087
8088   if (!Subtarget->isThumb1Only()) {
8089     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8090     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8091     if (Result.getNode())
8092       return Result;
8093   }
8094
8095   return SDValue();
8096 }
8097
8098 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8099 static SDValue PerformORCombine(SDNode *N,
8100                                 TargetLowering::DAGCombinerInfo &DCI,
8101                                 const ARMSubtarget *Subtarget) {
8102   // Attempt to use immediate-form VORR
8103   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8104   DebugLoc dl = N->getDebugLoc();
8105   EVT VT = N->getValueType(0);
8106   SelectionDAG &DAG = DCI.DAG;
8107
8108   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8109     return SDValue();
8110
8111   APInt SplatBits, SplatUndef;
8112   unsigned SplatBitSize;
8113   bool HasAnyUndefs;
8114   if (BVN && Subtarget->hasNEON() &&
8115       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8116     if (SplatBitSize <= 64) {
8117       EVT VorrVT;
8118       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8119                                       SplatUndef.getZExtValue(), SplatBitSize,
8120                                       DAG, VorrVT, VT.is128BitVector(),
8121                                       OtherModImm);
8122       if (Val.getNode()) {
8123         SDValue Input =
8124           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8125         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8126         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8127       }
8128     }
8129   }
8130
8131   if (!Subtarget->isThumb1Only()) {
8132     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8133     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8134     if (Result.getNode())
8135       return Result;
8136   }
8137
8138   // The code below optimizes (or (and X, Y), Z).
8139   // The AND operand needs to have a single user to make these optimizations
8140   // profitable.
8141   SDValue N0 = N->getOperand(0);
8142   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8143     return SDValue();
8144   SDValue N1 = N->getOperand(1);
8145
8146   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8147   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8148       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8149     APInt SplatUndef;
8150     unsigned SplatBitSize;
8151     bool HasAnyUndefs;
8152
8153     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8154     APInt SplatBits0;
8155     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8156                                   HasAnyUndefs) && !HasAnyUndefs) {
8157       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8158       APInt SplatBits1;
8159       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8160                                     HasAnyUndefs) && !HasAnyUndefs &&
8161           SplatBits0 == ~SplatBits1) {
8162         // Canonicalize the vector type to make instruction selection simpler.
8163         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8164         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8165                                      N0->getOperand(1), N0->getOperand(0),
8166                                      N1->getOperand(0));
8167         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8168       }
8169     }
8170   }
8171
8172   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8173   // reasonable.
8174
8175   // BFI is only available on V6T2+
8176   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8177     return SDValue();
8178
8179   DebugLoc DL = N->getDebugLoc();
8180   // 1) or (and A, mask), val => ARMbfi A, val, mask
8181   //      iff (val & mask) == val
8182   //
8183   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8184   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8185   //          && mask == ~mask2
8186   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8187   //          && ~mask == mask2
8188   //  (i.e., copy a bitfield value into another bitfield of the same width)
8189
8190   if (VT != MVT::i32)
8191     return SDValue();
8192
8193   SDValue N00 = N0.getOperand(0);
8194
8195   // The value and the mask need to be constants so we can verify this is
8196   // actually a bitfield set. If the mask is 0xffff, we can do better
8197   // via a movt instruction, so don't use BFI in that case.
8198   SDValue MaskOp = N0.getOperand(1);
8199   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8200   if (!MaskC)
8201     return SDValue();
8202   unsigned Mask = MaskC->getZExtValue();
8203   if (Mask == 0xffff)
8204     return SDValue();
8205   SDValue Res;
8206   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8207   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8208   if (N1C) {
8209     unsigned Val = N1C->getZExtValue();
8210     if ((Val & ~Mask) != Val)
8211       return SDValue();
8212
8213     if (ARM::isBitFieldInvertedMask(Mask)) {
8214       Val >>= CountTrailingZeros_32(~Mask);
8215
8216       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8217                         DAG.getConstant(Val, MVT::i32),
8218                         DAG.getConstant(Mask, MVT::i32));
8219
8220       // Do not add new nodes to DAG combiner worklist.
8221       DCI.CombineTo(N, Res, false);
8222       return SDValue();
8223     }
8224   } else if (N1.getOpcode() == ISD::AND) {
8225     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8226     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8227     if (!N11C)
8228       return SDValue();
8229     unsigned Mask2 = N11C->getZExtValue();
8230
8231     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8232     // as is to match.
8233     if (ARM::isBitFieldInvertedMask(Mask) &&
8234         (Mask == ~Mask2)) {
8235       // The pack halfword instruction works better for masks that fit it,
8236       // so use that when it's available.
8237       if (Subtarget->hasT2ExtractPack() &&
8238           (Mask == 0xffff || Mask == 0xffff0000))
8239         return SDValue();
8240       // 2a
8241       unsigned amt = CountTrailingZeros_32(Mask2);
8242       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8243                         DAG.getConstant(amt, MVT::i32));
8244       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8245                         DAG.getConstant(Mask, MVT::i32));
8246       // Do not add new nodes to DAG combiner worklist.
8247       DCI.CombineTo(N, Res, false);
8248       return SDValue();
8249     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8250                (~Mask == Mask2)) {
8251       // The pack halfword instruction works better for masks that fit it,
8252       // so use that when it's available.
8253       if (Subtarget->hasT2ExtractPack() &&
8254           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8255         return SDValue();
8256       // 2b
8257       unsigned lsb = CountTrailingZeros_32(Mask);
8258       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8259                         DAG.getConstant(lsb, MVT::i32));
8260       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8261                         DAG.getConstant(Mask2, MVT::i32));
8262       // Do not add new nodes to DAG combiner worklist.
8263       DCI.CombineTo(N, Res, false);
8264       return SDValue();
8265     }
8266   }
8267
8268   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8269       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8270       ARM::isBitFieldInvertedMask(~Mask)) {
8271     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8272     // where lsb(mask) == #shamt and masked bits of B are known zero.
8273     SDValue ShAmt = N00.getOperand(1);
8274     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8275     unsigned LSB = CountTrailingZeros_32(Mask);
8276     if (ShAmtC != LSB)
8277       return SDValue();
8278
8279     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8280                       DAG.getConstant(~Mask, MVT::i32));
8281
8282     // Do not add new nodes to DAG combiner worklist.
8283     DCI.CombineTo(N, Res, false);
8284   }
8285
8286   return SDValue();
8287 }
8288
8289 static SDValue PerformXORCombine(SDNode *N,
8290                                  TargetLowering::DAGCombinerInfo &DCI,
8291                                  const ARMSubtarget *Subtarget) {
8292   EVT VT = N->getValueType(0);
8293   SelectionDAG &DAG = DCI.DAG;
8294
8295   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8296     return SDValue();
8297
8298   if (!Subtarget->isThumb1Only()) {
8299     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8300     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8301     if (Result.getNode())
8302       return Result;
8303   }
8304
8305   return SDValue();
8306 }
8307
8308 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8309 /// the bits being cleared by the AND are not demanded by the BFI.
8310 static SDValue PerformBFICombine(SDNode *N,
8311                                  TargetLowering::DAGCombinerInfo &DCI) {
8312   SDValue N1 = N->getOperand(1);
8313   if (N1.getOpcode() == ISD::AND) {
8314     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8315     if (!N11C)
8316       return SDValue();
8317     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8318     unsigned LSB = CountTrailingZeros_32(~InvMask);
8319     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8320     unsigned Mask = (1 << Width)-1;
8321     unsigned Mask2 = N11C->getZExtValue();
8322     if ((Mask & (~Mask2)) == 0)
8323       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8324                              N->getOperand(0), N1.getOperand(0),
8325                              N->getOperand(2));
8326   }
8327   return SDValue();
8328 }
8329
8330 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8331 /// ARMISD::VMOVRRD.
8332 static SDValue PerformVMOVRRDCombine(SDNode *N,
8333                                      TargetLowering::DAGCombinerInfo &DCI) {
8334   // vmovrrd(vmovdrr x, y) -> x,y
8335   SDValue InDouble = N->getOperand(0);
8336   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8337     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8338
8339   // vmovrrd(load f64) -> (load i32), (load i32)
8340   SDNode *InNode = InDouble.getNode();
8341   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8342       InNode->getValueType(0) == MVT::f64 &&
8343       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8344       !cast<LoadSDNode>(InNode)->isVolatile()) {
8345     // TODO: Should this be done for non-FrameIndex operands?
8346     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8347
8348     SelectionDAG &DAG = DCI.DAG;
8349     DebugLoc DL = LD->getDebugLoc();
8350     SDValue BasePtr = LD->getBasePtr();
8351     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8352                                  LD->getPointerInfo(), LD->isVolatile(),
8353                                  LD->isNonTemporal(), LD->isInvariant(),
8354                                  LD->getAlignment());
8355
8356     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8357                                     DAG.getConstant(4, MVT::i32));
8358     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8359                                  LD->getPointerInfo(), LD->isVolatile(),
8360                                  LD->isNonTemporal(), LD->isInvariant(),
8361                                  std::min(4U, LD->getAlignment() / 2));
8362
8363     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8364     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8365     DCI.RemoveFromWorklist(LD);
8366     DAG.DeleteNode(LD);
8367     return Result;
8368   }
8369
8370   return SDValue();
8371 }
8372
8373 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8374 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8375 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8376   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8377   SDValue Op0 = N->getOperand(0);
8378   SDValue Op1 = N->getOperand(1);
8379   if (Op0.getOpcode() == ISD::BITCAST)
8380     Op0 = Op0.getOperand(0);
8381   if (Op1.getOpcode() == ISD::BITCAST)
8382     Op1 = Op1.getOperand(0);
8383   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8384       Op0.getNode() == Op1.getNode() &&
8385       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8386     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8387                        N->getValueType(0), Op0.getOperand(0));
8388   return SDValue();
8389 }
8390
8391 /// PerformSTORECombine - Target-specific dag combine xforms for
8392 /// ISD::STORE.
8393 static SDValue PerformSTORECombine(SDNode *N,
8394                                    TargetLowering::DAGCombinerInfo &DCI) {
8395   StoreSDNode *St = cast<StoreSDNode>(N);
8396   if (St->isVolatile())
8397     return SDValue();
8398
8399   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8400   // pack all of the elements in one place.  Next, store to memory in fewer
8401   // chunks.
8402   SDValue StVal = St->getValue();
8403   EVT VT = StVal.getValueType();
8404   if (St->isTruncatingStore() && VT.isVector()) {
8405     SelectionDAG &DAG = DCI.DAG;
8406     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8407     EVT StVT = St->getMemoryVT();
8408     unsigned NumElems = VT.getVectorNumElements();
8409     assert(StVT != VT && "Cannot truncate to the same type");
8410     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8411     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8412
8413     // From, To sizes and ElemCount must be pow of two
8414     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8415
8416     // We are going to use the original vector elt for storing.
8417     // Accumulated smaller vector elements must be a multiple of the store size.
8418     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8419
8420     unsigned SizeRatio  = FromEltSz / ToEltSz;
8421     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8422
8423     // Create a type on which we perform the shuffle.
8424     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8425                                      NumElems*SizeRatio);
8426     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8427
8428     DebugLoc DL = St->getDebugLoc();
8429     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8430     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8431     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8432
8433     // Can't shuffle using an illegal type.
8434     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8435
8436     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8437                                 DAG.getUNDEF(WideVec.getValueType()),
8438                                 ShuffleVec.data());
8439     // At this point all of the data is stored at the bottom of the
8440     // register. We now need to save it to mem.
8441
8442     // Find the largest store unit
8443     MVT StoreType = MVT::i8;
8444     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8445          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8446       MVT Tp = (MVT::SimpleValueType)tp;
8447       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8448         StoreType = Tp;
8449     }
8450     // Didn't find a legal store type.
8451     if (!TLI.isTypeLegal(StoreType))
8452       return SDValue();
8453
8454     // Bitcast the original vector into a vector of store-size units
8455     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8456             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8457     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8458     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8459     SmallVector<SDValue, 8> Chains;
8460     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8461                                         TLI.getPointerTy());
8462     SDValue BasePtr = St->getBasePtr();
8463
8464     // Perform one or more big stores into memory.
8465     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8466     for (unsigned I = 0; I < E; I++) {
8467       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8468                                    StoreType, ShuffWide,
8469                                    DAG.getIntPtrConstant(I));
8470       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8471                                 St->getPointerInfo(), St->isVolatile(),
8472                                 St->isNonTemporal(), St->getAlignment());
8473       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8474                             Increment);
8475       Chains.push_back(Ch);
8476     }
8477     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8478                        Chains.size());
8479   }
8480
8481   if (!ISD::isNormalStore(St))
8482     return SDValue();
8483
8484   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8485   // ARM stores of arguments in the same cache line.
8486   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8487       StVal.getNode()->hasOneUse()) {
8488     SelectionDAG  &DAG = DCI.DAG;
8489     DebugLoc DL = St->getDebugLoc();
8490     SDValue BasePtr = St->getBasePtr();
8491     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8492                                   StVal.getNode()->getOperand(0), BasePtr,
8493                                   St->getPointerInfo(), St->isVolatile(),
8494                                   St->isNonTemporal(), St->getAlignment());
8495
8496     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8497                                     DAG.getConstant(4, MVT::i32));
8498     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8499                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8500                         St->isNonTemporal(),
8501                         std::min(4U, St->getAlignment() / 2));
8502   }
8503
8504   if (StVal.getValueType() != MVT::i64 ||
8505       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8506     return SDValue();
8507
8508   // Bitcast an i64 store extracted from a vector to f64.
8509   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8510   SelectionDAG &DAG = DCI.DAG;
8511   DebugLoc dl = StVal.getDebugLoc();
8512   SDValue IntVec = StVal.getOperand(0);
8513   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8514                                  IntVec.getValueType().getVectorNumElements());
8515   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8516   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8517                                Vec, StVal.getOperand(1));
8518   dl = N->getDebugLoc();
8519   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8520   // Make the DAGCombiner fold the bitcasts.
8521   DCI.AddToWorklist(Vec.getNode());
8522   DCI.AddToWorklist(ExtElt.getNode());
8523   DCI.AddToWorklist(V.getNode());
8524   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8525                       St->getPointerInfo(), St->isVolatile(),
8526                       St->isNonTemporal(), St->getAlignment(),
8527                       St->getTBAAInfo());
8528 }
8529
8530 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8531 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8532 /// i64 vector to have f64 elements, since the value can then be loaded
8533 /// directly into a VFP register.
8534 static bool hasNormalLoadOperand(SDNode *N) {
8535   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8536   for (unsigned i = 0; i < NumElts; ++i) {
8537     SDNode *Elt = N->getOperand(i).getNode();
8538     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8539       return true;
8540   }
8541   return false;
8542 }
8543
8544 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8545 /// ISD::BUILD_VECTOR.
8546 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8547                                           TargetLowering::DAGCombinerInfo &DCI){
8548   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8549   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8550   // into a pair of GPRs, which is fine when the value is used as a scalar,
8551   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8552   SelectionDAG &DAG = DCI.DAG;
8553   if (N->getNumOperands() == 2) {
8554     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8555     if (RV.getNode())
8556       return RV;
8557   }
8558
8559   // Load i64 elements as f64 values so that type legalization does not split
8560   // them up into i32 values.
8561   EVT VT = N->getValueType(0);
8562   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8563     return SDValue();
8564   DebugLoc dl = N->getDebugLoc();
8565   SmallVector<SDValue, 8> Ops;
8566   unsigned NumElts = VT.getVectorNumElements();
8567   for (unsigned i = 0; i < NumElts; ++i) {
8568     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8569     Ops.push_back(V);
8570     // Make the DAGCombiner fold the bitcast.
8571     DCI.AddToWorklist(V.getNode());
8572   }
8573   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8574   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8575   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8576 }
8577
8578 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8579 /// ISD::INSERT_VECTOR_ELT.
8580 static SDValue PerformInsertEltCombine(SDNode *N,
8581                                        TargetLowering::DAGCombinerInfo &DCI) {
8582   // Bitcast an i64 load inserted into a vector to f64.
8583   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8584   EVT VT = N->getValueType(0);
8585   SDNode *Elt = N->getOperand(1).getNode();
8586   if (VT.getVectorElementType() != MVT::i64 ||
8587       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8588     return SDValue();
8589
8590   SelectionDAG &DAG = DCI.DAG;
8591   DebugLoc dl = N->getDebugLoc();
8592   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8593                                  VT.getVectorNumElements());
8594   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8595   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8596   // Make the DAGCombiner fold the bitcasts.
8597   DCI.AddToWorklist(Vec.getNode());
8598   DCI.AddToWorklist(V.getNode());
8599   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8600                                Vec, V, N->getOperand(2));
8601   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8602 }
8603
8604 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8605 /// ISD::VECTOR_SHUFFLE.
8606 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8607   // The LLVM shufflevector instruction does not require the shuffle mask
8608   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8609   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8610   // operands do not match the mask length, they are extended by concatenating
8611   // them with undef vectors.  That is probably the right thing for other
8612   // targets, but for NEON it is better to concatenate two double-register
8613   // size vector operands into a single quad-register size vector.  Do that
8614   // transformation here:
8615   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8616   //   shuffle(concat(v1, v2), undef)
8617   SDValue Op0 = N->getOperand(0);
8618   SDValue Op1 = N->getOperand(1);
8619   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8620       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8621       Op0.getNumOperands() != 2 ||
8622       Op1.getNumOperands() != 2)
8623     return SDValue();
8624   SDValue Concat0Op1 = Op0.getOperand(1);
8625   SDValue Concat1Op1 = Op1.getOperand(1);
8626   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8627       Concat1Op1.getOpcode() != ISD::UNDEF)
8628     return SDValue();
8629   // Skip the transformation if any of the types are illegal.
8630   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8631   EVT VT = N->getValueType(0);
8632   if (!TLI.isTypeLegal(VT) ||
8633       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8634       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8635     return SDValue();
8636
8637   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8638                                   Op0.getOperand(0), Op1.getOperand(0));
8639   // Translate the shuffle mask.
8640   SmallVector<int, 16> NewMask;
8641   unsigned NumElts = VT.getVectorNumElements();
8642   unsigned HalfElts = NumElts/2;
8643   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8644   for (unsigned n = 0; n < NumElts; ++n) {
8645     int MaskElt = SVN->getMaskElt(n);
8646     int NewElt = -1;
8647     if (MaskElt < (int)HalfElts)
8648       NewElt = MaskElt;
8649     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8650       NewElt = HalfElts + MaskElt - NumElts;
8651     NewMask.push_back(NewElt);
8652   }
8653   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8654                               DAG.getUNDEF(VT), NewMask.data());
8655 }
8656
8657 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8658 /// NEON load/store intrinsics to merge base address updates.
8659 static SDValue CombineBaseUpdate(SDNode *N,
8660                                  TargetLowering::DAGCombinerInfo &DCI) {
8661   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8662     return SDValue();
8663
8664   SelectionDAG &DAG = DCI.DAG;
8665   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8666                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8667   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8668   SDValue Addr = N->getOperand(AddrOpIdx);
8669
8670   // Search for a use of the address operand that is an increment.
8671   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8672          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8673     SDNode *User = *UI;
8674     if (User->getOpcode() != ISD::ADD ||
8675         UI.getUse().getResNo() != Addr.getResNo())
8676       continue;
8677
8678     // Check that the add is independent of the load/store.  Otherwise, folding
8679     // it would create a cycle.
8680     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8681       continue;
8682
8683     // Find the new opcode for the updating load/store.
8684     bool isLoad = true;
8685     bool isLaneOp = false;
8686     unsigned NewOpc = 0;
8687     unsigned NumVecs = 0;
8688     if (isIntrinsic) {
8689       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8690       switch (IntNo) {
8691       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8692       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8693         NumVecs = 1; break;
8694       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8695         NumVecs = 2; break;
8696       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8697         NumVecs = 3; break;
8698       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8699         NumVecs = 4; break;
8700       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8701         NumVecs = 2; isLaneOp = true; break;
8702       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8703         NumVecs = 3; isLaneOp = true; break;
8704       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8705         NumVecs = 4; isLaneOp = true; break;
8706       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8707         NumVecs = 1; isLoad = false; break;
8708       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8709         NumVecs = 2; isLoad = false; break;
8710       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8711         NumVecs = 3; isLoad = false; break;
8712       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8713         NumVecs = 4; isLoad = false; break;
8714       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8715         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8716       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8717         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8718       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8719         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8720       }
8721     } else {
8722       isLaneOp = true;
8723       switch (N->getOpcode()) {
8724       default: llvm_unreachable("unexpected opcode for Neon base update");
8725       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8726       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8727       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8728       }
8729     }
8730
8731     // Find the size of memory referenced by the load/store.
8732     EVT VecTy;
8733     if (isLoad)
8734       VecTy = N->getValueType(0);
8735     else
8736       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8737     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8738     if (isLaneOp)
8739       NumBytes /= VecTy.getVectorNumElements();
8740
8741     // If the increment is a constant, it must match the memory ref size.
8742     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8743     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8744       uint64_t IncVal = CInc->getZExtValue();
8745       if (IncVal != NumBytes)
8746         continue;
8747     } else if (NumBytes >= 3 * 16) {
8748       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8749       // separate instructions that make it harder to use a non-constant update.
8750       continue;
8751     }
8752
8753     // Create the new updating load/store node.
8754     EVT Tys[6];
8755     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8756     unsigned n;
8757     for (n = 0; n < NumResultVecs; ++n)
8758       Tys[n] = VecTy;
8759     Tys[n++] = MVT::i32;
8760     Tys[n] = MVT::Other;
8761     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8762     SmallVector<SDValue, 8> Ops;
8763     Ops.push_back(N->getOperand(0)); // incoming chain
8764     Ops.push_back(N->getOperand(AddrOpIdx));
8765     Ops.push_back(Inc);
8766     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8767       Ops.push_back(N->getOperand(i));
8768     }
8769     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8770     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8771                                            Ops.data(), Ops.size(),
8772                                            MemInt->getMemoryVT(),
8773                                            MemInt->getMemOperand());
8774
8775     // Update the uses.
8776     std::vector<SDValue> NewResults;
8777     for (unsigned i = 0; i < NumResultVecs; ++i) {
8778       NewResults.push_back(SDValue(UpdN.getNode(), i));
8779     }
8780     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8781     DCI.CombineTo(N, NewResults);
8782     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8783
8784     break;
8785   }
8786   return SDValue();
8787 }
8788
8789 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8790 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8791 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8792 /// return true.
8793 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8794   SelectionDAG &DAG = DCI.DAG;
8795   EVT VT = N->getValueType(0);
8796   // vldN-dup instructions only support 64-bit vectors for N > 1.
8797   if (!VT.is64BitVector())
8798     return false;
8799
8800   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8801   SDNode *VLD = N->getOperand(0).getNode();
8802   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8803     return false;
8804   unsigned NumVecs = 0;
8805   unsigned NewOpc = 0;
8806   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8807   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8808     NumVecs = 2;
8809     NewOpc = ARMISD::VLD2DUP;
8810   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8811     NumVecs = 3;
8812     NewOpc = ARMISD::VLD3DUP;
8813   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8814     NumVecs = 4;
8815     NewOpc = ARMISD::VLD4DUP;
8816   } else {
8817     return false;
8818   }
8819
8820   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8821   // numbers match the load.
8822   unsigned VLDLaneNo =
8823     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8824   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8825        UI != UE; ++UI) {
8826     // Ignore uses of the chain result.
8827     if (UI.getUse().getResNo() == NumVecs)
8828       continue;
8829     SDNode *User = *UI;
8830     if (User->getOpcode() != ARMISD::VDUPLANE ||
8831         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8832       return false;
8833   }
8834
8835   // Create the vldN-dup node.
8836   EVT Tys[5];
8837   unsigned n;
8838   for (n = 0; n < NumVecs; ++n)
8839     Tys[n] = VT;
8840   Tys[n] = MVT::Other;
8841   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8842   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8843   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8844   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8845                                            Ops, 2, VLDMemInt->getMemoryVT(),
8846                                            VLDMemInt->getMemOperand());
8847
8848   // Update the uses.
8849   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8850        UI != UE; ++UI) {
8851     unsigned ResNo = UI.getUse().getResNo();
8852     // Ignore uses of the chain result.
8853     if (ResNo == NumVecs)
8854       continue;
8855     SDNode *User = *UI;
8856     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8857   }
8858
8859   // Now the vldN-lane intrinsic is dead except for its chain result.
8860   // Update uses of the chain.
8861   std::vector<SDValue> VLDDupResults;
8862   for (unsigned n = 0; n < NumVecs; ++n)
8863     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8864   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8865   DCI.CombineTo(VLD, VLDDupResults);
8866
8867   return true;
8868 }
8869
8870 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8871 /// ARMISD::VDUPLANE.
8872 static SDValue PerformVDUPLANECombine(SDNode *N,
8873                                       TargetLowering::DAGCombinerInfo &DCI) {
8874   SDValue Op = N->getOperand(0);
8875
8876   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8877   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8878   if (CombineVLDDUP(N, DCI))
8879     return SDValue(N, 0);
8880
8881   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8882   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8883   while (Op.getOpcode() == ISD::BITCAST)
8884     Op = Op.getOperand(0);
8885   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8886     return SDValue();
8887
8888   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8889   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8890   // The canonical VMOV for a zero vector uses a 32-bit element size.
8891   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8892   unsigned EltBits;
8893   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8894     EltSize = 8;
8895   EVT VT = N->getValueType(0);
8896   if (EltSize > VT.getVectorElementType().getSizeInBits())
8897     return SDValue();
8898
8899   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8900 }
8901
8902 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8903 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8904 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8905 {
8906   integerPart cN;
8907   integerPart c0 = 0;
8908   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8909        I != E; I++) {
8910     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8911     if (!C)
8912       return false;
8913
8914     bool isExact;
8915     APFloat APF = C->getValueAPF();
8916     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8917         != APFloat::opOK || !isExact)
8918       return false;
8919
8920     c0 = (I == 0) ? cN : c0;
8921     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8922       return false;
8923   }
8924   C = c0;
8925   return true;
8926 }
8927
8928 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8929 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8930 /// when the VMUL has a constant operand that is a power of 2.
8931 ///
8932 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8933 ///  vmul.f32        d16, d17, d16
8934 ///  vcvt.s32.f32    d16, d16
8935 /// becomes:
8936 ///  vcvt.s32.f32    d16, d16, #3
8937 static SDValue PerformVCVTCombine(SDNode *N,
8938                                   TargetLowering::DAGCombinerInfo &DCI,
8939                                   const ARMSubtarget *Subtarget) {
8940   SelectionDAG &DAG = DCI.DAG;
8941   SDValue Op = N->getOperand(0);
8942
8943   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8944       Op.getOpcode() != ISD::FMUL)
8945     return SDValue();
8946
8947   uint64_t C;
8948   SDValue N0 = Op->getOperand(0);
8949   SDValue ConstVec = Op->getOperand(1);
8950   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8951
8952   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8953       !isConstVecPow2(ConstVec, isSigned, C))
8954     return SDValue();
8955
8956   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8957     Intrinsic::arm_neon_vcvtfp2fxu;
8958   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8959                      N->getValueType(0),
8960                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8961                      DAG.getConstant(Log2_64(C), MVT::i32));
8962 }
8963
8964 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8965 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8966 /// when the VDIV has a constant operand that is a power of 2.
8967 ///
8968 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8969 ///  vcvt.f32.s32    d16, d16
8970 ///  vdiv.f32        d16, d17, d16
8971 /// becomes:
8972 ///  vcvt.f32.s32    d16, d16, #3
8973 static SDValue PerformVDIVCombine(SDNode *N,
8974                                   TargetLowering::DAGCombinerInfo &DCI,
8975                                   const ARMSubtarget *Subtarget) {
8976   SelectionDAG &DAG = DCI.DAG;
8977   SDValue Op = N->getOperand(0);
8978   unsigned OpOpcode = Op.getNode()->getOpcode();
8979
8980   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8981       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8982     return SDValue();
8983
8984   uint64_t C;
8985   SDValue ConstVec = N->getOperand(1);
8986   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8987
8988   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8989       !isConstVecPow2(ConstVec, isSigned, C))
8990     return SDValue();
8991
8992   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8993     Intrinsic::arm_neon_vcvtfxu2fp;
8994   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8995                      Op.getValueType(),
8996                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8997                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8998 }
8999
9000 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9001 /// operand of a vector shift operation, where all the elements of the
9002 /// build_vector must have the same constant integer value.
9003 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9004   // Ignore bit_converts.
9005   while (Op.getOpcode() == ISD::BITCAST)
9006     Op = Op.getOperand(0);
9007   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9008   APInt SplatBits, SplatUndef;
9009   unsigned SplatBitSize;
9010   bool HasAnyUndefs;
9011   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9012                                       HasAnyUndefs, ElementBits) ||
9013       SplatBitSize > ElementBits)
9014     return false;
9015   Cnt = SplatBits.getSExtValue();
9016   return true;
9017 }
9018
9019 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9020 /// operand of a vector shift left operation.  That value must be in the range:
9021 ///   0 <= Value < ElementBits for a left shift; or
9022 ///   0 <= Value <= ElementBits for a long left shift.
9023 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9024   assert(VT.isVector() && "vector shift count is not a vector type");
9025   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9026   if (! getVShiftImm(Op, ElementBits, Cnt))
9027     return false;
9028   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9029 }
9030
9031 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9032 /// operand of a vector shift right operation.  For a shift opcode, the value
9033 /// is positive, but for an intrinsic the value count must be negative. The
9034 /// absolute value must be in the range:
9035 ///   1 <= |Value| <= ElementBits for a right shift; or
9036 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9037 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9038                          int64_t &Cnt) {
9039   assert(VT.isVector() && "vector shift count is not a vector type");
9040   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9041   if (! getVShiftImm(Op, ElementBits, Cnt))
9042     return false;
9043   if (isIntrinsic)
9044     Cnt = -Cnt;
9045   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9046 }
9047
9048 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9049 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9050   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9051   switch (IntNo) {
9052   default:
9053     // Don't do anything for most intrinsics.
9054     break;
9055
9056   // Vector shifts: check for immediate versions and lower them.
9057   // Note: This is done during DAG combining instead of DAG legalizing because
9058   // the build_vectors for 64-bit vector element shift counts are generally
9059   // not legal, and it is hard to see their values after they get legalized to
9060   // loads from a constant pool.
9061   case Intrinsic::arm_neon_vshifts:
9062   case Intrinsic::arm_neon_vshiftu:
9063   case Intrinsic::arm_neon_vshiftls:
9064   case Intrinsic::arm_neon_vshiftlu:
9065   case Intrinsic::arm_neon_vshiftn:
9066   case Intrinsic::arm_neon_vrshifts:
9067   case Intrinsic::arm_neon_vrshiftu:
9068   case Intrinsic::arm_neon_vrshiftn:
9069   case Intrinsic::arm_neon_vqshifts:
9070   case Intrinsic::arm_neon_vqshiftu:
9071   case Intrinsic::arm_neon_vqshiftsu:
9072   case Intrinsic::arm_neon_vqshiftns:
9073   case Intrinsic::arm_neon_vqshiftnu:
9074   case Intrinsic::arm_neon_vqshiftnsu:
9075   case Intrinsic::arm_neon_vqrshiftns:
9076   case Intrinsic::arm_neon_vqrshiftnu:
9077   case Intrinsic::arm_neon_vqrshiftnsu: {
9078     EVT VT = N->getOperand(1).getValueType();
9079     int64_t Cnt;
9080     unsigned VShiftOpc = 0;
9081
9082     switch (IntNo) {
9083     case Intrinsic::arm_neon_vshifts:
9084     case Intrinsic::arm_neon_vshiftu:
9085       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9086         VShiftOpc = ARMISD::VSHL;
9087         break;
9088       }
9089       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9090         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9091                      ARMISD::VSHRs : ARMISD::VSHRu);
9092         break;
9093       }
9094       return SDValue();
9095
9096     case Intrinsic::arm_neon_vshiftls:
9097     case Intrinsic::arm_neon_vshiftlu:
9098       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9099         break;
9100       llvm_unreachable("invalid shift count for vshll intrinsic");
9101
9102     case Intrinsic::arm_neon_vrshifts:
9103     case Intrinsic::arm_neon_vrshiftu:
9104       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9105         break;
9106       return SDValue();
9107
9108     case Intrinsic::arm_neon_vqshifts:
9109     case Intrinsic::arm_neon_vqshiftu:
9110       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9111         break;
9112       return SDValue();
9113
9114     case Intrinsic::arm_neon_vqshiftsu:
9115       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9116         break;
9117       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9118
9119     case Intrinsic::arm_neon_vshiftn:
9120     case Intrinsic::arm_neon_vrshiftn:
9121     case Intrinsic::arm_neon_vqshiftns:
9122     case Intrinsic::arm_neon_vqshiftnu:
9123     case Intrinsic::arm_neon_vqshiftnsu:
9124     case Intrinsic::arm_neon_vqrshiftns:
9125     case Intrinsic::arm_neon_vqrshiftnu:
9126     case Intrinsic::arm_neon_vqrshiftnsu:
9127       // Narrowing shifts require an immediate right shift.
9128       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9129         break;
9130       llvm_unreachable("invalid shift count for narrowing vector shift "
9131                        "intrinsic");
9132
9133     default:
9134       llvm_unreachable("unhandled vector shift");
9135     }
9136
9137     switch (IntNo) {
9138     case Intrinsic::arm_neon_vshifts:
9139     case Intrinsic::arm_neon_vshiftu:
9140       // Opcode already set above.
9141       break;
9142     case Intrinsic::arm_neon_vshiftls:
9143     case Intrinsic::arm_neon_vshiftlu:
9144       if (Cnt == VT.getVectorElementType().getSizeInBits())
9145         VShiftOpc = ARMISD::VSHLLi;
9146       else
9147         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9148                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9149       break;
9150     case Intrinsic::arm_neon_vshiftn:
9151       VShiftOpc = ARMISD::VSHRN; break;
9152     case Intrinsic::arm_neon_vrshifts:
9153       VShiftOpc = ARMISD::VRSHRs; break;
9154     case Intrinsic::arm_neon_vrshiftu:
9155       VShiftOpc = ARMISD::VRSHRu; break;
9156     case Intrinsic::arm_neon_vrshiftn:
9157       VShiftOpc = ARMISD::VRSHRN; break;
9158     case Intrinsic::arm_neon_vqshifts:
9159       VShiftOpc = ARMISD::VQSHLs; break;
9160     case Intrinsic::arm_neon_vqshiftu:
9161       VShiftOpc = ARMISD::VQSHLu; break;
9162     case Intrinsic::arm_neon_vqshiftsu:
9163       VShiftOpc = ARMISD::VQSHLsu; break;
9164     case Intrinsic::arm_neon_vqshiftns:
9165       VShiftOpc = ARMISD::VQSHRNs; break;
9166     case Intrinsic::arm_neon_vqshiftnu:
9167       VShiftOpc = ARMISD::VQSHRNu; break;
9168     case Intrinsic::arm_neon_vqshiftnsu:
9169       VShiftOpc = ARMISD::VQSHRNsu; break;
9170     case Intrinsic::arm_neon_vqrshiftns:
9171       VShiftOpc = ARMISD::VQRSHRNs; break;
9172     case Intrinsic::arm_neon_vqrshiftnu:
9173       VShiftOpc = ARMISD::VQRSHRNu; break;
9174     case Intrinsic::arm_neon_vqrshiftnsu:
9175       VShiftOpc = ARMISD::VQRSHRNsu; break;
9176     }
9177
9178     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9179                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9180   }
9181
9182   case Intrinsic::arm_neon_vshiftins: {
9183     EVT VT = N->getOperand(1).getValueType();
9184     int64_t Cnt;
9185     unsigned VShiftOpc = 0;
9186
9187     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9188       VShiftOpc = ARMISD::VSLI;
9189     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9190       VShiftOpc = ARMISD::VSRI;
9191     else {
9192       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9193     }
9194
9195     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9196                        N->getOperand(1), N->getOperand(2),
9197                        DAG.getConstant(Cnt, MVT::i32));
9198   }
9199
9200   case Intrinsic::arm_neon_vqrshifts:
9201   case Intrinsic::arm_neon_vqrshiftu:
9202     // No immediate versions of these to check for.
9203     break;
9204   }
9205
9206   return SDValue();
9207 }
9208
9209 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9210 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9211 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9212 /// vector element shift counts are generally not legal, and it is hard to see
9213 /// their values after they get legalized to loads from a constant pool.
9214 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9215                                    const ARMSubtarget *ST) {
9216   EVT VT = N->getValueType(0);
9217   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9218     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9219     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9220     SDValue N1 = N->getOperand(1);
9221     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9222       SDValue N0 = N->getOperand(0);
9223       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9224           DAG.MaskedValueIsZero(N0.getOperand(0),
9225                                 APInt::getHighBitsSet(32, 16)))
9226         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9227     }
9228   }
9229
9230   // Nothing to be done for scalar shifts.
9231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9232   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9233     return SDValue();
9234
9235   assert(ST->hasNEON() && "unexpected vector shift");
9236   int64_t Cnt;
9237
9238   switch (N->getOpcode()) {
9239   default: llvm_unreachable("unexpected shift opcode");
9240
9241   case ISD::SHL:
9242     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9243       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9244                          DAG.getConstant(Cnt, MVT::i32));
9245     break;
9246
9247   case ISD::SRA:
9248   case ISD::SRL:
9249     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9250       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9251                             ARMISD::VSHRs : ARMISD::VSHRu);
9252       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9253                          DAG.getConstant(Cnt, MVT::i32));
9254     }
9255   }
9256   return SDValue();
9257 }
9258
9259 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9260 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9261 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9262                                     const ARMSubtarget *ST) {
9263   SDValue N0 = N->getOperand(0);
9264
9265   // Check for sign- and zero-extensions of vector extract operations of 8-
9266   // and 16-bit vector elements.  NEON supports these directly.  They are
9267   // handled during DAG combining because type legalization will promote them
9268   // to 32-bit types and it is messy to recognize the operations after that.
9269   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9270     SDValue Vec = N0.getOperand(0);
9271     SDValue Lane = N0.getOperand(1);
9272     EVT VT = N->getValueType(0);
9273     EVT EltVT = N0.getValueType();
9274     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9275
9276     if (VT == MVT::i32 &&
9277         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9278         TLI.isTypeLegal(Vec.getValueType()) &&
9279         isa<ConstantSDNode>(Lane)) {
9280
9281       unsigned Opc = 0;
9282       switch (N->getOpcode()) {
9283       default: llvm_unreachable("unexpected opcode");
9284       case ISD::SIGN_EXTEND:
9285         Opc = ARMISD::VGETLANEs;
9286         break;
9287       case ISD::ZERO_EXTEND:
9288       case ISD::ANY_EXTEND:
9289         Opc = ARMISD::VGETLANEu;
9290         break;
9291       }
9292       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9293     }
9294   }
9295
9296   return SDValue();
9297 }
9298
9299 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9300 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9301 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9302                                        const ARMSubtarget *ST) {
9303   // If the target supports NEON, try to use vmax/vmin instructions for f32
9304   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9305   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9306   // a NaN; only do the transformation when it matches that behavior.
9307
9308   // For now only do this when using NEON for FP operations; if using VFP, it
9309   // is not obvious that the benefit outweighs the cost of switching to the
9310   // NEON pipeline.
9311   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9312       N->getValueType(0) != MVT::f32)
9313     return SDValue();
9314
9315   SDValue CondLHS = N->getOperand(0);
9316   SDValue CondRHS = N->getOperand(1);
9317   SDValue LHS = N->getOperand(2);
9318   SDValue RHS = N->getOperand(3);
9319   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9320
9321   unsigned Opcode = 0;
9322   bool IsReversed;
9323   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9324     IsReversed = false; // x CC y ? x : y
9325   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9326     IsReversed = true ; // x CC y ? y : x
9327   } else {
9328     return SDValue();
9329   }
9330
9331   bool IsUnordered;
9332   switch (CC) {
9333   default: break;
9334   case ISD::SETOLT:
9335   case ISD::SETOLE:
9336   case ISD::SETLT:
9337   case ISD::SETLE:
9338   case ISD::SETULT:
9339   case ISD::SETULE:
9340     // If LHS is NaN, an ordered comparison will be false and the result will
9341     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9342     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9343     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9344     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9345       break;
9346     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9347     // will return -0, so vmin can only be used for unsafe math or if one of
9348     // the operands is known to be nonzero.
9349     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9350         !DAG.getTarget().Options.UnsafeFPMath &&
9351         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9352       break;
9353     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9354     break;
9355
9356   case ISD::SETOGT:
9357   case ISD::SETOGE:
9358   case ISD::SETGT:
9359   case ISD::SETGE:
9360   case ISD::SETUGT:
9361   case ISD::SETUGE:
9362     // If LHS is NaN, an ordered comparison will be false and the result will
9363     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9364     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9365     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9366     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9367       break;
9368     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9369     // will return +0, so vmax can only be used for unsafe math or if one of
9370     // the operands is known to be nonzero.
9371     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9372         !DAG.getTarget().Options.UnsafeFPMath &&
9373         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9374       break;
9375     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9376     break;
9377   }
9378
9379   if (!Opcode)
9380     return SDValue();
9381   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9382 }
9383
9384 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9385 SDValue
9386 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9387   SDValue Cmp = N->getOperand(4);
9388   if (Cmp.getOpcode() != ARMISD::CMPZ)
9389     // Only looking at EQ and NE cases.
9390     return SDValue();
9391
9392   EVT VT = N->getValueType(0);
9393   DebugLoc dl = N->getDebugLoc();
9394   SDValue LHS = Cmp.getOperand(0);
9395   SDValue RHS = Cmp.getOperand(1);
9396   SDValue FalseVal = N->getOperand(0);
9397   SDValue TrueVal = N->getOperand(1);
9398   SDValue ARMcc = N->getOperand(2);
9399   ARMCC::CondCodes CC =
9400     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9401
9402   // Simplify
9403   //   mov     r1, r0
9404   //   cmp     r1, x
9405   //   mov     r0, y
9406   //   moveq   r0, x
9407   // to
9408   //   cmp     r0, x
9409   //   movne   r0, y
9410   //
9411   //   mov     r1, r0
9412   //   cmp     r1, x
9413   //   mov     r0, x
9414   //   movne   r0, y
9415   // to
9416   //   cmp     r0, x
9417   //   movne   r0, y
9418   /// FIXME: Turn this into a target neutral optimization?
9419   SDValue Res;
9420   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9421     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9422                       N->getOperand(3), Cmp);
9423   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9424     SDValue ARMcc;
9425     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9426     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9427                       N->getOperand(3), NewCmp);
9428   }
9429
9430   if (Res.getNode()) {
9431     APInt KnownZero, KnownOne;
9432     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9433     // Capture demanded bits information that would be otherwise lost.
9434     if (KnownZero == 0xfffffffe)
9435       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9436                         DAG.getValueType(MVT::i1));
9437     else if (KnownZero == 0xffffff00)
9438       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9439                         DAG.getValueType(MVT::i8));
9440     else if (KnownZero == 0xffff0000)
9441       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9442                         DAG.getValueType(MVT::i16));
9443   }
9444
9445   return Res;
9446 }
9447
9448 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9449                                              DAGCombinerInfo &DCI) const {
9450   switch (N->getOpcode()) {
9451   default: break;
9452   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9453   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9454   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9455   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9456   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9457   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9458   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9459   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9460   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9461   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9462   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9463   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9464   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9465   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9466   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9467   case ISD::FP_TO_SINT:
9468   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9469   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9470   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9471   case ISD::SHL:
9472   case ISD::SRA:
9473   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9474   case ISD::SIGN_EXTEND:
9475   case ISD::ZERO_EXTEND:
9476   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9477   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9478   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9479   case ARMISD::VLD2DUP:
9480   case ARMISD::VLD3DUP:
9481   case ARMISD::VLD4DUP:
9482     return CombineBaseUpdate(N, DCI);
9483   case ISD::INTRINSIC_VOID:
9484   case ISD::INTRINSIC_W_CHAIN:
9485     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9486     case Intrinsic::arm_neon_vld1:
9487     case Intrinsic::arm_neon_vld2:
9488     case Intrinsic::arm_neon_vld3:
9489     case Intrinsic::arm_neon_vld4:
9490     case Intrinsic::arm_neon_vld2lane:
9491     case Intrinsic::arm_neon_vld3lane:
9492     case Intrinsic::arm_neon_vld4lane:
9493     case Intrinsic::arm_neon_vst1:
9494     case Intrinsic::arm_neon_vst2:
9495     case Intrinsic::arm_neon_vst3:
9496     case Intrinsic::arm_neon_vst4:
9497     case Intrinsic::arm_neon_vst2lane:
9498     case Intrinsic::arm_neon_vst3lane:
9499     case Intrinsic::arm_neon_vst4lane:
9500       return CombineBaseUpdate(N, DCI);
9501     default: break;
9502     }
9503     break;
9504   }
9505   return SDValue();
9506 }
9507
9508 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9509                                                           EVT VT) const {
9510   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9511 }
9512
9513 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9514   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9515   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9516
9517   switch (VT.getSimpleVT().SimpleTy) {
9518   default:
9519     return false;
9520   case MVT::i8:
9521   case MVT::i16:
9522   case MVT::i32: {
9523     // Unaligned access can use (for example) LRDB, LRDH, LDR
9524     if (AllowsUnaligned) {
9525       if (Fast)
9526         *Fast = Subtarget->hasV7Ops();
9527       return true;
9528     }
9529     return false;
9530   }
9531   case MVT::f64:
9532   case MVT::v2f64: {
9533     // For any little-endian targets with neon, we can support unaligned ld/st
9534     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9535     // A big-endian target may also explictly support unaligned accesses
9536     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9537       if (Fast)
9538         *Fast = true;
9539       return true;
9540     }
9541     return false;
9542   }
9543   }
9544 }
9545
9546 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9547                        unsigned AlignCheck) {
9548   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9549           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9550 }
9551
9552 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9553                                            unsigned DstAlign, unsigned SrcAlign,
9554                                            bool IsMemset, bool ZeroMemset,
9555                                            bool MemcpyStrSrc,
9556                                            MachineFunction &MF) const {
9557   const Function *F = MF.getFunction();
9558
9559   // See if we can use NEON instructions for this...
9560   if ((!IsMemset || ZeroMemset) &&
9561       Subtarget->hasNEON() &&
9562       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9563                                        Attribute::NoImplicitFloat)) {
9564     bool Fast;
9565     if (Size >= 16 &&
9566         (memOpAlign(SrcAlign, DstAlign, 16) ||
9567          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9568       return MVT::v2f64;
9569     } else if (Size >= 8 &&
9570                (memOpAlign(SrcAlign, DstAlign, 8) ||
9571                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9572       return MVT::f64;
9573     }
9574   }
9575
9576   // Lowering to i32/i16 if the size permits.
9577   if (Size >= 4)
9578     return MVT::i32;
9579   else if (Size >= 2)
9580     return MVT::i16;
9581
9582   // Let the target-independent logic figure it out.
9583   return MVT::Other;
9584 }
9585
9586 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9587   if (Val.getOpcode() != ISD::LOAD)
9588     return false;
9589
9590   EVT VT1 = Val.getValueType();
9591   if (!VT1.isSimple() || !VT1.isInteger() ||
9592       !VT2.isSimple() || !VT2.isInteger())
9593     return false;
9594
9595   switch (VT1.getSimpleVT().SimpleTy) {
9596   default: break;
9597   case MVT::i1:
9598   case MVT::i8:
9599   case MVT::i16:
9600     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9601     return true;
9602   }
9603
9604   return false;
9605 }
9606
9607 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9608   if (V < 0)
9609     return false;
9610
9611   unsigned Scale = 1;
9612   switch (VT.getSimpleVT().SimpleTy) {
9613   default: return false;
9614   case MVT::i1:
9615   case MVT::i8:
9616     // Scale == 1;
9617     break;
9618   case MVT::i16:
9619     // Scale == 2;
9620     Scale = 2;
9621     break;
9622   case MVT::i32:
9623     // Scale == 4;
9624     Scale = 4;
9625     break;
9626   }
9627
9628   if ((V & (Scale - 1)) != 0)
9629     return false;
9630   V /= Scale;
9631   return V == (V & ((1LL << 5) - 1));
9632 }
9633
9634 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9635                                       const ARMSubtarget *Subtarget) {
9636   bool isNeg = false;
9637   if (V < 0) {
9638     isNeg = true;
9639     V = - V;
9640   }
9641
9642   switch (VT.getSimpleVT().SimpleTy) {
9643   default: return false;
9644   case MVT::i1:
9645   case MVT::i8:
9646   case MVT::i16:
9647   case MVT::i32:
9648     // + imm12 or - imm8
9649     if (isNeg)
9650       return V == (V & ((1LL << 8) - 1));
9651     return V == (V & ((1LL << 12) - 1));
9652   case MVT::f32:
9653   case MVT::f64:
9654     // Same as ARM mode. FIXME: NEON?
9655     if (!Subtarget->hasVFP2())
9656       return false;
9657     if ((V & 3) != 0)
9658       return false;
9659     V >>= 2;
9660     return V == (V & ((1LL << 8) - 1));
9661   }
9662 }
9663
9664 /// isLegalAddressImmediate - Return true if the integer value can be used
9665 /// as the offset of the target addressing mode for load / store of the
9666 /// given type.
9667 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9668                                     const ARMSubtarget *Subtarget) {
9669   if (V == 0)
9670     return true;
9671
9672   if (!VT.isSimple())
9673     return false;
9674
9675   if (Subtarget->isThumb1Only())
9676     return isLegalT1AddressImmediate(V, VT);
9677   else if (Subtarget->isThumb2())
9678     return isLegalT2AddressImmediate(V, VT, Subtarget);
9679
9680   // ARM mode.
9681   if (V < 0)
9682     V = - V;
9683   switch (VT.getSimpleVT().SimpleTy) {
9684   default: return false;
9685   case MVT::i1:
9686   case MVT::i8:
9687   case MVT::i32:
9688     // +- imm12
9689     return V == (V & ((1LL << 12) - 1));
9690   case MVT::i16:
9691     // +- imm8
9692     return V == (V & ((1LL << 8) - 1));
9693   case MVT::f32:
9694   case MVT::f64:
9695     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9696       return false;
9697     if ((V & 3) != 0)
9698       return false;
9699     V >>= 2;
9700     return V == (V & ((1LL << 8) - 1));
9701   }
9702 }
9703
9704 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9705                                                       EVT VT) const {
9706   int Scale = AM.Scale;
9707   if (Scale < 0)
9708     return false;
9709
9710   switch (VT.getSimpleVT().SimpleTy) {
9711   default: return false;
9712   case MVT::i1:
9713   case MVT::i8:
9714   case MVT::i16:
9715   case MVT::i32:
9716     if (Scale == 1)
9717       return true;
9718     // r + r << imm
9719     Scale = Scale & ~1;
9720     return Scale == 2 || Scale == 4 || Scale == 8;
9721   case MVT::i64:
9722     // r + r
9723     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9724       return true;
9725     return false;
9726   case MVT::isVoid:
9727     // Note, we allow "void" uses (basically, uses that aren't loads or
9728     // stores), because arm allows folding a scale into many arithmetic
9729     // operations.  This should be made more precise and revisited later.
9730
9731     // Allow r << imm, but the imm has to be a multiple of two.
9732     if (Scale & 1) return false;
9733     return isPowerOf2_32(Scale);
9734   }
9735 }
9736
9737 /// isLegalAddressingMode - Return true if the addressing mode represented
9738 /// by AM is legal for this target, for a load/store of the specified type.
9739 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9740                                               Type *Ty) const {
9741   EVT VT = getValueType(Ty, true);
9742   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9743     return false;
9744
9745   // Can never fold addr of global into load/store.
9746   if (AM.BaseGV)
9747     return false;
9748
9749   switch (AM.Scale) {
9750   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9751     break;
9752   case 1:
9753     if (Subtarget->isThumb1Only())
9754       return false;
9755     // FALL THROUGH.
9756   default:
9757     // ARM doesn't support any R+R*scale+imm addr modes.
9758     if (AM.BaseOffs)
9759       return false;
9760
9761     if (!VT.isSimple())
9762       return false;
9763
9764     if (Subtarget->isThumb2())
9765       return isLegalT2ScaledAddressingMode(AM, VT);
9766
9767     int Scale = AM.Scale;
9768     switch (VT.getSimpleVT().SimpleTy) {
9769     default: return false;
9770     case MVT::i1:
9771     case MVT::i8:
9772     case MVT::i32:
9773       if (Scale < 0) Scale = -Scale;
9774       if (Scale == 1)
9775         return true;
9776       // r + r << imm
9777       return isPowerOf2_32(Scale & ~1);
9778     case MVT::i16:
9779     case MVT::i64:
9780       // r + r
9781       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9782         return true;
9783       return false;
9784
9785     case MVT::isVoid:
9786       // Note, we allow "void" uses (basically, uses that aren't loads or
9787       // stores), because arm allows folding a scale into many arithmetic
9788       // operations.  This should be made more precise and revisited later.
9789
9790       // Allow r << imm, but the imm has to be a multiple of two.
9791       if (Scale & 1) return false;
9792       return isPowerOf2_32(Scale);
9793     }
9794   }
9795   return true;
9796 }
9797
9798 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9799 /// icmp immediate, that is the target has icmp instructions which can compare
9800 /// a register against the immediate without having to materialize the
9801 /// immediate into a register.
9802 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9803   // Thumb2 and ARM modes can use cmn for negative immediates.
9804   if (!Subtarget->isThumb())
9805     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9806   if (Subtarget->isThumb2())
9807     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9808   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9809   return Imm >= 0 && Imm <= 255;
9810 }
9811
9812 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9813 /// *or sub* immediate, that is the target has add or sub instructions which can
9814 /// add a register with the immediate without having to materialize the
9815 /// immediate into a register.
9816 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9817   // Same encoding for add/sub, just flip the sign.
9818   int64_t AbsImm = llvm::abs64(Imm);
9819   if (!Subtarget->isThumb())
9820     return ARM_AM::getSOImmVal(AbsImm) != -1;
9821   if (Subtarget->isThumb2())
9822     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9823   // Thumb1 only has 8-bit unsigned immediate.
9824   return AbsImm >= 0 && AbsImm <= 255;
9825 }
9826
9827 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9828                                       bool isSEXTLoad, SDValue &Base,
9829                                       SDValue &Offset, bool &isInc,
9830                                       SelectionDAG &DAG) {
9831   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9832     return false;
9833
9834   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9835     // AddressingMode 3
9836     Base = Ptr->getOperand(0);
9837     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9838       int RHSC = (int)RHS->getZExtValue();
9839       if (RHSC < 0 && RHSC > -256) {
9840         assert(Ptr->getOpcode() == ISD::ADD);
9841         isInc = false;
9842         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9843         return true;
9844       }
9845     }
9846     isInc = (Ptr->getOpcode() == ISD::ADD);
9847     Offset = Ptr->getOperand(1);
9848     return true;
9849   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9850     // AddressingMode 2
9851     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9852       int RHSC = (int)RHS->getZExtValue();
9853       if (RHSC < 0 && RHSC > -0x1000) {
9854         assert(Ptr->getOpcode() == ISD::ADD);
9855         isInc = false;
9856         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9857         Base = Ptr->getOperand(0);
9858         return true;
9859       }
9860     }
9861
9862     if (Ptr->getOpcode() == ISD::ADD) {
9863       isInc = true;
9864       ARM_AM::ShiftOpc ShOpcVal=
9865         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9866       if (ShOpcVal != ARM_AM::no_shift) {
9867         Base = Ptr->getOperand(1);
9868         Offset = Ptr->getOperand(0);
9869       } else {
9870         Base = Ptr->getOperand(0);
9871         Offset = Ptr->getOperand(1);
9872       }
9873       return true;
9874     }
9875
9876     isInc = (Ptr->getOpcode() == ISD::ADD);
9877     Base = Ptr->getOperand(0);
9878     Offset = Ptr->getOperand(1);
9879     return true;
9880   }
9881
9882   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9883   return false;
9884 }
9885
9886 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9887                                      bool isSEXTLoad, SDValue &Base,
9888                                      SDValue &Offset, bool &isInc,
9889                                      SelectionDAG &DAG) {
9890   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9891     return false;
9892
9893   Base = Ptr->getOperand(0);
9894   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9895     int RHSC = (int)RHS->getZExtValue();
9896     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9897       assert(Ptr->getOpcode() == ISD::ADD);
9898       isInc = false;
9899       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9900       return true;
9901     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9902       isInc = Ptr->getOpcode() == ISD::ADD;
9903       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9904       return true;
9905     }
9906   }
9907
9908   return false;
9909 }
9910
9911 /// getPreIndexedAddressParts - returns true by value, base pointer and
9912 /// offset pointer and addressing mode by reference if the node's address
9913 /// can be legally represented as pre-indexed load / store address.
9914 bool
9915 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9916                                              SDValue &Offset,
9917                                              ISD::MemIndexedMode &AM,
9918                                              SelectionDAG &DAG) const {
9919   if (Subtarget->isThumb1Only())
9920     return false;
9921
9922   EVT VT;
9923   SDValue Ptr;
9924   bool isSEXTLoad = false;
9925   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9926     Ptr = LD->getBasePtr();
9927     VT  = LD->getMemoryVT();
9928     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9929   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9930     Ptr = ST->getBasePtr();
9931     VT  = ST->getMemoryVT();
9932   } else
9933     return false;
9934
9935   bool isInc;
9936   bool isLegal = false;
9937   if (Subtarget->isThumb2())
9938     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9939                                        Offset, isInc, DAG);
9940   else
9941     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9942                                         Offset, isInc, DAG);
9943   if (!isLegal)
9944     return false;
9945
9946   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9947   return true;
9948 }
9949
9950 /// getPostIndexedAddressParts - returns true by value, base pointer and
9951 /// offset pointer and addressing mode by reference if this node can be
9952 /// combined with a load / store to form a post-indexed load / store.
9953 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9954                                                    SDValue &Base,
9955                                                    SDValue &Offset,
9956                                                    ISD::MemIndexedMode &AM,
9957                                                    SelectionDAG &DAG) const {
9958   if (Subtarget->isThumb1Only())
9959     return false;
9960
9961   EVT VT;
9962   SDValue Ptr;
9963   bool isSEXTLoad = false;
9964   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9965     VT  = LD->getMemoryVT();
9966     Ptr = LD->getBasePtr();
9967     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9968   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9969     VT  = ST->getMemoryVT();
9970     Ptr = ST->getBasePtr();
9971   } else
9972     return false;
9973
9974   bool isInc;
9975   bool isLegal = false;
9976   if (Subtarget->isThumb2())
9977     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9978                                        isInc, DAG);
9979   else
9980     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9981                                         isInc, DAG);
9982   if (!isLegal)
9983     return false;
9984
9985   if (Ptr != Base) {
9986     // Swap base ptr and offset to catch more post-index load / store when
9987     // it's legal. In Thumb2 mode, offset must be an immediate.
9988     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9989         !Subtarget->isThumb2())
9990       std::swap(Base, Offset);
9991
9992     // Post-indexed load / store update the base pointer.
9993     if (Ptr != Base)
9994       return false;
9995   }
9996
9997   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9998   return true;
9999 }
10000
10001 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10002                                                        APInt &KnownZero,
10003                                                        APInt &KnownOne,
10004                                                        const SelectionDAG &DAG,
10005                                                        unsigned Depth) const {
10006   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10007   switch (Op.getOpcode()) {
10008   default: break;
10009   case ARMISD::CMOV: {
10010     // Bits are known zero/one if known on the LHS and RHS.
10011     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10012     if (KnownZero == 0 && KnownOne == 0) return;
10013
10014     APInt KnownZeroRHS, KnownOneRHS;
10015     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10016     KnownZero &= KnownZeroRHS;
10017     KnownOne  &= KnownOneRHS;
10018     return;
10019   }
10020   }
10021 }
10022
10023 //===----------------------------------------------------------------------===//
10024 //                           ARM Inline Assembly Support
10025 //===----------------------------------------------------------------------===//
10026
10027 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10028   // Looking for "rev" which is V6+.
10029   if (!Subtarget->hasV6Ops())
10030     return false;
10031
10032   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10033   std::string AsmStr = IA->getAsmString();
10034   SmallVector<StringRef, 4> AsmPieces;
10035   SplitString(AsmStr, AsmPieces, ";\n");
10036
10037   switch (AsmPieces.size()) {
10038   default: return false;
10039   case 1:
10040     AsmStr = AsmPieces[0];
10041     AsmPieces.clear();
10042     SplitString(AsmStr, AsmPieces, " \t,");
10043
10044     // rev $0, $1
10045     if (AsmPieces.size() == 3 &&
10046         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10047         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10048       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10049       if (Ty && Ty->getBitWidth() == 32)
10050         return IntrinsicLowering::LowerToByteSwap(CI);
10051     }
10052     break;
10053   }
10054
10055   return false;
10056 }
10057
10058 /// getConstraintType - Given a constraint letter, return the type of
10059 /// constraint it is for this target.
10060 ARMTargetLowering::ConstraintType
10061 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10062   if (Constraint.size() == 1) {
10063     switch (Constraint[0]) {
10064     default:  break;
10065     case 'l': return C_RegisterClass;
10066     case 'w': return C_RegisterClass;
10067     case 'h': return C_RegisterClass;
10068     case 'x': return C_RegisterClass;
10069     case 't': return C_RegisterClass;
10070     case 'j': return C_Other; // Constant for movw.
10071       // An address with a single base register. Due to the way we
10072       // currently handle addresses it is the same as an 'r' memory constraint.
10073     case 'Q': return C_Memory;
10074     }
10075   } else if (Constraint.size() == 2) {
10076     switch (Constraint[0]) {
10077     default: break;
10078     // All 'U+' constraints are addresses.
10079     case 'U': return C_Memory;
10080     }
10081   }
10082   return TargetLowering::getConstraintType(Constraint);
10083 }
10084
10085 /// Examine constraint type and operand type and determine a weight value.
10086 /// This object must already have been set up with the operand type
10087 /// and the current alternative constraint selected.
10088 TargetLowering::ConstraintWeight
10089 ARMTargetLowering::getSingleConstraintMatchWeight(
10090     AsmOperandInfo &info, const char *constraint) const {
10091   ConstraintWeight weight = CW_Invalid;
10092   Value *CallOperandVal = info.CallOperandVal;
10093     // If we don't have a value, we can't do a match,
10094     // but allow it at the lowest weight.
10095   if (CallOperandVal == NULL)
10096     return CW_Default;
10097   Type *type = CallOperandVal->getType();
10098   // Look at the constraint type.
10099   switch (*constraint) {
10100   default:
10101     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10102     break;
10103   case 'l':
10104     if (type->isIntegerTy()) {
10105       if (Subtarget->isThumb())
10106         weight = CW_SpecificReg;
10107       else
10108         weight = CW_Register;
10109     }
10110     break;
10111   case 'w':
10112     if (type->isFloatingPointTy())
10113       weight = CW_Register;
10114     break;
10115   }
10116   return weight;
10117 }
10118
10119 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10120 RCPair
10121 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10122                                                 EVT VT) const {
10123   if (Constraint.size() == 1) {
10124     // GCC ARM Constraint Letters
10125     switch (Constraint[0]) {
10126     case 'l': // Low regs or general regs.
10127       if (Subtarget->isThumb())
10128         return RCPair(0U, &ARM::tGPRRegClass);
10129       return RCPair(0U, &ARM::GPRRegClass);
10130     case 'h': // High regs or no regs.
10131       if (Subtarget->isThumb())
10132         return RCPair(0U, &ARM::hGPRRegClass);
10133       break;
10134     case 'r':
10135       return RCPair(0U, &ARM::GPRRegClass);
10136     case 'w':
10137       if (VT == MVT::f32)
10138         return RCPair(0U, &ARM::SPRRegClass);
10139       if (VT.getSizeInBits() == 64)
10140         return RCPair(0U, &ARM::DPRRegClass);
10141       if (VT.getSizeInBits() == 128)
10142         return RCPair(0U, &ARM::QPRRegClass);
10143       break;
10144     case 'x':
10145       if (VT == MVT::f32)
10146         return RCPair(0U, &ARM::SPR_8RegClass);
10147       if (VT.getSizeInBits() == 64)
10148         return RCPair(0U, &ARM::DPR_8RegClass);
10149       if (VT.getSizeInBits() == 128)
10150         return RCPair(0U, &ARM::QPR_8RegClass);
10151       break;
10152     case 't':
10153       if (VT == MVT::f32)
10154         return RCPair(0U, &ARM::SPRRegClass);
10155       break;
10156     }
10157   }
10158   if (StringRef("{cc}").equals_lower(Constraint))
10159     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10160
10161   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10162 }
10163
10164 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10165 /// vector.  If it is invalid, don't add anything to Ops.
10166 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10167                                                      std::string &Constraint,
10168                                                      std::vector<SDValue>&Ops,
10169                                                      SelectionDAG &DAG) const {
10170   SDValue Result(0, 0);
10171
10172   // Currently only support length 1 constraints.
10173   if (Constraint.length() != 1) return;
10174
10175   char ConstraintLetter = Constraint[0];
10176   switch (ConstraintLetter) {
10177   default: break;
10178   case 'j':
10179   case 'I': case 'J': case 'K': case 'L':
10180   case 'M': case 'N': case 'O':
10181     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10182     if (!C)
10183       return;
10184
10185     int64_t CVal64 = C->getSExtValue();
10186     int CVal = (int) CVal64;
10187     // None of these constraints allow values larger than 32 bits.  Check
10188     // that the value fits in an int.
10189     if (CVal != CVal64)
10190       return;
10191
10192     switch (ConstraintLetter) {
10193       case 'j':
10194         // Constant suitable for movw, must be between 0 and
10195         // 65535.
10196         if (Subtarget->hasV6T2Ops())
10197           if (CVal >= 0 && CVal <= 65535)
10198             break;
10199         return;
10200       case 'I':
10201         if (Subtarget->isThumb1Only()) {
10202           // This must be a constant between 0 and 255, for ADD
10203           // immediates.
10204           if (CVal >= 0 && CVal <= 255)
10205             break;
10206         } else if (Subtarget->isThumb2()) {
10207           // A constant that can be used as an immediate value in a
10208           // data-processing instruction.
10209           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10210             break;
10211         } else {
10212           // A constant that can be used as an immediate value in a
10213           // data-processing instruction.
10214           if (ARM_AM::getSOImmVal(CVal) != -1)
10215             break;
10216         }
10217         return;
10218
10219       case 'J':
10220         if (Subtarget->isThumb()) {  // FIXME thumb2
10221           // This must be a constant between -255 and -1, for negated ADD
10222           // immediates. This can be used in GCC with an "n" modifier that
10223           // prints the negated value, for use with SUB instructions. It is
10224           // not useful otherwise but is implemented for compatibility.
10225           if (CVal >= -255 && CVal <= -1)
10226             break;
10227         } else {
10228           // This must be a constant between -4095 and 4095. It is not clear
10229           // what this constraint is intended for. Implemented for
10230           // compatibility with GCC.
10231           if (CVal >= -4095 && CVal <= 4095)
10232             break;
10233         }
10234         return;
10235
10236       case 'K':
10237         if (Subtarget->isThumb1Only()) {
10238           // A 32-bit value where only one byte has a nonzero value. Exclude
10239           // zero to match GCC. This constraint is used by GCC internally for
10240           // constants that can be loaded with a move/shift combination.
10241           // It is not useful otherwise but is implemented for compatibility.
10242           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10243             break;
10244         } else if (Subtarget->isThumb2()) {
10245           // A constant whose bitwise inverse can be used as an immediate
10246           // value in a data-processing instruction. This can be used in GCC
10247           // with a "B" modifier that prints the inverted value, for use with
10248           // BIC and MVN instructions. It is not useful otherwise but is
10249           // implemented for compatibility.
10250           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10251             break;
10252         } else {
10253           // A constant whose bitwise inverse can be used as an immediate
10254           // value in a data-processing instruction. This can be used in GCC
10255           // with a "B" modifier that prints the inverted value, for use with
10256           // BIC and MVN instructions. It is not useful otherwise but is
10257           // implemented for compatibility.
10258           if (ARM_AM::getSOImmVal(~CVal) != -1)
10259             break;
10260         }
10261         return;
10262
10263       case 'L':
10264         if (Subtarget->isThumb1Only()) {
10265           // This must be a constant between -7 and 7,
10266           // for 3-operand ADD/SUB immediate instructions.
10267           if (CVal >= -7 && CVal < 7)
10268             break;
10269         } else if (Subtarget->isThumb2()) {
10270           // A constant whose negation can be used as an immediate value in a
10271           // data-processing instruction. This can be used in GCC with an "n"
10272           // modifier that prints the negated value, for use with SUB
10273           // instructions. It is not useful otherwise but is implemented for
10274           // compatibility.
10275           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10276             break;
10277         } else {
10278           // A constant whose negation can be used as an immediate value in a
10279           // data-processing instruction. This can be used in GCC with an "n"
10280           // modifier that prints the negated value, for use with SUB
10281           // instructions. It is not useful otherwise but is implemented for
10282           // compatibility.
10283           if (ARM_AM::getSOImmVal(-CVal) != -1)
10284             break;
10285         }
10286         return;
10287
10288       case 'M':
10289         if (Subtarget->isThumb()) { // FIXME thumb2
10290           // This must be a multiple of 4 between 0 and 1020, for
10291           // ADD sp + immediate.
10292           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10293             break;
10294         } else {
10295           // A power of two or a constant between 0 and 32.  This is used in
10296           // GCC for the shift amount on shifted register operands, but it is
10297           // useful in general for any shift amounts.
10298           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10299             break;
10300         }
10301         return;
10302
10303       case 'N':
10304         if (Subtarget->isThumb()) {  // FIXME thumb2
10305           // This must be a constant between 0 and 31, for shift amounts.
10306           if (CVal >= 0 && CVal <= 31)
10307             break;
10308         }
10309         return;
10310
10311       case 'O':
10312         if (Subtarget->isThumb()) {  // FIXME thumb2
10313           // This must be a multiple of 4 between -508 and 508, for
10314           // ADD/SUB sp = sp + immediate.
10315           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10316             break;
10317         }
10318         return;
10319     }
10320     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10321     break;
10322   }
10323
10324   if (Result.getNode()) {
10325     Ops.push_back(Result);
10326     return;
10327   }
10328   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10329 }
10330
10331 bool
10332 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10333   // The ARM target isn't yet aware of offsets.
10334   return false;
10335 }
10336
10337 bool ARM::isBitFieldInvertedMask(unsigned v) {
10338   if (v == 0xffffffff)
10339     return 0;
10340   // there can be 1's on either or both "outsides", all the "inside"
10341   // bits must be 0's
10342   unsigned int lsb = 0, msb = 31;
10343   while (v & (1 << msb)) --msb;
10344   while (v & (1 << lsb)) ++lsb;
10345   for (unsigned int i = lsb; i <= msb; ++i) {
10346     if (v & (1 << i))
10347       return 0;
10348   }
10349   return 1;
10350 }
10351
10352 /// isFPImmLegal - Returns true if the target can instruction select the
10353 /// specified FP immediate natively. If false, the legalizer will
10354 /// materialize the FP immediate as a load from a constant pool.
10355 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10356   if (!Subtarget->hasVFP3())
10357     return false;
10358   if (VT == MVT::f32)
10359     return ARM_AM::getFP32Imm(Imm) != -1;
10360   if (VT == MVT::f64)
10361     return ARM_AM::getFP64Imm(Imm) != -1;
10362   return false;
10363 }
10364
10365 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10366 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10367 /// specified in the intrinsic calls.
10368 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10369                                            const CallInst &I,
10370                                            unsigned Intrinsic) const {
10371   switch (Intrinsic) {
10372   case Intrinsic::arm_neon_vld1:
10373   case Intrinsic::arm_neon_vld2:
10374   case Intrinsic::arm_neon_vld3:
10375   case Intrinsic::arm_neon_vld4:
10376   case Intrinsic::arm_neon_vld2lane:
10377   case Intrinsic::arm_neon_vld3lane:
10378   case Intrinsic::arm_neon_vld4lane: {
10379     Info.opc = ISD::INTRINSIC_W_CHAIN;
10380     // Conservatively set memVT to the entire set of vectors loaded.
10381     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10382     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10383     Info.ptrVal = I.getArgOperand(0);
10384     Info.offset = 0;
10385     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10386     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10387     Info.vol = false; // volatile loads with NEON intrinsics not supported
10388     Info.readMem = true;
10389     Info.writeMem = false;
10390     return true;
10391   }
10392   case Intrinsic::arm_neon_vst1:
10393   case Intrinsic::arm_neon_vst2:
10394   case Intrinsic::arm_neon_vst3:
10395   case Intrinsic::arm_neon_vst4:
10396   case Intrinsic::arm_neon_vst2lane:
10397   case Intrinsic::arm_neon_vst3lane:
10398   case Intrinsic::arm_neon_vst4lane: {
10399     Info.opc = ISD::INTRINSIC_VOID;
10400     // Conservatively set memVT to the entire set of vectors stored.
10401     unsigned NumElts = 0;
10402     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10403       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10404       if (!ArgTy->isVectorTy())
10405         break;
10406       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10407     }
10408     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10409     Info.ptrVal = I.getArgOperand(0);
10410     Info.offset = 0;
10411     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10412     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10413     Info.vol = false; // volatile stores with NEON intrinsics not supported
10414     Info.readMem = false;
10415     Info.writeMem = true;
10416     return true;
10417   }
10418   case Intrinsic::arm_strexd: {
10419     Info.opc = ISD::INTRINSIC_W_CHAIN;
10420     Info.memVT = MVT::i64;
10421     Info.ptrVal = I.getArgOperand(2);
10422     Info.offset = 0;
10423     Info.align = 8;
10424     Info.vol = true;
10425     Info.readMem = false;
10426     Info.writeMem = true;
10427     return true;
10428   }
10429   case Intrinsic::arm_ldrexd: {
10430     Info.opc = ISD::INTRINSIC_W_CHAIN;
10431     Info.memVT = MVT::i64;
10432     Info.ptrVal = I.getArgOperand(0);
10433     Info.offset = 0;
10434     Info.align = 8;
10435     Info.vol = true;
10436     Info.readMem = true;
10437     Info.writeMem = false;
10438     return true;
10439   }
10440   default:
10441     break;
10442   }
10443
10444   return false;
10445 }