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