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