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