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