Fix for 5.5 Parameter Passing --> Stage C:
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
508
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Mark v2f32 intrinsics.
526     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
541
542     // Neon does not support some operations on v1i64 and v2i64 types.
543     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544     // Custom handling for some quad-vector types to detect VMULL.
545     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548     // Custom handling for some vector types to avoid expensive expansions
549     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556     // a destination type that is wider than the source, and nor does
557     // it have a FP_TO_[SU]INT instruction with a narrower destination than
558     // source.
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
563
564     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
565     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
566
567     // Custom expand long extensions to vectors.
568     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
569     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
571     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
575     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
576
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585     // NEON only has FMA instructions as of VFP4.
586     if (!Subtarget->hasVFP4()) {
587       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
589     }
590
591     setTargetDAGCombine(ISD::INTRINSIC_VOID);
592     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594     setTargetDAGCombine(ISD::SHL);
595     setTargetDAGCombine(ISD::SRL);
596     setTargetDAGCombine(ISD::SRA);
597     setTargetDAGCombine(ISD::SIGN_EXTEND);
598     setTargetDAGCombine(ISD::ZERO_EXTEND);
599     setTargetDAGCombine(ISD::ANY_EXTEND);
600     setTargetDAGCombine(ISD::SELECT_CC);
601     setTargetDAGCombine(ISD::BUILD_VECTOR);
602     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604     setTargetDAGCombine(ISD::STORE);
605     setTargetDAGCombine(ISD::FP_TO_SINT);
606     setTargetDAGCombine(ISD::FP_TO_UINT);
607     setTargetDAGCombine(ISD::FDIV);
608
609     // It is legal to extload from v4i8 to v4i16 or v4i32.
610     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611                   MVT::v4i16, MVT::v2i16,
612                   MVT::v2i32};
613     for (unsigned i = 0; i < 6; ++i) {
614       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
617     }
618   }
619
620   // ARM and Thumb2 support UMLAL/SMLAL.
621   if (!Subtarget->isThumb1Only())
622     setTargetDAGCombine(ISD::ADDC);
623
624
625   computeRegisterProperties();
626
627   // ARM does not have f32 extending load.
628   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
629
630   // ARM does not have i1 sign extending load.
631   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
632
633   // ARM supports all 4 flavors of integer indexed load / store.
634   if (!Subtarget->isThumb1Only()) {
635     for (unsigned im = (unsigned)ISD::PRE_INC;
636          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637       setIndexedLoadAction(im,  MVT::i1,  Legal);
638       setIndexedLoadAction(im,  MVT::i8,  Legal);
639       setIndexedLoadAction(im,  MVT::i16, Legal);
640       setIndexedLoadAction(im,  MVT::i32, Legal);
641       setIndexedStoreAction(im, MVT::i1,  Legal);
642       setIndexedStoreAction(im, MVT::i8,  Legal);
643       setIndexedStoreAction(im, MVT::i16, Legal);
644       setIndexedStoreAction(im, MVT::i32, Legal);
645     }
646   }
647
648   // i64 operation support.
649   setOperationAction(ISD::MUL,     MVT::i64, Expand);
650   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
651   if (Subtarget->isThumb1Only()) {
652     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
654   }
655   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657     setOperationAction(ISD::MULHS, MVT::i32, Expand);
658
659   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL,       MVT::i64, Custom);
663   setOperationAction(ISD::SRA,       MVT::i64, Custom);
664
665   if (!Subtarget->isThumb1Only()) {
666     // FIXME: We should do this for Thumb1 as well.
667     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
668     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
669     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
671   }
672
673   // ARM does not have ROTL.
674   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
675   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
676   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
679
680   // These just redirect to CTTZ and CTLZ on ARM.
681   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
682   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
683
684   // Only ARMv6 has BSWAP.
685   if (!Subtarget->hasV6Ops())
686     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
687
688   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
689       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
690     // These are expanded into libcalls if the cpu doesn't have HW divider.
691     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
692     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
693   }
694   setOperationAction(ISD::SREM,  MVT::i32, Expand);
695   setOperationAction(ISD::UREM,  MVT::i32, Expand);
696   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
697   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
698
699   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
700   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
701   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
702   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
703   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
704
705   setOperationAction(ISD::TRAP, MVT::Other, Legal);
706
707   // Use the default implementation.
708   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
709   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
710   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
711   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
712   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
713   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
714
715   if (!Subtarget->isTargetDarwin()) {
716     // Non-Darwin platforms may return values in these registers via the
717     // personality function.
718     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
719     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
720     setExceptionPointerRegister(ARM::R0);
721     setExceptionSelectorRegister(ARM::R1);
722   }
723
724   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
725   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
726   // the default expansion.
727   // FIXME: This should be checking for v6k, not just v6.
728   if (Subtarget->hasDataBarrier() ||
729       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
730     // membarrier needs custom lowering; the rest are legal and handled
731     // normally.
732     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
733     // Custom lowering for 64-bit ops
734     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
735     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
736     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
737     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
738     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
739     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
740     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
741     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
742     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
743     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
744     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
745     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
746     setInsertFencesForAtomic(true);
747   } else {
748     // Set them all for expansion, which will force libcalls.
749     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
750     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
751     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
752     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
755     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
756     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
757     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
758     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
759     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
762     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
763     // Unordered/Monotonic case.
764     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
765     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
766   }
767
768   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
769
770   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
771   if (!Subtarget->hasV6Ops()) {
772     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
773     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
774   }
775   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
776
777   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
778       !Subtarget->isThumb1Only()) {
779     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
780     // iff target supports vfp2.
781     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
782     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
783   }
784
785   // We want to custom lower some of our intrinsics.
786   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
787   if (Subtarget->isTargetDarwin()) {
788     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
789     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
790     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
791   }
792
793   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
794   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
795   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
796   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
797   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
798   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
799   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
800   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
801   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
802
803   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
804   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
805   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
806   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
807   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
808
809   // We don't support sin/cos/fmod/copysign/pow
810   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
811   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
812   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
813   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
814   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
815   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
816   setOperationAction(ISD::FREM,      MVT::f64, Expand);
817   setOperationAction(ISD::FREM,      MVT::f32, Expand);
818   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
819       !Subtarget->isThumb1Only()) {
820     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
821     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
822   }
823   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
824   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
825
826   if (!Subtarget->hasVFP4()) {
827     setOperationAction(ISD::FMA, MVT::f64, Expand);
828     setOperationAction(ISD::FMA, MVT::f32, Expand);
829   }
830
831   // Various VFP goodness
832   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
833     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
834     if (Subtarget->hasVFP2()) {
835       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
836       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
837       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
838       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
839     }
840     // Special handling for half-precision FP.
841     if (!Subtarget->hasFP16()) {
842       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
843       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
844     }
845   }
846
847   // We have target-specific dag combine patterns for the following nodes:
848   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
849   setTargetDAGCombine(ISD::ADD);
850   setTargetDAGCombine(ISD::SUB);
851   setTargetDAGCombine(ISD::MUL);
852   setTargetDAGCombine(ISD::AND);
853   setTargetDAGCombine(ISD::OR);
854   setTargetDAGCombine(ISD::XOR);
855
856   if (Subtarget->hasV6Ops())
857     setTargetDAGCombine(ISD::SRL);
858
859   setStackPointerRegisterToSaveRestore(ARM::SP);
860
861   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862       !Subtarget->hasVFP2())
863     setSchedulingPreference(Sched::RegPressure);
864   else
865     setSchedulingPreference(Sched::Hybrid);
866
867   //// temporary - rewrite interface to use type
868   MaxStoresPerMemset = 8;
869   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874
875   // On ARM arguments smaller than 4 bytes are extended, so all arguments
876   // are at least 4 bytes aligned.
877   setMinStackArgumentAlignment(4);
878
879   // Prefer likely predicted branches to selects on out-of-order cores.
880   PredictableSelectIsExpensive = Subtarget->isLikeA9();
881
882   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
883 }
884
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
894 // and extractions.
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897   const TargetRegisterClass *RRC = 0;
898   uint8_t Cost = 1;
899   switch (VT.SimpleTy) {
900   default:
901     return TargetLowering::findRepresentativeClass(VT);
902   // Use DPR as representative register class for all floating point
903   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904   // the cost is 1 for both f32 and f64.
905   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907     RRC = &ARM::DPRRegClass;
908     // When NEON is used for SP, only half of the register file is available
909     // because operations that define both SP and DP results will be constrained
910     // to the VFP2 class (D0-D15). We currently model this constraint prior to
911     // coalescing by double-counting the SP regs. See the FIXME above.
912     if (Subtarget->useNEONForSinglePrecisionFP())
913       Cost = 2;
914     break;
915   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916   case MVT::v4f32: case MVT::v2f64:
917     RRC = &ARM::DPRRegClass;
918     Cost = 2;
919     break;
920   case MVT::v4i64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 4;
923     break;
924   case MVT::v8i64:
925     RRC = &ARM::DPRRegClass;
926     Cost = 8;
927     break;
928   }
929   return std::make_pair(RRC, Cost);
930 }
931
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
933   switch (Opcode) {
934   default: return 0;
935   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
936   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
937   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
938   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
939   case ARMISD::CALL:          return "ARMISD::CALL";
940   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
941   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
942   case ARMISD::tCALL:         return "ARMISD::tCALL";
943   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
944   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
945   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
946   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
947   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
948   case ARMISD::CMP:           return "ARMISD::CMP";
949   case ARMISD::CMN:           return "ARMISD::CMN";
950   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
951   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
952   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
953   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
954   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
955
956   case ARMISD::CMOV:          return "ARMISD::CMOV";
957
958   case ARMISD::RBIT:          return "ARMISD::RBIT";
959
960   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
961   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
962   case ARMISD::SITOF:         return "ARMISD::SITOF";
963   case ARMISD::UITOF:         return "ARMISD::UITOF";
964
965   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
966   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
967   case ARMISD::RRX:           return "ARMISD::RRX";
968
969   case ARMISD::ADDC:          return "ARMISD::ADDC";
970   case ARMISD::ADDE:          return "ARMISD::ADDE";
971   case ARMISD::SUBC:          return "ARMISD::SUBC";
972   case ARMISD::SUBE:          return "ARMISD::SUBE";
973
974   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
975   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
976
977   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
979
980   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
981
982   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
983
984   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
985
986   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
987   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
988
989   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
990
991   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
992   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
993   case ARMISD::VCGE:          return "ARMISD::VCGE";
994   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
995   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
996   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
997   case ARMISD::VCGT:          return "ARMISD::VCGT";
998   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
999   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1000   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1001   case ARMISD::VTST:          return "ARMISD::VTST";
1002
1003   case ARMISD::VSHL:          return "ARMISD::VSHL";
1004   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1005   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1006   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1007   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1008   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1009   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1010   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1011   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1012   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1013   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1014   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1015   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1016   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1017   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1018   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1019   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1020   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1021   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1022   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1023   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1024   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1025   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1026   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1027   case ARMISD::VDUP:          return "ARMISD::VDUP";
1028   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1029   case ARMISD::VEXT:          return "ARMISD::VEXT";
1030   case ARMISD::VREV64:        return "ARMISD::VREV64";
1031   case ARMISD::VREV32:        return "ARMISD::VREV32";
1032   case ARMISD::VREV16:        return "ARMISD::VREV16";
1033   case ARMISD::VZIP:          return "ARMISD::VZIP";
1034   case ARMISD::VUZP:          return "ARMISD::VUZP";
1035   case ARMISD::VTRN:          return "ARMISD::VTRN";
1036   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1037   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1038   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1039   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1040   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1041   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1042   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1043   case ARMISD::FMAX:          return "ARMISD::FMAX";
1044   case ARMISD::FMIN:          return "ARMISD::FMIN";
1045   case ARMISD::BFI:           return "ARMISD::BFI";
1046   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1047   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1048   case ARMISD::VBSL:          return "ARMISD::VBSL";
1049   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1050   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1051   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1052   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1053   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1054   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1055   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1056   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1057   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1058   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1059   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1060   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1061   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1062   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1063   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1064   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1065   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1066   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1067   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1068   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1069   }
1070 }
1071
1072 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1073   if (!VT.isVector()) return getPointerTy();
1074   return VT.changeVectorElementTypeToInteger();
1075 }
1076
1077 /// getRegClassFor - Return the register class that should be used for the
1078 /// specified value type.
1079 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1080   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1081   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1082   // load / store 4 to 8 consecutive D registers.
1083   if (Subtarget->hasNEON()) {
1084     if (VT == MVT::v4i64)
1085       return &ARM::QQPRRegClass;
1086     if (VT == MVT::v8i64)
1087       return &ARM::QQQQPRRegClass;
1088   }
1089   return TargetLowering::getRegClassFor(VT);
1090 }
1091
1092 // Create a fast isel object.
1093 FastISel *
1094 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1095                                   const TargetLibraryInfo *libInfo) const {
1096   return ARM::createFastISel(funcInfo, libInfo);
1097 }
1098
1099 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1100 /// be used for loads / stores from the global.
1101 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1102   return (Subtarget->isThumb1Only() ? 127 : 4095);
1103 }
1104
1105 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1106   unsigned NumVals = N->getNumValues();
1107   if (!NumVals)
1108     return Sched::RegPressure;
1109
1110   for (unsigned i = 0; i != NumVals; ++i) {
1111     EVT VT = N->getValueType(i);
1112     if (VT == MVT::Glue || VT == MVT::Other)
1113       continue;
1114     if (VT.isFloatingPoint() || VT.isVector())
1115       return Sched::ILP;
1116   }
1117
1118   if (!N->isMachineOpcode())
1119     return Sched::RegPressure;
1120
1121   // Load are scheduled for latency even if there instruction itinerary
1122   // is not available.
1123   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1124   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1125
1126   if (MCID.getNumDefs() == 0)
1127     return Sched::RegPressure;
1128   if (!Itins->isEmpty() &&
1129       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1130     return Sched::ILP;
1131
1132   return Sched::RegPressure;
1133 }
1134
1135 //===----------------------------------------------------------------------===//
1136 // Lowering Code
1137 //===----------------------------------------------------------------------===//
1138
1139 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1140 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1141   switch (CC) {
1142   default: llvm_unreachable("Unknown condition code!");
1143   case ISD::SETNE:  return ARMCC::NE;
1144   case ISD::SETEQ:  return ARMCC::EQ;
1145   case ISD::SETGT:  return ARMCC::GT;
1146   case ISD::SETGE:  return ARMCC::GE;
1147   case ISD::SETLT:  return ARMCC::LT;
1148   case ISD::SETLE:  return ARMCC::LE;
1149   case ISD::SETUGT: return ARMCC::HI;
1150   case ISD::SETUGE: return ARMCC::HS;
1151   case ISD::SETULT: return ARMCC::LO;
1152   case ISD::SETULE: return ARMCC::LS;
1153   }
1154 }
1155
1156 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1157 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1158                         ARMCC::CondCodes &CondCode2) {
1159   CondCode2 = ARMCC::AL;
1160   switch (CC) {
1161   default: llvm_unreachable("Unknown FP condition!");
1162   case ISD::SETEQ:
1163   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1164   case ISD::SETGT:
1165   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1166   case ISD::SETGE:
1167   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1168   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1169   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1170   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1171   case ISD::SETO:   CondCode = ARMCC::VC; break;
1172   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1173   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1174   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1175   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1176   case ISD::SETLT:
1177   case ISD::SETULT: CondCode = ARMCC::LT; break;
1178   case ISD::SETLE:
1179   case ISD::SETULE: CondCode = ARMCC::LE; break;
1180   case ISD::SETNE:
1181   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1182   }
1183 }
1184
1185 //===----------------------------------------------------------------------===//
1186 //                      Calling Convention Implementation
1187 //===----------------------------------------------------------------------===//
1188
1189 #include "ARMGenCallingConv.inc"
1190
1191 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1192 /// given CallingConvention value.
1193 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1194                                                  bool Return,
1195                                                  bool isVarArg) const {
1196   switch (CC) {
1197   default:
1198     llvm_unreachable("Unsupported calling convention");
1199   case CallingConv::Fast:
1200     if (Subtarget->hasVFP2() && !isVarArg) {
1201       if (!Subtarget->isAAPCS_ABI())
1202         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1203       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1204       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1205     }
1206     // Fallthrough
1207   case CallingConv::C: {
1208     // Use target triple & subtarget features to do actual dispatch.
1209     if (!Subtarget->isAAPCS_ABI())
1210       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1211     else if (Subtarget->hasVFP2() &&
1212              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1213              !isVarArg)
1214       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1215     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1216   }
1217   case CallingConv::ARM_AAPCS_VFP:
1218     if (!isVarArg)
1219       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1220     // Fallthrough
1221   case CallingConv::ARM_AAPCS:
1222     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1223   case CallingConv::ARM_APCS:
1224     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1225   case CallingConv::GHC:
1226     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1227   }
1228 }
1229
1230 /// LowerCallResult - Lower the result values of a call into the
1231 /// appropriate copies out of appropriate physical registers.
1232 SDValue
1233 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1234                                    CallingConv::ID CallConv, bool isVarArg,
1235                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1236                                    DebugLoc dl, SelectionDAG &DAG,
1237                                    SmallVectorImpl<SDValue> &InVals,
1238                                    bool isThisReturn, SDValue ThisVal) const {
1239
1240   // Assign locations to each value returned by this call.
1241   SmallVector<CCValAssign, 16> RVLocs;
1242   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1243                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1244   CCInfo.AnalyzeCallResult(Ins,
1245                            CCAssignFnForNode(CallConv, /* Return*/ true,
1246                                              isVarArg));
1247
1248   // Copy all of the result registers out of their specified physreg.
1249   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1250     CCValAssign VA = RVLocs[i];
1251
1252     // Pass 'this' value directly from the argument to return value, to avoid
1253     // reg unit interference
1254     if (i == 0 && isThisReturn) {
1255       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32);
1256       InVals.push_back(ThisVal);
1257       continue;
1258     }
1259
1260     SDValue Val;
1261     if (VA.needsCustom()) {
1262       // Handle f64 or half of a v2f64.
1263       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1264                                       InFlag);
1265       Chain = Lo.getValue(1);
1266       InFlag = Lo.getValue(2);
1267       VA = RVLocs[++i]; // skip ahead to next loc
1268       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1269                                       InFlag);
1270       Chain = Hi.getValue(1);
1271       InFlag = Hi.getValue(2);
1272       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1273
1274       if (VA.getLocVT() == MVT::v2f64) {
1275         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1276         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1277                           DAG.getConstant(0, MVT::i32));
1278
1279         VA = RVLocs[++i]; // skip ahead to next loc
1280         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1281         Chain = Lo.getValue(1);
1282         InFlag = Lo.getValue(2);
1283         VA = RVLocs[++i]; // skip ahead to next loc
1284         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1285         Chain = Hi.getValue(1);
1286         InFlag = Hi.getValue(2);
1287         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1288         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1289                           DAG.getConstant(1, MVT::i32));
1290       }
1291     } else {
1292       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1293                                InFlag);
1294       Chain = Val.getValue(1);
1295       InFlag = Val.getValue(2);
1296     }
1297
1298     switch (VA.getLocInfo()) {
1299     default: llvm_unreachable("Unknown loc info!");
1300     case CCValAssign::Full: break;
1301     case CCValAssign::BCvt:
1302       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1303       break;
1304     }
1305
1306     InVals.push_back(Val);
1307   }
1308
1309   return Chain;
1310 }
1311
1312 /// LowerMemOpCallTo - Store the argument to the stack.
1313 SDValue
1314 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1315                                     SDValue StackPtr, SDValue Arg,
1316                                     DebugLoc dl, SelectionDAG &DAG,
1317                                     const CCValAssign &VA,
1318                                     ISD::ArgFlagsTy Flags) const {
1319   unsigned LocMemOffset = VA.getLocMemOffset();
1320   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1321   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1322   return DAG.getStore(Chain, dl, Arg, PtrOff,
1323                       MachinePointerInfo::getStack(LocMemOffset),
1324                       false, false, 0);
1325 }
1326
1327 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1328                                          SDValue Chain, SDValue &Arg,
1329                                          RegsToPassVector &RegsToPass,
1330                                          CCValAssign &VA, CCValAssign &NextVA,
1331                                          SDValue &StackPtr,
1332                                          SmallVector<SDValue, 8> &MemOpChains,
1333                                          ISD::ArgFlagsTy Flags) const {
1334
1335   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1336                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1337   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1338
1339   if (NextVA.isRegLoc())
1340     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1341   else {
1342     assert(NextVA.isMemLoc());
1343     if (StackPtr.getNode() == 0)
1344       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1345
1346     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1347                                            dl, DAG, NextVA,
1348                                            Flags));
1349   }
1350 }
1351
1352 /// LowerCall - Lowering a call into a callseq_start <-
1353 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1354 /// nodes.
1355 SDValue
1356 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1357                              SmallVectorImpl<SDValue> &InVals) const {
1358   SelectionDAG &DAG                     = CLI.DAG;
1359   DebugLoc &dl                          = CLI.DL;
1360   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1361   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1362   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1363   SDValue Chain                         = CLI.Chain;
1364   SDValue Callee                        = CLI.Callee;
1365   bool &isTailCall                      = CLI.IsTailCall;
1366   CallingConv::ID CallConv              = CLI.CallConv;
1367   bool doesNotRet                       = CLI.DoesNotReturn;
1368   bool isVarArg                         = CLI.IsVarArg;
1369
1370   MachineFunction &MF = DAG.getMachineFunction();
1371   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1372   bool IsThisReturn   = false;
1373   bool IsSibCall      = false;
1374   // Disable tail calls if they're not supported.
1375   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1376     isTailCall = false;
1377   if (isTailCall) {
1378     // Check if it's really possible to do a tail call.
1379     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1380                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1381                                                    Outs, OutVals, Ins, DAG);
1382     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1383     // detected sibcalls.
1384     if (isTailCall) {
1385       ++NumTailCalls;
1386       IsSibCall = true;
1387     }
1388   }
1389
1390   // Analyze operands of the call, assigning locations to each operand.
1391   SmallVector<CCValAssign, 16> ArgLocs;
1392   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1393                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1394   CCInfo.AnalyzeCallOperands(Outs,
1395                              CCAssignFnForNode(CallConv, /* Return*/ false,
1396                                                isVarArg));
1397
1398   // Get a count of how many bytes are to be pushed on the stack.
1399   unsigned NumBytes = CCInfo.getNextStackOffset();
1400
1401   // For tail calls, memory operands are available in our caller's stack.
1402   if (IsSibCall)
1403     NumBytes = 0;
1404
1405   // Adjust the stack pointer for the new arguments...
1406   // These operations are automatically eliminated by the prolog/epilog pass
1407   if (!IsSibCall)
1408     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1409
1410   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1411
1412   RegsToPassVector RegsToPass;
1413   SmallVector<SDValue, 8> MemOpChains;
1414
1415   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1416   // of tail call optimization, arguments are handled later.
1417   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1418        i != e;
1419        ++i, ++realArgIdx) {
1420     CCValAssign &VA = ArgLocs[i];
1421     SDValue Arg = OutVals[realArgIdx];
1422     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1423     bool isByVal = Flags.isByVal();
1424
1425     // Promote the value if needed.
1426     switch (VA.getLocInfo()) {
1427     default: llvm_unreachable("Unknown loc info!");
1428     case CCValAssign::Full: break;
1429     case CCValAssign::SExt:
1430       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1431       break;
1432     case CCValAssign::ZExt:
1433       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1434       break;
1435     case CCValAssign::AExt:
1436       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1437       break;
1438     case CCValAssign::BCvt:
1439       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1440       break;
1441     }
1442
1443     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1444     if (VA.needsCustom()) {
1445       if (VA.getLocVT() == MVT::v2f64) {
1446         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1447                                   DAG.getConstant(0, MVT::i32));
1448         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1449                                   DAG.getConstant(1, MVT::i32));
1450
1451         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1452                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1453
1454         VA = ArgLocs[++i]; // skip ahead to next loc
1455         if (VA.isRegLoc()) {
1456           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1457                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1458         } else {
1459           assert(VA.isMemLoc());
1460
1461           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1462                                                  dl, DAG, VA, Flags));
1463         }
1464       } else {
1465         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1466                          StackPtr, MemOpChains, Flags);
1467       }
1468     } else if (VA.isRegLoc()) {
1469       if (realArgIdx == 0 && Flags.isReturned() && VA.getLocVT() == MVT::i32) {
1470         assert(!Ins.empty() && Ins[0].VT == Outs[0].VT &&
1471                "unexpected use of 'returned'");
1472         IsThisReturn = true;
1473       }
1474       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1475     } else if (isByVal) {
1476       assert(VA.isMemLoc());
1477       unsigned offset = 0;
1478
1479       // True if this byval aggregate will be split between registers
1480       // and memory.
1481       if (CCInfo.isFirstByValRegValid()) {
1482         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1483         unsigned int i, j;
1484         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1485           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1486           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1487           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1488                                      MachinePointerInfo(),
1489                                      false, false, false, 0);
1490           MemOpChains.push_back(Load.getValue(1));
1491           RegsToPass.push_back(std::make_pair(j, Load));
1492         }
1493         offset = ARM::R4 - CCInfo.getFirstByValReg();
1494         CCInfo.clearFirstByValReg();
1495       }
1496
1497       if (Flags.getByValSize() - 4*offset > 0) {
1498         unsigned LocMemOffset = VA.getLocMemOffset();
1499         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1500         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1501                                   StkPtrOff);
1502         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1503         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1504         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1505                                            MVT::i32);
1506         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1507
1508         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1509         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1510         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1511                                           Ops, array_lengthof(Ops)));
1512       }
1513     } else if (!IsSibCall) {
1514       assert(VA.isMemLoc());
1515
1516       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1517                                              dl, DAG, VA, Flags));
1518     }
1519   }
1520
1521   if (!MemOpChains.empty())
1522     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1523                         &MemOpChains[0], MemOpChains.size());
1524
1525   // Build a sequence of copy-to-reg nodes chained together with token chain
1526   // and flag operands which copy the outgoing args into the appropriate regs.
1527   SDValue InFlag;
1528   // Tail call byval lowering might overwrite argument registers so in case of
1529   // tail call optimization the copies to registers are lowered later.
1530   if (!isTailCall)
1531     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1532       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1533                                RegsToPass[i].second, InFlag);
1534       InFlag = Chain.getValue(1);
1535     }
1536
1537   // For tail calls lower the arguments to the 'real' stack slot.
1538   if (isTailCall) {
1539     // Force all the incoming stack arguments to be loaded from the stack
1540     // before any new outgoing arguments are stored to the stack, because the
1541     // outgoing stack slots may alias the incoming argument stack slots, and
1542     // the alias isn't otherwise explicit. This is slightly more conservative
1543     // than necessary, because it means that each store effectively depends
1544     // on every argument instead of just those arguments it would clobber.
1545
1546     // Do not flag preceding copytoreg stuff together with the following stuff.
1547     InFlag = SDValue();
1548     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1549       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1550                                RegsToPass[i].second, InFlag);
1551       InFlag = Chain.getValue(1);
1552     }
1553     InFlag = SDValue();
1554   }
1555
1556   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1557   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1558   // node so that legalize doesn't hack it.
1559   bool isDirect = false;
1560   bool isARMFunc = false;
1561   bool isLocalARMFunc = false;
1562   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1563
1564   if (EnableARMLongCalls) {
1565     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1566             && "long-calls with non-static relocation model!");
1567     // Handle a global address or an external symbol. If it's not one of
1568     // those, the target's already in a register, so we don't need to do
1569     // anything extra.
1570     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1571       const GlobalValue *GV = G->getGlobal();
1572       // Create a constant pool entry for the callee address
1573       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1574       ARMConstantPoolValue *CPV =
1575         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1576
1577       // Get the address of the callee into a register
1578       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1579       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1580       Callee = DAG.getLoad(getPointerTy(), dl,
1581                            DAG.getEntryNode(), CPAddr,
1582                            MachinePointerInfo::getConstantPool(),
1583                            false, false, false, 0);
1584     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1585       const char *Sym = S->getSymbol();
1586
1587       // Create a constant pool entry for the callee address
1588       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1589       ARMConstantPoolValue *CPV =
1590         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1591                                       ARMPCLabelIndex, 0);
1592       // Get the address of the callee into a register
1593       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1594       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1595       Callee = DAG.getLoad(getPointerTy(), dl,
1596                            DAG.getEntryNode(), CPAddr,
1597                            MachinePointerInfo::getConstantPool(),
1598                            false, false, false, 0);
1599     }
1600   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1601     const GlobalValue *GV = G->getGlobal();
1602     isDirect = true;
1603     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1604     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1605                    getTargetMachine().getRelocationModel() != Reloc::Static;
1606     isARMFunc = !Subtarget->isThumb() || isStub;
1607     // ARM call to a local ARM function is predicable.
1608     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1609     // tBX takes a register source operand.
1610     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1611       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1612       ARMConstantPoolValue *CPV =
1613         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1614       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1615       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1616       Callee = DAG.getLoad(getPointerTy(), dl,
1617                            DAG.getEntryNode(), CPAddr,
1618                            MachinePointerInfo::getConstantPool(),
1619                            false, false, false, 0);
1620       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1621       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1622                            getPointerTy(), Callee, PICLabel);
1623     } else {
1624       // On ELF targets for PIC code, direct calls should go through the PLT
1625       unsigned OpFlags = 0;
1626       if (Subtarget->isTargetELF() &&
1627           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1628         OpFlags = ARMII::MO_PLT;
1629       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1630     }
1631   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1632     isDirect = true;
1633     bool isStub = Subtarget->isTargetDarwin() &&
1634                   getTargetMachine().getRelocationModel() != Reloc::Static;
1635     isARMFunc = !Subtarget->isThumb() || isStub;
1636     // tBX takes a register source operand.
1637     const char *Sym = S->getSymbol();
1638     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1639       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1640       ARMConstantPoolValue *CPV =
1641         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1642                                       ARMPCLabelIndex, 4);
1643       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1644       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1645       Callee = DAG.getLoad(getPointerTy(), dl,
1646                            DAG.getEntryNode(), CPAddr,
1647                            MachinePointerInfo::getConstantPool(),
1648                            false, false, false, 0);
1649       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1650       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1651                            getPointerTy(), Callee, PICLabel);
1652     } else {
1653       unsigned OpFlags = 0;
1654       // On ELF targets for PIC code, direct calls should go through the PLT
1655       if (Subtarget->isTargetELF() &&
1656                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1657         OpFlags = ARMII::MO_PLT;
1658       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1659     }
1660   }
1661
1662   // FIXME: handle tail calls differently.
1663   unsigned CallOpc;
1664   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1665     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1666   if (Subtarget->isThumb()) {
1667     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1668       CallOpc = ARMISD::CALL_NOLINK;
1669     else
1670       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1671   } else {
1672     if (!isDirect && !Subtarget->hasV5TOps())
1673       CallOpc = ARMISD::CALL_NOLINK;
1674     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1675                // Emit regular call when code size is the priority
1676                !HasMinSizeAttr)
1677       // "mov lr, pc; b _foo" to avoid confusing the RSP
1678       CallOpc = ARMISD::CALL_NOLINK;
1679     else
1680       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1681   }
1682
1683   std::vector<SDValue> Ops;
1684   Ops.push_back(Chain);
1685   Ops.push_back(Callee);
1686
1687   // Add argument registers to the end of the list so that they are known live
1688   // into the call.
1689   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1690     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1691                                   RegsToPass[i].second.getValueType()));
1692
1693   // Add a register mask operand representing the call-preserved registers.
1694   const uint32_t *Mask;
1695   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1696   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1697   if (IsThisReturn)
1698     // For 'this' returns, use the R0-preserving mask
1699     Mask = ARI->getThisReturnPreservedMask(CallConv);
1700   else
1701     Mask = ARI->getCallPreservedMask(CallConv);
1702
1703   assert(Mask && "Missing call preserved mask for calling convention");
1704   Ops.push_back(DAG.getRegisterMask(Mask));
1705
1706   if (InFlag.getNode())
1707     Ops.push_back(InFlag);
1708
1709   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1710   if (isTailCall)
1711     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1712
1713   // Returns a chain and a flag for retval copy to use.
1714   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1715   InFlag = Chain.getValue(1);
1716
1717   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1718                              DAG.getIntPtrConstant(0, true), InFlag);
1719   if (!Ins.empty())
1720     InFlag = Chain.getValue(1);
1721
1722   // Handle result values, copying them out of physregs into vregs that we
1723   // return.
1724   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1725                          InVals, IsThisReturn,
1726                          IsThisReturn ? OutVals[0] : SDValue());
1727 }
1728
1729 /// HandleByVal - Every parameter *after* a byval parameter is passed
1730 /// on the stack.  Remember the next parameter register to allocate,
1731 /// and then confiscate the rest of the parameter registers to insure
1732 /// this.
1733 void
1734 ARMTargetLowering::HandleByVal(
1735     CCState *State, unsigned &size, unsigned Align) const {
1736   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1737   assert((State->getCallOrPrologue() == Prologue ||
1738           State->getCallOrPrologue() == Call) &&
1739          "unhandled ParmContext");
1740   if ((!State->isFirstByValRegValid()) &&
1741       (!Subtarget->isAAPCS_ABI() || State->getNextStackOffset() == 0) &&
1742       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1743     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1744       unsigned AlignInRegs = Align / 4;
1745       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1746       for (unsigned i = 0; i < Waste; ++i)
1747         reg = State->AllocateReg(GPRArgRegs, 4);
1748     }
1749     if (reg != 0) {
1750       State->setFirstByValReg(reg);
1751       // At a call site, a byval parameter that is split between
1752       // registers and memory needs its size truncated here.  In a
1753       // function prologue, such byval parameters are reassembled in
1754       // memory, and are not truncated.
1755       if (State->getCallOrPrologue() == Call) {
1756         unsigned excess = 4 * (ARM::R4 - reg);
1757         assert(size >= excess && "expected larger existing stack allocation");
1758         size -= excess;
1759       }
1760     }
1761   }
1762   // Confiscate any remaining parameter registers to preclude their
1763   // assignment to subsequent parameters.
1764   while (State->AllocateReg(GPRArgRegs, 4))
1765     ;
1766 }
1767
1768 /// MatchingStackOffset - Return true if the given stack call argument is
1769 /// already available in the same position (relatively) of the caller's
1770 /// incoming argument stack.
1771 static
1772 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1773                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1774                          const TargetInstrInfo *TII) {
1775   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1776   int FI = INT_MAX;
1777   if (Arg.getOpcode() == ISD::CopyFromReg) {
1778     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1779     if (!TargetRegisterInfo::isVirtualRegister(VR))
1780       return false;
1781     MachineInstr *Def = MRI->getVRegDef(VR);
1782     if (!Def)
1783       return false;
1784     if (!Flags.isByVal()) {
1785       if (!TII->isLoadFromStackSlot(Def, FI))
1786         return false;
1787     } else {
1788       return false;
1789     }
1790   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1791     if (Flags.isByVal())
1792       // ByVal argument is passed in as a pointer but it's now being
1793       // dereferenced. e.g.
1794       // define @foo(%struct.X* %A) {
1795       //   tail call @bar(%struct.X* byval %A)
1796       // }
1797       return false;
1798     SDValue Ptr = Ld->getBasePtr();
1799     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1800     if (!FINode)
1801       return false;
1802     FI = FINode->getIndex();
1803   } else
1804     return false;
1805
1806   assert(FI != INT_MAX);
1807   if (!MFI->isFixedObjectIndex(FI))
1808     return false;
1809   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1810 }
1811
1812 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1813 /// for tail call optimization. Targets which want to do tail call
1814 /// optimization should implement this function.
1815 bool
1816 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1817                                                      CallingConv::ID CalleeCC,
1818                                                      bool isVarArg,
1819                                                      bool isCalleeStructRet,
1820                                                      bool isCallerStructRet,
1821                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1822                                     const SmallVectorImpl<SDValue> &OutVals,
1823                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1824                                                      SelectionDAG& DAG) const {
1825   const Function *CallerF = DAG.getMachineFunction().getFunction();
1826   CallingConv::ID CallerCC = CallerF->getCallingConv();
1827   bool CCMatch = CallerCC == CalleeCC;
1828
1829   // Look for obvious safe cases to perform tail call optimization that do not
1830   // require ABI changes. This is what gcc calls sibcall.
1831
1832   // Do not sibcall optimize vararg calls unless the call site is not passing
1833   // any arguments.
1834   if (isVarArg && !Outs.empty())
1835     return false;
1836
1837   // Also avoid sibcall optimization if either caller or callee uses struct
1838   // return semantics.
1839   if (isCalleeStructRet || isCallerStructRet)
1840     return false;
1841
1842   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1843   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1844   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1845   // support in the assembler and linker to be used. This would need to be
1846   // fixed to fully support tail calls in Thumb1.
1847   //
1848   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1849   // LR.  This means if we need to reload LR, it takes an extra instructions,
1850   // which outweighs the value of the tail call; but here we don't know yet
1851   // whether LR is going to be used.  Probably the right approach is to
1852   // generate the tail call here and turn it back into CALL/RET in
1853   // emitEpilogue if LR is used.
1854
1855   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1856   // but we need to make sure there are enough registers; the only valid
1857   // registers are the 4 used for parameters.  We don't currently do this
1858   // case.
1859   if (Subtarget->isThumb1Only())
1860     return false;
1861
1862   // If the calling conventions do not match, then we'd better make sure the
1863   // results are returned in the same way as what the caller expects.
1864   if (!CCMatch) {
1865     SmallVector<CCValAssign, 16> RVLocs1;
1866     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1867                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1868     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1869
1870     SmallVector<CCValAssign, 16> RVLocs2;
1871     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1872                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1873     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1874
1875     if (RVLocs1.size() != RVLocs2.size())
1876       return false;
1877     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1878       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1879         return false;
1880       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1881         return false;
1882       if (RVLocs1[i].isRegLoc()) {
1883         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1884           return false;
1885       } else {
1886         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1887           return false;
1888       }
1889     }
1890   }
1891
1892   // If Caller's vararg or byval argument has been split between registers and
1893   // stack, do not perform tail call, since part of the argument is in caller's
1894   // local frame.
1895   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1896                                       getInfo<ARMFunctionInfo>();
1897   if (AFI_Caller->getVarArgsRegSaveSize())
1898     return false;
1899
1900   // If the callee takes no arguments then go on to check the results of the
1901   // call.
1902   if (!Outs.empty()) {
1903     // Check if stack adjustment is needed. For now, do not do this if any
1904     // argument is passed on the stack.
1905     SmallVector<CCValAssign, 16> ArgLocs;
1906     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1907                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1908     CCInfo.AnalyzeCallOperands(Outs,
1909                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1910     if (CCInfo.getNextStackOffset()) {
1911       MachineFunction &MF = DAG.getMachineFunction();
1912
1913       // Check if the arguments are already laid out in the right way as
1914       // the caller's fixed stack objects.
1915       MachineFrameInfo *MFI = MF.getFrameInfo();
1916       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1917       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1918       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1919            i != e;
1920            ++i, ++realArgIdx) {
1921         CCValAssign &VA = ArgLocs[i];
1922         EVT RegVT = VA.getLocVT();
1923         SDValue Arg = OutVals[realArgIdx];
1924         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1925         if (VA.getLocInfo() == CCValAssign::Indirect)
1926           return false;
1927         if (VA.needsCustom()) {
1928           // f64 and vector types are split into multiple registers or
1929           // register/stack-slot combinations.  The types will not match
1930           // the registers; give up on memory f64 refs until we figure
1931           // out what to do about this.
1932           if (!VA.isRegLoc())
1933             return false;
1934           if (!ArgLocs[++i].isRegLoc())
1935             return false;
1936           if (RegVT == MVT::v2f64) {
1937             if (!ArgLocs[++i].isRegLoc())
1938               return false;
1939             if (!ArgLocs[++i].isRegLoc())
1940               return false;
1941           }
1942         } else if (!VA.isRegLoc()) {
1943           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1944                                    MFI, MRI, TII))
1945             return false;
1946         }
1947       }
1948     }
1949   }
1950
1951   return true;
1952 }
1953
1954 bool
1955 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1956                                   MachineFunction &MF, bool isVarArg,
1957                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
1958                                   LLVMContext &Context) const {
1959   SmallVector<CCValAssign, 16> RVLocs;
1960   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1961   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1962                                                     isVarArg));
1963 }
1964
1965 SDValue
1966 ARMTargetLowering::LowerReturn(SDValue Chain,
1967                                CallingConv::ID CallConv, bool isVarArg,
1968                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1969                                const SmallVectorImpl<SDValue> &OutVals,
1970                                DebugLoc dl, SelectionDAG &DAG) const {
1971
1972   // CCValAssign - represent the assignment of the return value to a location.
1973   SmallVector<CCValAssign, 16> RVLocs;
1974
1975   // CCState - Info about the registers and stack slots.
1976   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1977                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1978
1979   // Analyze outgoing return values.
1980   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1981                                                isVarArg));
1982
1983   SDValue Flag;
1984   SmallVector<SDValue, 4> RetOps;
1985   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1986
1987   // Copy the result values into the output registers.
1988   for (unsigned i = 0, realRVLocIdx = 0;
1989        i != RVLocs.size();
1990        ++i, ++realRVLocIdx) {
1991     CCValAssign &VA = RVLocs[i];
1992     assert(VA.isRegLoc() && "Can only return in registers!");
1993
1994     SDValue Arg = OutVals[realRVLocIdx];
1995
1996     switch (VA.getLocInfo()) {
1997     default: llvm_unreachable("Unknown loc info!");
1998     case CCValAssign::Full: break;
1999     case CCValAssign::BCvt:
2000       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2001       break;
2002     }
2003
2004     if (VA.needsCustom()) {
2005       if (VA.getLocVT() == MVT::v2f64) {
2006         // Extract the first half and return it in two registers.
2007         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2008                                    DAG.getConstant(0, MVT::i32));
2009         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2010                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2011
2012         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2013         Flag = Chain.getValue(1);
2014         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2015         VA = RVLocs[++i]; // skip ahead to next loc
2016         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2017                                  HalfGPRs.getValue(1), Flag);
2018         Flag = Chain.getValue(1);
2019         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2020         VA = RVLocs[++i]; // skip ahead to next loc
2021
2022         // Extract the 2nd half and fall through to handle it as an f64 value.
2023         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2024                           DAG.getConstant(1, MVT::i32));
2025       }
2026       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2027       // available.
2028       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2029                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2030       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2031       Flag = Chain.getValue(1);
2032       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2033       VA = RVLocs[++i]; // skip ahead to next loc
2034       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2035                                Flag);
2036     } else
2037       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2038
2039     // Guarantee that all emitted copies are
2040     // stuck together, avoiding something bad.
2041     Flag = Chain.getValue(1);
2042     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2043   }
2044
2045   // Update chain and glue.
2046   RetOps[0] = Chain;
2047   if (Flag.getNode())
2048     RetOps.push_back(Flag);
2049
2050   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2051                      RetOps.data(), RetOps.size());
2052 }
2053
2054 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2055   if (N->getNumValues() != 1)
2056     return false;
2057   if (!N->hasNUsesOfValue(1, 0))
2058     return false;
2059
2060   SDValue TCChain = Chain;
2061   SDNode *Copy = *N->use_begin();
2062   if (Copy->getOpcode() == ISD::CopyToReg) {
2063     // If the copy has a glue operand, we conservatively assume it isn't safe to
2064     // perform a tail call.
2065     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2066       return false;
2067     TCChain = Copy->getOperand(0);
2068   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2069     SDNode *VMov = Copy;
2070     // f64 returned in a pair of GPRs.
2071     SmallPtrSet<SDNode*, 2> Copies;
2072     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2073          UI != UE; ++UI) {
2074       if (UI->getOpcode() != ISD::CopyToReg)
2075         return false;
2076       Copies.insert(*UI);
2077     }
2078     if (Copies.size() > 2)
2079       return false;
2080
2081     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2082          UI != UE; ++UI) {
2083       SDValue UseChain = UI->getOperand(0);
2084       if (Copies.count(UseChain.getNode()))
2085         // Second CopyToReg
2086         Copy = *UI;
2087       else
2088         // First CopyToReg
2089         TCChain = UseChain;
2090     }
2091   } else if (Copy->getOpcode() == ISD::BITCAST) {
2092     // f32 returned in a single GPR.
2093     if (!Copy->hasOneUse())
2094       return false;
2095     Copy = *Copy->use_begin();
2096     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2097       return false;
2098     Chain = Copy->getOperand(0);
2099   } else {
2100     return false;
2101   }
2102
2103   bool HasRet = false;
2104   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2105        UI != UE; ++UI) {
2106     if (UI->getOpcode() != ARMISD::RET_FLAG)
2107       return false;
2108     HasRet = true;
2109   }
2110
2111   if (!HasRet)
2112     return false;
2113
2114   Chain = TCChain;
2115   return true;
2116 }
2117
2118 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2120     return false;
2121
2122   if (!CI->isTailCall())
2123     return false;
2124
2125   return !Subtarget->isThumb1Only();
2126 }
2127
2128 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2129 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2130 // one of the above mentioned nodes. It has to be wrapped because otherwise
2131 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2132 // be used to form addressing mode. These wrapped nodes will be selected
2133 // into MOVi.
2134 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2135   EVT PtrVT = Op.getValueType();
2136   // FIXME there is no actual debug info here
2137   DebugLoc dl = Op.getDebugLoc();
2138   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2139   SDValue Res;
2140   if (CP->isMachineConstantPoolEntry())
2141     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2142                                     CP->getAlignment());
2143   else
2144     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2145                                     CP->getAlignment());
2146   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2147 }
2148
2149 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2150   return MachineJumpTableInfo::EK_Inline;
2151 }
2152
2153 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2154                                              SelectionDAG &DAG) const {
2155   MachineFunction &MF = DAG.getMachineFunction();
2156   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2157   unsigned ARMPCLabelIndex = 0;
2158   DebugLoc DL = Op.getDebugLoc();
2159   EVT PtrVT = getPointerTy();
2160   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2161   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2162   SDValue CPAddr;
2163   if (RelocM == Reloc::Static) {
2164     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2165   } else {
2166     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2167     ARMPCLabelIndex = AFI->createPICLabelUId();
2168     ARMConstantPoolValue *CPV =
2169       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2170                                       ARMCP::CPBlockAddress, PCAdj);
2171     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2172   }
2173   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2174   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2175                                MachinePointerInfo::getConstantPool(),
2176                                false, false, false, 0);
2177   if (RelocM == Reloc::Static)
2178     return Result;
2179   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2180   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2181 }
2182
2183 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2184 SDValue
2185 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2186                                                  SelectionDAG &DAG) const {
2187   DebugLoc dl = GA->getDebugLoc();
2188   EVT PtrVT = getPointerTy();
2189   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2190   MachineFunction &MF = DAG.getMachineFunction();
2191   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2192   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2193   ARMConstantPoolValue *CPV =
2194     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2195                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2196   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2197   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2198   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2199                          MachinePointerInfo::getConstantPool(),
2200                          false, false, false, 0);
2201   SDValue Chain = Argument.getValue(1);
2202
2203   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2204   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2205
2206   // call __tls_get_addr.
2207   ArgListTy Args;
2208   ArgListEntry Entry;
2209   Entry.Node = Argument;
2210   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2211   Args.push_back(Entry);
2212   // FIXME: is there useful debug info available here?
2213   TargetLowering::CallLoweringInfo CLI(Chain,
2214                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2215                 false, false, false, false,
2216                 0, CallingConv::C, /*isTailCall=*/false,
2217                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2218                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2219   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2220   return CallResult.first;
2221 }
2222
2223 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2224 // "local exec" model.
2225 SDValue
2226 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2227                                         SelectionDAG &DAG,
2228                                         TLSModel::Model model) const {
2229   const GlobalValue *GV = GA->getGlobal();
2230   DebugLoc dl = GA->getDebugLoc();
2231   SDValue Offset;
2232   SDValue Chain = DAG.getEntryNode();
2233   EVT PtrVT = getPointerTy();
2234   // Get the Thread Pointer
2235   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2236
2237   if (model == TLSModel::InitialExec) {
2238     MachineFunction &MF = DAG.getMachineFunction();
2239     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2240     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2241     // Initial exec model.
2242     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2243     ARMConstantPoolValue *CPV =
2244       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2245                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2246                                       true);
2247     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2248     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2249     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2250                          MachinePointerInfo::getConstantPool(),
2251                          false, false, false, 0);
2252     Chain = Offset.getValue(1);
2253
2254     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2255     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2256
2257     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2258                          MachinePointerInfo::getConstantPool(),
2259                          false, false, false, 0);
2260   } else {
2261     // local exec model
2262     assert(model == TLSModel::LocalExec);
2263     ARMConstantPoolValue *CPV =
2264       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2265     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2266     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2267     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2268                          MachinePointerInfo::getConstantPool(),
2269                          false, false, false, 0);
2270   }
2271
2272   // The address of the thread local variable is the add of the thread
2273   // pointer with the offset of the variable.
2274   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2275 }
2276
2277 SDValue
2278 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2279   // TODO: implement the "local dynamic" model
2280   assert(Subtarget->isTargetELF() &&
2281          "TLS not implemented for non-ELF targets");
2282   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2283
2284   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2285
2286   switch (model) {
2287     case TLSModel::GeneralDynamic:
2288     case TLSModel::LocalDynamic:
2289       return LowerToTLSGeneralDynamicModel(GA, DAG);
2290     case TLSModel::InitialExec:
2291     case TLSModel::LocalExec:
2292       return LowerToTLSExecModels(GA, DAG, model);
2293   }
2294   llvm_unreachable("bogus TLS model");
2295 }
2296
2297 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2298                                                  SelectionDAG &DAG) const {
2299   EVT PtrVT = getPointerTy();
2300   DebugLoc dl = Op.getDebugLoc();
2301   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2302   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2303     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2304     ARMConstantPoolValue *CPV =
2305       ARMConstantPoolConstant::Create(GV,
2306                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2307     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2308     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2309     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2310                                  CPAddr,
2311                                  MachinePointerInfo::getConstantPool(),
2312                                  false, false, false, 0);
2313     SDValue Chain = Result.getValue(1);
2314     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2315     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2316     if (!UseGOTOFF)
2317       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2318                            MachinePointerInfo::getGOT(),
2319                            false, false, false, 0);
2320     return Result;
2321   }
2322
2323   // If we have T2 ops, we can materialize the address directly via movt/movw
2324   // pair. This is always cheaper.
2325   if (Subtarget->useMovt()) {
2326     ++NumMovwMovt;
2327     // FIXME: Once remat is capable of dealing with instructions with register
2328     // operands, expand this into two nodes.
2329     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2330                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2331   } else {
2332     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2333     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2334     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2335                        MachinePointerInfo::getConstantPool(),
2336                        false, false, false, 0);
2337   }
2338 }
2339
2340 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2341                                                     SelectionDAG &DAG) const {
2342   EVT PtrVT = getPointerTy();
2343   DebugLoc dl = Op.getDebugLoc();
2344   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2345   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2346
2347   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2348   // update ARMFastISel::ARMMaterializeGV.
2349   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2350     ++NumMovwMovt;
2351     // FIXME: Once remat is capable of dealing with instructions with register
2352     // operands, expand this into two nodes.
2353     if (RelocM == Reloc::Static)
2354       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2355                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2356
2357     unsigned Wrapper = (RelocM == Reloc::PIC_)
2358       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2359     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2360                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2361     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2362       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2363                            MachinePointerInfo::getGOT(),
2364                            false, false, false, 0);
2365     return Result;
2366   }
2367
2368   unsigned ARMPCLabelIndex = 0;
2369   SDValue CPAddr;
2370   if (RelocM == Reloc::Static) {
2371     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2372   } else {
2373     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2374     ARMPCLabelIndex = AFI->createPICLabelUId();
2375     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2376     ARMConstantPoolValue *CPV =
2377       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2378                                       PCAdj);
2379     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2380   }
2381   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2382
2383   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2384                                MachinePointerInfo::getConstantPool(),
2385                                false, false, false, 0);
2386   SDValue Chain = Result.getValue(1);
2387
2388   if (RelocM == Reloc::PIC_) {
2389     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2390     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2391   }
2392
2393   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2394     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2395                          false, false, false, 0);
2396
2397   return Result;
2398 }
2399
2400 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2401                                                     SelectionDAG &DAG) const {
2402   assert(Subtarget->isTargetELF() &&
2403          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2404   MachineFunction &MF = DAG.getMachineFunction();
2405   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2406   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2407   EVT PtrVT = getPointerTy();
2408   DebugLoc dl = Op.getDebugLoc();
2409   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2410   ARMConstantPoolValue *CPV =
2411     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2412                                   ARMPCLabelIndex, PCAdj);
2413   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2414   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2415   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2416                                MachinePointerInfo::getConstantPool(),
2417                                false, false, false, 0);
2418   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2419   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2420 }
2421
2422 SDValue
2423 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2424   DebugLoc dl = Op.getDebugLoc();
2425   SDValue Val = DAG.getConstant(0, MVT::i32);
2426   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2427                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2428                      Op.getOperand(1), Val);
2429 }
2430
2431 SDValue
2432 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2433   DebugLoc dl = Op.getDebugLoc();
2434   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2435                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2436 }
2437
2438 SDValue
2439 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2440                                           const ARMSubtarget *Subtarget) const {
2441   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2442   DebugLoc dl = Op.getDebugLoc();
2443   switch (IntNo) {
2444   default: return SDValue();    // Don't custom lower most intrinsics.
2445   case Intrinsic::arm_thread_pointer: {
2446     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2447     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2448   }
2449   case Intrinsic::eh_sjlj_lsda: {
2450     MachineFunction &MF = DAG.getMachineFunction();
2451     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2452     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2453     EVT PtrVT = getPointerTy();
2454     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2455     SDValue CPAddr;
2456     unsigned PCAdj = (RelocM != Reloc::PIC_)
2457       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2458     ARMConstantPoolValue *CPV =
2459       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2460                                       ARMCP::CPLSDA, PCAdj);
2461     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2462     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2463     SDValue Result =
2464       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2465                   MachinePointerInfo::getConstantPool(),
2466                   false, false, false, 0);
2467
2468     if (RelocM == Reloc::PIC_) {
2469       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2470       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2471     }
2472     return Result;
2473   }
2474   case Intrinsic::arm_neon_vmulls:
2475   case Intrinsic::arm_neon_vmullu: {
2476     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2477       ? ARMISD::VMULLs : ARMISD::VMULLu;
2478     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2479                        Op.getOperand(1), Op.getOperand(2));
2480   }
2481   }
2482 }
2483
2484 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2485                                  const ARMSubtarget *Subtarget) {
2486   // FIXME: handle "fence singlethread" more efficiently.
2487   DebugLoc dl = Op.getDebugLoc();
2488   if (!Subtarget->hasDataBarrier()) {
2489     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2490     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2491     // here.
2492     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2493            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2494     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2495                        DAG.getConstant(0, MVT::i32));
2496   }
2497
2498   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2499                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2500 }
2501
2502 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2503                              const ARMSubtarget *Subtarget) {
2504   // ARM pre v5TE and Thumb1 does not have preload instructions.
2505   if (!(Subtarget->isThumb2() ||
2506         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2507     // Just preserve the chain.
2508     return Op.getOperand(0);
2509
2510   DebugLoc dl = Op.getDebugLoc();
2511   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2512   if (!isRead &&
2513       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2514     // ARMv7 with MP extension has PLDW.
2515     return Op.getOperand(0);
2516
2517   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2518   if (Subtarget->isThumb()) {
2519     // Invert the bits.
2520     isRead = ~isRead & 1;
2521     isData = ~isData & 1;
2522   }
2523
2524   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2525                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2526                      DAG.getConstant(isData, MVT::i32));
2527 }
2528
2529 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2530   MachineFunction &MF = DAG.getMachineFunction();
2531   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2532
2533   // vastart just stores the address of the VarArgsFrameIndex slot into the
2534   // memory location argument.
2535   DebugLoc dl = Op.getDebugLoc();
2536   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2537   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2538   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2539   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2540                       MachinePointerInfo(SV), false, false, 0);
2541 }
2542
2543 SDValue
2544 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2545                                         SDValue &Root, SelectionDAG &DAG,
2546                                         DebugLoc dl) const {
2547   MachineFunction &MF = DAG.getMachineFunction();
2548   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2549
2550   const TargetRegisterClass *RC;
2551   if (AFI->isThumb1OnlyFunction())
2552     RC = &ARM::tGPRRegClass;
2553   else
2554     RC = &ARM::GPRRegClass;
2555
2556   // Transform the arguments stored in physical registers into virtual ones.
2557   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2558   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2559
2560   SDValue ArgValue2;
2561   if (NextVA.isMemLoc()) {
2562     MachineFrameInfo *MFI = MF.getFrameInfo();
2563     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2564
2565     // Create load node to retrieve arguments from the stack.
2566     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2567     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2568                             MachinePointerInfo::getFixedStack(FI),
2569                             false, false, false, 0);
2570   } else {
2571     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2572     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2573   }
2574
2575   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2576 }
2577
2578 void
2579 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2580                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2581   const {
2582   unsigned NumGPRs;
2583   if (CCInfo.isFirstByValRegValid())
2584     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2585   else {
2586     unsigned int firstUnalloced;
2587     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2588                                                 sizeof(GPRArgRegs) /
2589                                                 sizeof(GPRArgRegs[0]));
2590     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2591   }
2592
2593   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2594   VARegSize = NumGPRs * 4;
2595   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2596 }
2597
2598 // The remaining GPRs hold either the beginning of variable-argument
2599 // data, or the beginning of an aggregate passed by value (usually
2600 // byval).  Either way, we allocate stack slots adjacent to the data
2601 // provided by our caller, and store the unallocated registers there.
2602 // If this is a variadic function, the va_list pointer will begin with
2603 // these values; otherwise, this reassembles a (byval) structure that
2604 // was split between registers and memory.
2605 void
2606 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2607                                         DebugLoc dl, SDValue &Chain,
2608                                         const Value *OrigArg,
2609                                         unsigned OffsetFromOrigArg,
2610                                         unsigned ArgOffset,
2611                                         bool ForceMutable) const {
2612   MachineFunction &MF = DAG.getMachineFunction();
2613   MachineFrameInfo *MFI = MF.getFrameInfo();
2614   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2615   unsigned firstRegToSaveIndex;
2616   if (CCInfo.isFirstByValRegValid())
2617     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2618   else {
2619     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2620       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2621   }
2622
2623   unsigned VARegSize, VARegSaveSize;
2624   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2625   if (VARegSaveSize) {
2626     // If this function is vararg, store any remaining integer argument regs
2627     // to their spots on the stack so that they may be loaded by deferencing
2628     // the result of va_next.
2629     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2630     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2631                                                      ArgOffset + VARegSaveSize
2632                                                      - VARegSize,
2633                                                      false));
2634     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2635                                     getPointerTy());
2636
2637     SmallVector<SDValue, 4> MemOps;
2638     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2639       const TargetRegisterClass *RC;
2640       if (AFI->isThumb1OnlyFunction())
2641         RC = &ARM::tGPRRegClass;
2642       else
2643         RC = &ARM::GPRRegClass;
2644
2645       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2646       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2647       SDValue Store =
2648         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2649                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2650                      false, false, 0);
2651       MemOps.push_back(Store);
2652       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2653                         DAG.getConstant(4, getPointerTy()));
2654     }
2655     if (!MemOps.empty())
2656       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2657                           &MemOps[0], MemOps.size());
2658   } else
2659     // This will point to the next argument passed via stack.
2660     AFI->setVarArgsFrameIndex(
2661         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2662 }
2663
2664 SDValue
2665 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2666                                         CallingConv::ID CallConv, bool isVarArg,
2667                                         const SmallVectorImpl<ISD::InputArg>
2668                                           &Ins,
2669                                         DebugLoc dl, SelectionDAG &DAG,
2670                                         SmallVectorImpl<SDValue> &InVals)
2671                                           const {
2672   MachineFunction &MF = DAG.getMachineFunction();
2673   MachineFrameInfo *MFI = MF.getFrameInfo();
2674
2675   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2676
2677   // Assign locations to all of the incoming arguments.
2678   SmallVector<CCValAssign, 16> ArgLocs;
2679   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2680                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2681   CCInfo.AnalyzeFormalArguments(Ins,
2682                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2683                                                   isVarArg));
2684
2685   SmallVector<SDValue, 16> ArgValues;
2686   int lastInsIndex = -1;
2687   SDValue ArgValue;
2688   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2689   unsigned CurArgIdx = 0;
2690   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2691     CCValAssign &VA = ArgLocs[i];
2692     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2693     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2694     // Arguments stored in registers.
2695     if (VA.isRegLoc()) {
2696       EVT RegVT = VA.getLocVT();
2697
2698       if (VA.needsCustom()) {
2699         // f64 and vector types are split up into multiple registers or
2700         // combinations of registers and stack slots.
2701         if (VA.getLocVT() == MVT::v2f64) {
2702           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2703                                                    Chain, DAG, dl);
2704           VA = ArgLocs[++i]; // skip ahead to next loc
2705           SDValue ArgValue2;
2706           if (VA.isMemLoc()) {
2707             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2708             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2709             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2710                                     MachinePointerInfo::getFixedStack(FI),
2711                                     false, false, false, 0);
2712           } else {
2713             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2714                                              Chain, DAG, dl);
2715           }
2716           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2717           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2718                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2719           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2720                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2721         } else
2722           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2723
2724       } else {
2725         const TargetRegisterClass *RC;
2726
2727         if (RegVT == MVT::f32)
2728           RC = &ARM::SPRRegClass;
2729         else if (RegVT == MVT::f64)
2730           RC = &ARM::DPRRegClass;
2731         else if (RegVT == MVT::v2f64)
2732           RC = &ARM::QPRRegClass;
2733         else if (RegVT == MVT::i32)
2734           RC = AFI->isThumb1OnlyFunction() ?
2735             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2736             (const TargetRegisterClass*)&ARM::GPRRegClass;
2737         else
2738           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2739
2740         // Transform the arguments in physical registers into virtual ones.
2741         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2742         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2743       }
2744
2745       // If this is an 8 or 16-bit value, it is really passed promoted
2746       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2747       // truncate to the right size.
2748       switch (VA.getLocInfo()) {
2749       default: llvm_unreachable("Unknown loc info!");
2750       case CCValAssign::Full: break;
2751       case CCValAssign::BCvt:
2752         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2753         break;
2754       case CCValAssign::SExt:
2755         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2756                                DAG.getValueType(VA.getValVT()));
2757         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2758         break;
2759       case CCValAssign::ZExt:
2760         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2761                                DAG.getValueType(VA.getValVT()));
2762         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2763         break;
2764       }
2765
2766       InVals.push_back(ArgValue);
2767
2768     } else { // VA.isRegLoc()
2769
2770       // sanity check
2771       assert(VA.isMemLoc());
2772       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2773
2774       int index = ArgLocs[i].getValNo();
2775
2776       // Some Ins[] entries become multiple ArgLoc[] entries.
2777       // Process them only once.
2778       if (index != lastInsIndex)
2779         {
2780           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2781           // FIXME: For now, all byval parameter objects are marked mutable.
2782           // This can be changed with more analysis.
2783           // In case of tail call optimization mark all arguments mutable.
2784           // Since they could be overwritten by lowering of arguments in case of
2785           // a tail call.
2786           if (Flags.isByVal()) {
2787             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2788             if (!AFI->getVarArgsFrameIndex()) {
2789               VarArgStyleRegisters(CCInfo, DAG,
2790                                    dl, Chain, CurOrigArg,
2791                                    Ins[VA.getValNo()].PartOffset,
2792                                    VA.getLocMemOffset(),
2793                                    true /*force mutable frames*/);
2794               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2795               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2796             } else {
2797               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2798                                               VA.getLocMemOffset(), false);
2799               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2800             }
2801           } else {
2802             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2803                                             VA.getLocMemOffset(), true);
2804
2805             // Create load nodes to retrieve arguments from the stack.
2806             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2807             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2808                                          MachinePointerInfo::getFixedStack(FI),
2809                                          false, false, false, 0));
2810           }
2811           lastInsIndex = index;
2812         }
2813     }
2814   }
2815
2816   // varargs
2817   if (isVarArg)
2818     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2819                          CCInfo.getNextStackOffset());
2820
2821   return Chain;
2822 }
2823
2824 /// isFloatingPointZero - Return true if this is +0.0.
2825 static bool isFloatingPointZero(SDValue Op) {
2826   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2827     return CFP->getValueAPF().isPosZero();
2828   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2829     // Maybe this has already been legalized into the constant pool?
2830     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2831       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2832       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2833         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2834           return CFP->getValueAPF().isPosZero();
2835     }
2836   }
2837   return false;
2838 }
2839
2840 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2841 /// the given operands.
2842 SDValue
2843 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2844                              SDValue &ARMcc, SelectionDAG &DAG,
2845                              DebugLoc dl) const {
2846   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2847     unsigned C = RHSC->getZExtValue();
2848     if (!isLegalICmpImmediate(C)) {
2849       // Constant does not fit, try adjusting it by one?
2850       switch (CC) {
2851       default: break;
2852       case ISD::SETLT:
2853       case ISD::SETGE:
2854         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2855           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2856           RHS = DAG.getConstant(C-1, MVT::i32);
2857         }
2858         break;
2859       case ISD::SETULT:
2860       case ISD::SETUGE:
2861         if (C != 0 && isLegalICmpImmediate(C-1)) {
2862           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2863           RHS = DAG.getConstant(C-1, MVT::i32);
2864         }
2865         break;
2866       case ISD::SETLE:
2867       case ISD::SETGT:
2868         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2869           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2870           RHS = DAG.getConstant(C+1, MVT::i32);
2871         }
2872         break;
2873       case ISD::SETULE:
2874       case ISD::SETUGT:
2875         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2876           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2877           RHS = DAG.getConstant(C+1, MVT::i32);
2878         }
2879         break;
2880       }
2881     }
2882   }
2883
2884   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2885   ARMISD::NodeType CompareType;
2886   switch (CondCode) {
2887   default:
2888     CompareType = ARMISD::CMP;
2889     break;
2890   case ARMCC::EQ:
2891   case ARMCC::NE:
2892     // Uses only Z Flag
2893     CompareType = ARMISD::CMPZ;
2894     break;
2895   }
2896   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2897   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2898 }
2899
2900 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2901 SDValue
2902 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2903                              DebugLoc dl) const {
2904   SDValue Cmp;
2905   if (!isFloatingPointZero(RHS))
2906     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2907   else
2908     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2909   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2910 }
2911
2912 /// duplicateCmp - Glue values can have only one use, so this function
2913 /// duplicates a comparison node.
2914 SDValue
2915 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2916   unsigned Opc = Cmp.getOpcode();
2917   DebugLoc DL = Cmp.getDebugLoc();
2918   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2919     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2920
2921   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2922   Cmp = Cmp.getOperand(0);
2923   Opc = Cmp.getOpcode();
2924   if (Opc == ARMISD::CMPFP)
2925     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2926   else {
2927     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2928     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2929   }
2930   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2931 }
2932
2933 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2934   SDValue Cond = Op.getOperand(0);
2935   SDValue SelectTrue = Op.getOperand(1);
2936   SDValue SelectFalse = Op.getOperand(2);
2937   DebugLoc dl = Op.getDebugLoc();
2938
2939   // Convert:
2940   //
2941   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2942   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2943   //
2944   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2945     const ConstantSDNode *CMOVTrue =
2946       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2947     const ConstantSDNode *CMOVFalse =
2948       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2949
2950     if (CMOVTrue && CMOVFalse) {
2951       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2952       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2953
2954       SDValue True;
2955       SDValue False;
2956       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2957         True = SelectTrue;
2958         False = SelectFalse;
2959       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2960         True = SelectFalse;
2961         False = SelectTrue;
2962       }
2963
2964       if (True.getNode() && False.getNode()) {
2965         EVT VT = Op.getValueType();
2966         SDValue ARMcc = Cond.getOperand(2);
2967         SDValue CCR = Cond.getOperand(3);
2968         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2969         assert(True.getValueType() == VT);
2970         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2971       }
2972     }
2973   }
2974
2975   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2976   // undefined bits before doing a full-word comparison with zero.
2977   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2978                      DAG.getConstant(1, Cond.getValueType()));
2979
2980   return DAG.getSelectCC(dl, Cond,
2981                          DAG.getConstant(0, Cond.getValueType()),
2982                          SelectTrue, SelectFalse, ISD::SETNE);
2983 }
2984
2985 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2986   EVT VT = Op.getValueType();
2987   SDValue LHS = Op.getOperand(0);
2988   SDValue RHS = Op.getOperand(1);
2989   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2990   SDValue TrueVal = Op.getOperand(2);
2991   SDValue FalseVal = Op.getOperand(3);
2992   DebugLoc dl = Op.getDebugLoc();
2993
2994   if (LHS.getValueType() == MVT::i32) {
2995     SDValue ARMcc;
2996     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2997     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2998     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2999   }
3000
3001   ARMCC::CondCodes CondCode, CondCode2;
3002   FPCCToARMCC(CC, CondCode, CondCode2);
3003
3004   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3005   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3006   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3007   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3008                                ARMcc, CCR, Cmp);
3009   if (CondCode2 != ARMCC::AL) {
3010     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3011     // FIXME: Needs another CMP because flag can have but one use.
3012     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3013     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3014                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3015   }
3016   return Result;
3017 }
3018
3019 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3020 /// to morph to an integer compare sequence.
3021 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3022                            const ARMSubtarget *Subtarget) {
3023   SDNode *N = Op.getNode();
3024   if (!N->hasOneUse())
3025     // Otherwise it requires moving the value from fp to integer registers.
3026     return false;
3027   if (!N->getNumValues())
3028     return false;
3029   EVT VT = Op.getValueType();
3030   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3031     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3032     // vmrs are very slow, e.g. cortex-a8.
3033     return false;
3034
3035   if (isFloatingPointZero(Op)) {
3036     SeenZero = true;
3037     return true;
3038   }
3039   return ISD::isNormalLoad(N);
3040 }
3041
3042 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3043   if (isFloatingPointZero(Op))
3044     return DAG.getConstant(0, MVT::i32);
3045
3046   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3047     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3048                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3049                        Ld->isVolatile(), Ld->isNonTemporal(),
3050                        Ld->isInvariant(), Ld->getAlignment());
3051
3052   llvm_unreachable("Unknown VFP cmp argument!");
3053 }
3054
3055 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3056                            SDValue &RetVal1, SDValue &RetVal2) {
3057   if (isFloatingPointZero(Op)) {
3058     RetVal1 = DAG.getConstant(0, MVT::i32);
3059     RetVal2 = DAG.getConstant(0, MVT::i32);
3060     return;
3061   }
3062
3063   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3064     SDValue Ptr = Ld->getBasePtr();
3065     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3066                           Ld->getChain(), Ptr,
3067                           Ld->getPointerInfo(),
3068                           Ld->isVolatile(), Ld->isNonTemporal(),
3069                           Ld->isInvariant(), Ld->getAlignment());
3070
3071     EVT PtrType = Ptr.getValueType();
3072     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3073     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3074                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3075     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3076                           Ld->getChain(), NewPtr,
3077                           Ld->getPointerInfo().getWithOffset(4),
3078                           Ld->isVolatile(), Ld->isNonTemporal(),
3079                           Ld->isInvariant(), NewAlign);
3080     return;
3081   }
3082
3083   llvm_unreachable("Unknown VFP cmp argument!");
3084 }
3085
3086 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3087 /// f32 and even f64 comparisons to integer ones.
3088 SDValue
3089 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3090   SDValue Chain = Op.getOperand(0);
3091   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3092   SDValue LHS = Op.getOperand(2);
3093   SDValue RHS = Op.getOperand(3);
3094   SDValue Dest = Op.getOperand(4);
3095   DebugLoc dl = Op.getDebugLoc();
3096
3097   bool LHSSeenZero = false;
3098   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3099   bool RHSSeenZero = false;
3100   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3101   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3102     // If unsafe fp math optimization is enabled and there are no other uses of
3103     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3104     // to an integer comparison.
3105     if (CC == ISD::SETOEQ)
3106       CC = ISD::SETEQ;
3107     else if (CC == ISD::SETUNE)
3108       CC = ISD::SETNE;
3109
3110     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3111     SDValue ARMcc;
3112     if (LHS.getValueType() == MVT::f32) {
3113       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3114                         bitcastf32Toi32(LHS, DAG), Mask);
3115       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3116                         bitcastf32Toi32(RHS, DAG), Mask);
3117       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3118       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3119       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3120                          Chain, Dest, ARMcc, CCR, Cmp);
3121     }
3122
3123     SDValue LHS1, LHS2;
3124     SDValue RHS1, RHS2;
3125     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3126     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3127     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3128     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3129     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3130     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3131     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3132     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3133     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3134   }
3135
3136   return SDValue();
3137 }
3138
3139 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3140   SDValue Chain = Op.getOperand(0);
3141   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3142   SDValue LHS = Op.getOperand(2);
3143   SDValue RHS = Op.getOperand(3);
3144   SDValue Dest = Op.getOperand(4);
3145   DebugLoc dl = Op.getDebugLoc();
3146
3147   if (LHS.getValueType() == MVT::i32) {
3148     SDValue ARMcc;
3149     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3150     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3151     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3152                        Chain, Dest, ARMcc, CCR, Cmp);
3153   }
3154
3155   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3156
3157   if (getTargetMachine().Options.UnsafeFPMath &&
3158       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3159        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3160     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3161     if (Result.getNode())
3162       return Result;
3163   }
3164
3165   ARMCC::CondCodes CondCode, CondCode2;
3166   FPCCToARMCC(CC, CondCode, CondCode2);
3167
3168   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3169   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3170   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3171   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3172   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3173   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3174   if (CondCode2 != ARMCC::AL) {
3175     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3176     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3177     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3178   }
3179   return Res;
3180 }
3181
3182 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3183   SDValue Chain = Op.getOperand(0);
3184   SDValue Table = Op.getOperand(1);
3185   SDValue Index = Op.getOperand(2);
3186   DebugLoc dl = Op.getDebugLoc();
3187
3188   EVT PTy = getPointerTy();
3189   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3190   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3191   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3192   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3193   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3194   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3195   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3196   if (Subtarget->isThumb2()) {
3197     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3198     // which does another jump to the destination. This also makes it easier
3199     // to translate it to TBB / TBH later.
3200     // FIXME: This might not work if the function is extremely large.
3201     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3202                        Addr, Op.getOperand(2), JTI, UId);
3203   }
3204   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3205     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3206                        MachinePointerInfo::getJumpTable(),
3207                        false, false, false, 0);
3208     Chain = Addr.getValue(1);
3209     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3210     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3211   } else {
3212     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3213                        MachinePointerInfo::getJumpTable(),
3214                        false, false, false, 0);
3215     Chain = Addr.getValue(1);
3216     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3217   }
3218 }
3219
3220 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3221   EVT VT = Op.getValueType();
3222   DebugLoc dl = Op.getDebugLoc();
3223
3224   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3225     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3226       return Op;
3227     return DAG.UnrollVectorOp(Op.getNode());
3228   }
3229
3230   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3231          "Invalid type for custom lowering!");
3232   if (VT != MVT::v4i16)
3233     return DAG.UnrollVectorOp(Op.getNode());
3234
3235   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3236   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3237 }
3238
3239 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3240   EVT VT = Op.getValueType();
3241   if (VT.isVector())
3242     return LowerVectorFP_TO_INT(Op, DAG);
3243
3244   DebugLoc dl = Op.getDebugLoc();
3245   unsigned Opc;
3246
3247   switch (Op.getOpcode()) {
3248   default: llvm_unreachable("Invalid opcode!");
3249   case ISD::FP_TO_SINT:
3250     Opc = ARMISD::FTOSI;
3251     break;
3252   case ISD::FP_TO_UINT:
3253     Opc = ARMISD::FTOUI;
3254     break;
3255   }
3256   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3257   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3258 }
3259
3260 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3261   EVT VT = Op.getValueType();
3262   DebugLoc dl = Op.getDebugLoc();
3263
3264   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3265     if (VT.getVectorElementType() == MVT::f32)
3266       return Op;
3267     return DAG.UnrollVectorOp(Op.getNode());
3268   }
3269
3270   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3271          "Invalid type for custom lowering!");
3272   if (VT != MVT::v4f32)
3273     return DAG.UnrollVectorOp(Op.getNode());
3274
3275   unsigned CastOpc;
3276   unsigned Opc;
3277   switch (Op.getOpcode()) {
3278   default: llvm_unreachable("Invalid opcode!");
3279   case ISD::SINT_TO_FP:
3280     CastOpc = ISD::SIGN_EXTEND;
3281     Opc = ISD::SINT_TO_FP;
3282     break;
3283   case ISD::UINT_TO_FP:
3284     CastOpc = ISD::ZERO_EXTEND;
3285     Opc = ISD::UINT_TO_FP;
3286     break;
3287   }
3288
3289   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3290   return DAG.getNode(Opc, dl, VT, Op);
3291 }
3292
3293 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3294   EVT VT = Op.getValueType();
3295   if (VT.isVector())
3296     return LowerVectorINT_TO_FP(Op, DAG);
3297
3298   DebugLoc dl = Op.getDebugLoc();
3299   unsigned Opc;
3300
3301   switch (Op.getOpcode()) {
3302   default: llvm_unreachable("Invalid opcode!");
3303   case ISD::SINT_TO_FP:
3304     Opc = ARMISD::SITOF;
3305     break;
3306   case ISD::UINT_TO_FP:
3307     Opc = ARMISD::UITOF;
3308     break;
3309   }
3310
3311   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3312   return DAG.getNode(Opc, dl, VT, Op);
3313 }
3314
3315 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3316   // Implement fcopysign with a fabs and a conditional fneg.
3317   SDValue Tmp0 = Op.getOperand(0);
3318   SDValue Tmp1 = Op.getOperand(1);
3319   DebugLoc dl = Op.getDebugLoc();
3320   EVT VT = Op.getValueType();
3321   EVT SrcVT = Tmp1.getValueType();
3322   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3323     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3324   bool UseNEON = !InGPR && Subtarget->hasNEON();
3325
3326   if (UseNEON) {
3327     // Use VBSL to copy the sign bit.
3328     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3329     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3330                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3331     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3332     if (VT == MVT::f64)
3333       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3334                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3335                          DAG.getConstant(32, MVT::i32));
3336     else /*if (VT == MVT::f32)*/
3337       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3338     if (SrcVT == MVT::f32) {
3339       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3340       if (VT == MVT::f64)
3341         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3342                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3343                            DAG.getConstant(32, MVT::i32));
3344     } else if (VT == MVT::f32)
3345       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3346                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3347                          DAG.getConstant(32, MVT::i32));
3348     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3349     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3350
3351     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3352                                             MVT::i32);
3353     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3354     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3355                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3356
3357     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3358                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3359                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3360     if (VT == MVT::f32) {
3361       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3362       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3363                         DAG.getConstant(0, MVT::i32));
3364     } else {
3365       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3366     }
3367
3368     return Res;
3369   }
3370
3371   // Bitcast operand 1 to i32.
3372   if (SrcVT == MVT::f64)
3373     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3374                        &Tmp1, 1).getValue(1);
3375   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3376
3377   // Or in the signbit with integer operations.
3378   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3379   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3380   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3381   if (VT == MVT::f32) {
3382     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3383                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3384     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3385                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3386   }
3387
3388   // f64: Or the high part with signbit and then combine two parts.
3389   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3390                      &Tmp0, 1);
3391   SDValue Lo = Tmp0.getValue(0);
3392   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3393   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3394   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3395 }
3396
3397 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3398   MachineFunction &MF = DAG.getMachineFunction();
3399   MachineFrameInfo *MFI = MF.getFrameInfo();
3400   MFI->setReturnAddressIsTaken(true);
3401
3402   EVT VT = Op.getValueType();
3403   DebugLoc dl = Op.getDebugLoc();
3404   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3405   if (Depth) {
3406     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3407     SDValue Offset = DAG.getConstant(4, MVT::i32);
3408     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3409                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3410                        MachinePointerInfo(), false, false, false, 0);
3411   }
3412
3413   // Return LR, which contains the return address. Mark it an implicit live-in.
3414   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3415   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3416 }
3417
3418 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3419   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3420   MFI->setFrameAddressIsTaken(true);
3421
3422   EVT VT = Op.getValueType();
3423   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3424   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3425   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3426     ? ARM::R7 : ARM::R11;
3427   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3428   while (Depth--)
3429     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3430                             MachinePointerInfo(),
3431                             false, false, false, 0);
3432   return FrameAddr;
3433 }
3434
3435 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3436 /// and size(DestVec) > 128-bits.
3437 /// This is achieved by doing the one extension from the SrcVec, splitting the
3438 /// result, extending these parts, and then concatenating these into the
3439 /// destination.
3440 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3441   SDValue Op = N->getOperand(0);
3442   EVT SrcVT = Op.getValueType();
3443   EVT DestVT = N->getValueType(0);
3444
3445   assert(DestVT.getSizeInBits() > 128 &&
3446          "Custom sext/zext expansion needs >128-bit vector.");
3447   // If this is a normal length extension, use the default expansion.
3448   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3449       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3450     return SDValue();
3451
3452   DebugLoc dl = N->getDebugLoc();
3453   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3454   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3455   unsigned NumElts = SrcVT.getVectorNumElements();
3456   LLVMContext &Ctx = *DAG.getContext();
3457   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3458
3459   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3460                                NumElts);
3461   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3462                                  NumElts/2);
3463   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3464                                NumElts/2);
3465
3466   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3467   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3468                         DAG.getIntPtrConstant(0));
3469   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3470                         DAG.getIntPtrConstant(NumElts/2));
3471   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3472   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3473   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3474 }
3475
3476 /// ExpandBITCAST - If the target supports VFP, this function is called to
3477 /// expand a bit convert where either the source or destination type is i64 to
3478 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3479 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3480 /// vectors), since the legalizer won't know what to do with that.
3481 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3483   DebugLoc dl = N->getDebugLoc();
3484   SDValue Op = N->getOperand(0);
3485
3486   // This function is only supposed to be called for i64 types, either as the
3487   // source or destination of the bit convert.
3488   EVT SrcVT = Op.getValueType();
3489   EVT DstVT = N->getValueType(0);
3490   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3491          "ExpandBITCAST called for non-i64 type");
3492
3493   // Turn i64->f64 into VMOVDRR.
3494   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3495     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3496                              DAG.getConstant(0, MVT::i32));
3497     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3498                              DAG.getConstant(1, MVT::i32));
3499     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3500                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3501   }
3502
3503   // Turn f64->i64 into VMOVRRD.
3504   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3505     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3506                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3507     // Merge the pieces into a single i64 value.
3508     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3509   }
3510
3511   return SDValue();
3512 }
3513
3514 /// getZeroVector - Returns a vector of specified type with all zero elements.
3515 /// Zero vectors are used to represent vector negation and in those cases
3516 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3517 /// not support i64 elements, so sometimes the zero vectors will need to be
3518 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3519 /// zero vector.
3520 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3521   assert(VT.isVector() && "Expected a vector type");
3522   // The canonical modified immediate encoding of a zero vector is....0!
3523   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3524   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3525   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3526   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3527 }
3528
3529 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3530 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3531 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3532                                                 SelectionDAG &DAG) const {
3533   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3534   EVT VT = Op.getValueType();
3535   unsigned VTBits = VT.getSizeInBits();
3536   DebugLoc dl = Op.getDebugLoc();
3537   SDValue ShOpLo = Op.getOperand(0);
3538   SDValue ShOpHi = Op.getOperand(1);
3539   SDValue ShAmt  = Op.getOperand(2);
3540   SDValue ARMcc;
3541   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3542
3543   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3544
3545   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3546                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3547   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3548   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3549                                    DAG.getConstant(VTBits, MVT::i32));
3550   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3551   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3552   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3553
3554   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3555   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3556                           ARMcc, DAG, dl);
3557   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3558   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3559                            CCR, Cmp);
3560
3561   SDValue Ops[2] = { Lo, Hi };
3562   return DAG.getMergeValues(Ops, 2, dl);
3563 }
3564
3565 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3566 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3567 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3568                                                SelectionDAG &DAG) const {
3569   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3570   EVT VT = Op.getValueType();
3571   unsigned VTBits = VT.getSizeInBits();
3572   DebugLoc dl = Op.getDebugLoc();
3573   SDValue ShOpLo = Op.getOperand(0);
3574   SDValue ShOpHi = Op.getOperand(1);
3575   SDValue ShAmt  = Op.getOperand(2);
3576   SDValue ARMcc;
3577
3578   assert(Op.getOpcode() == ISD::SHL_PARTS);
3579   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3580                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3581   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3582   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3583                                    DAG.getConstant(VTBits, MVT::i32));
3584   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3585   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3586
3587   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3588   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3589   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3590                           ARMcc, DAG, dl);
3591   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3592   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3593                            CCR, Cmp);
3594
3595   SDValue Ops[2] = { Lo, Hi };
3596   return DAG.getMergeValues(Ops, 2, dl);
3597 }
3598
3599 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3600                                             SelectionDAG &DAG) const {
3601   // The rounding mode is in bits 23:22 of the FPSCR.
3602   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3603   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3604   // so that the shift + and get folded into a bitfield extract.
3605   DebugLoc dl = Op.getDebugLoc();
3606   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3607                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3608                                               MVT::i32));
3609   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3610                                   DAG.getConstant(1U << 22, MVT::i32));
3611   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3612                               DAG.getConstant(22, MVT::i32));
3613   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3614                      DAG.getConstant(3, MVT::i32));
3615 }
3616
3617 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3618                          const ARMSubtarget *ST) {
3619   EVT VT = N->getValueType(0);
3620   DebugLoc dl = N->getDebugLoc();
3621
3622   if (!ST->hasV6T2Ops())
3623     return SDValue();
3624
3625   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3626   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3627 }
3628
3629 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3630 /// for each 16-bit element from operand, repeated.  The basic idea is to
3631 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3632 ///
3633 /// Trace for v4i16:
3634 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3635 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3636 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3637 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3638 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3639 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3640 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3641 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3642 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3643   EVT VT = N->getValueType(0);
3644   DebugLoc DL = N->getDebugLoc();
3645
3646   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3647   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3648   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3649   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3650   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3651   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3652 }
3653
3654 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3655 /// bit-count for each 16-bit element from the operand.  We need slightly
3656 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3657 /// 64/128-bit registers.
3658 ///
3659 /// Trace for v4i16:
3660 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3661 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3662 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3663 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3664 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3665   EVT VT = N->getValueType(0);
3666   DebugLoc DL = N->getDebugLoc();
3667
3668   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3669   if (VT.is64BitVector()) {
3670     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3671     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3672                        DAG.getIntPtrConstant(0));
3673   } else {
3674     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3675                                     BitCounts, DAG.getIntPtrConstant(0));
3676     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3677   }
3678 }
3679
3680 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3681 /// bit-count for each 32-bit element from the operand.  The idea here is
3682 /// to split the vector into 16-bit elements, leverage the 16-bit count
3683 /// routine, and then combine the results.
3684 ///
3685 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3686 /// input    = [v0    v1    ] (vi: 32-bit elements)
3687 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3688 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3689 /// vrev: N0 = [k1 k0 k3 k2 ]
3690 ///            [k0 k1 k2 k3 ]
3691 ///       N1 =+[k1 k0 k3 k2 ]
3692 ///            [k0 k2 k1 k3 ]
3693 ///       N2 =+[k1 k3 k0 k2 ]
3694 ///            [k0    k2    k1    k3    ]
3695 /// Extended =+[k1    k3    k0    k2    ]
3696 ///            [k0    k2    ]
3697 /// Extracted=+[k1    k3    ]
3698 ///
3699 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3700   EVT VT = N->getValueType(0);
3701   DebugLoc DL = N->getDebugLoc();
3702
3703   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3704
3705   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3706   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3707   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3708   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3709   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3710
3711   if (VT.is64BitVector()) {
3712     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3713     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3714                        DAG.getIntPtrConstant(0));
3715   } else {
3716     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3717                                     DAG.getIntPtrConstant(0));
3718     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3719   }
3720 }
3721
3722 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3723                           const ARMSubtarget *ST) {
3724   EVT VT = N->getValueType(0);
3725
3726   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3727   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3728           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3729          "Unexpected type for custom ctpop lowering");
3730
3731   if (VT.getVectorElementType() == MVT::i32)
3732     return lowerCTPOP32BitElements(N, DAG);
3733   else
3734     return lowerCTPOP16BitElements(N, DAG);
3735 }
3736
3737 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3738                           const ARMSubtarget *ST) {
3739   EVT VT = N->getValueType(0);
3740   DebugLoc dl = N->getDebugLoc();
3741
3742   if (!VT.isVector())
3743     return SDValue();
3744
3745   // Lower vector shifts on NEON to use VSHL.
3746   assert(ST->hasNEON() && "unexpected vector shift");
3747
3748   // Left shifts translate directly to the vshiftu intrinsic.
3749   if (N->getOpcode() == ISD::SHL)
3750     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3751                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3752                        N->getOperand(0), N->getOperand(1));
3753
3754   assert((N->getOpcode() == ISD::SRA ||
3755           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3756
3757   // NEON uses the same intrinsics for both left and right shifts.  For
3758   // right shifts, the shift amounts are negative, so negate the vector of
3759   // shift amounts.
3760   EVT ShiftVT = N->getOperand(1).getValueType();
3761   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3762                                      getZeroVector(ShiftVT, DAG, dl),
3763                                      N->getOperand(1));
3764   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3765                              Intrinsic::arm_neon_vshifts :
3766                              Intrinsic::arm_neon_vshiftu);
3767   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3768                      DAG.getConstant(vshiftInt, MVT::i32),
3769                      N->getOperand(0), NegatedCount);
3770 }
3771
3772 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3773                                 const ARMSubtarget *ST) {
3774   EVT VT = N->getValueType(0);
3775   DebugLoc dl = N->getDebugLoc();
3776
3777   // We can get here for a node like i32 = ISD::SHL i32, i64
3778   if (VT != MVT::i64)
3779     return SDValue();
3780
3781   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3782          "Unknown shift to lower!");
3783
3784   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3785   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3786       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3787     return SDValue();
3788
3789   // If we are in thumb mode, we don't have RRX.
3790   if (ST->isThumb1Only()) return SDValue();
3791
3792   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3793   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3794                            DAG.getConstant(0, MVT::i32));
3795   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3796                            DAG.getConstant(1, MVT::i32));
3797
3798   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3799   // captures the result into a carry flag.
3800   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3801   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3802
3803   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3804   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3805
3806   // Merge the pieces into a single i64 value.
3807  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3808 }
3809
3810 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3811   SDValue TmpOp0, TmpOp1;
3812   bool Invert = false;
3813   bool Swap = false;
3814   unsigned Opc = 0;
3815
3816   SDValue Op0 = Op.getOperand(0);
3817   SDValue Op1 = Op.getOperand(1);
3818   SDValue CC = Op.getOperand(2);
3819   EVT VT = Op.getValueType();
3820   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3821   DebugLoc dl = Op.getDebugLoc();
3822
3823   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3824     switch (SetCCOpcode) {
3825     default: llvm_unreachable("Illegal FP comparison");
3826     case ISD::SETUNE:
3827     case ISD::SETNE:  Invert = true; // Fallthrough
3828     case ISD::SETOEQ:
3829     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3830     case ISD::SETOLT:
3831     case ISD::SETLT: Swap = true; // Fallthrough
3832     case ISD::SETOGT:
3833     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3834     case ISD::SETOLE:
3835     case ISD::SETLE:  Swap = true; // Fallthrough
3836     case ISD::SETOGE:
3837     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3838     case ISD::SETUGE: Swap = true; // Fallthrough
3839     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3840     case ISD::SETUGT: Swap = true; // Fallthrough
3841     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3842     case ISD::SETUEQ: Invert = true; // Fallthrough
3843     case ISD::SETONE:
3844       // Expand this to (OLT | OGT).
3845       TmpOp0 = Op0;
3846       TmpOp1 = Op1;
3847       Opc = ISD::OR;
3848       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3849       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3850       break;
3851     case ISD::SETUO: Invert = true; // Fallthrough
3852     case ISD::SETO:
3853       // Expand this to (OLT | OGE).
3854       TmpOp0 = Op0;
3855       TmpOp1 = Op1;
3856       Opc = ISD::OR;
3857       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3858       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3859       break;
3860     }
3861   } else {
3862     // Integer comparisons.
3863     switch (SetCCOpcode) {
3864     default: llvm_unreachable("Illegal integer comparison");
3865     case ISD::SETNE:  Invert = true;
3866     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3867     case ISD::SETLT:  Swap = true;
3868     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3869     case ISD::SETLE:  Swap = true;
3870     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3871     case ISD::SETULT: Swap = true;
3872     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3873     case ISD::SETULE: Swap = true;
3874     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3875     }
3876
3877     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3878     if (Opc == ARMISD::VCEQ) {
3879
3880       SDValue AndOp;
3881       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3882         AndOp = Op0;
3883       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3884         AndOp = Op1;
3885
3886       // Ignore bitconvert.
3887       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3888         AndOp = AndOp.getOperand(0);
3889
3890       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3891         Opc = ARMISD::VTST;
3892         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3893         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3894         Invert = !Invert;
3895       }
3896     }
3897   }
3898
3899   if (Swap)
3900     std::swap(Op0, Op1);
3901
3902   // If one of the operands is a constant vector zero, attempt to fold the
3903   // comparison to a specialized compare-against-zero form.
3904   SDValue SingleOp;
3905   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3906     SingleOp = Op0;
3907   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3908     if (Opc == ARMISD::VCGE)
3909       Opc = ARMISD::VCLEZ;
3910     else if (Opc == ARMISD::VCGT)
3911       Opc = ARMISD::VCLTZ;
3912     SingleOp = Op1;
3913   }
3914
3915   SDValue Result;
3916   if (SingleOp.getNode()) {
3917     switch (Opc) {
3918     case ARMISD::VCEQ:
3919       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3920     case ARMISD::VCGE:
3921       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3922     case ARMISD::VCLEZ:
3923       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3924     case ARMISD::VCGT:
3925       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3926     case ARMISD::VCLTZ:
3927       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3928     default:
3929       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3930     }
3931   } else {
3932      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3933   }
3934
3935   if (Invert)
3936     Result = DAG.getNOT(dl, Result, VT);
3937
3938   return Result;
3939 }
3940
3941 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3942 /// valid vector constant for a NEON instruction with a "modified immediate"
3943 /// operand (e.g., VMOV).  If so, return the encoded value.
3944 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3945                                  unsigned SplatBitSize, SelectionDAG &DAG,
3946                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3947   unsigned OpCmode, Imm;
3948
3949   // SplatBitSize is set to the smallest size that splats the vector, so a
3950   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3951   // immediate instructions others than VMOV do not support the 8-bit encoding
3952   // of a zero vector, and the default encoding of zero is supposed to be the
3953   // 32-bit version.
3954   if (SplatBits == 0)
3955     SplatBitSize = 32;
3956
3957   switch (SplatBitSize) {
3958   case 8:
3959     if (type != VMOVModImm)
3960       return SDValue();
3961     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3962     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3963     OpCmode = 0xe;
3964     Imm = SplatBits;
3965     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3966     break;
3967
3968   case 16:
3969     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3970     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3971     if ((SplatBits & ~0xff) == 0) {
3972       // Value = 0x00nn: Op=x, Cmode=100x.
3973       OpCmode = 0x8;
3974       Imm = SplatBits;
3975       break;
3976     }
3977     if ((SplatBits & ~0xff00) == 0) {
3978       // Value = 0xnn00: Op=x, Cmode=101x.
3979       OpCmode = 0xa;
3980       Imm = SplatBits >> 8;
3981       break;
3982     }
3983     return SDValue();
3984
3985   case 32:
3986     // NEON's 32-bit VMOV supports splat values where:
3987     // * only one byte is nonzero, or
3988     // * the least significant byte is 0xff and the second byte is nonzero, or
3989     // * the least significant 2 bytes are 0xff and the third is nonzero.
3990     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3991     if ((SplatBits & ~0xff) == 0) {
3992       // Value = 0x000000nn: Op=x, Cmode=000x.
3993       OpCmode = 0;
3994       Imm = SplatBits;
3995       break;
3996     }
3997     if ((SplatBits & ~0xff00) == 0) {
3998       // Value = 0x0000nn00: Op=x, Cmode=001x.
3999       OpCmode = 0x2;
4000       Imm = SplatBits >> 8;
4001       break;
4002     }
4003     if ((SplatBits & ~0xff0000) == 0) {
4004       // Value = 0x00nn0000: Op=x, Cmode=010x.
4005       OpCmode = 0x4;
4006       Imm = SplatBits >> 16;
4007       break;
4008     }
4009     if ((SplatBits & ~0xff000000) == 0) {
4010       // Value = 0xnn000000: Op=x, Cmode=011x.
4011       OpCmode = 0x6;
4012       Imm = SplatBits >> 24;
4013       break;
4014     }
4015
4016     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4017     if (type == OtherModImm) return SDValue();
4018
4019     if ((SplatBits & ~0xffff) == 0 &&
4020         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4021       // Value = 0x0000nnff: Op=x, Cmode=1100.
4022       OpCmode = 0xc;
4023       Imm = SplatBits >> 8;
4024       SplatBits |= 0xff;
4025       break;
4026     }
4027
4028     if ((SplatBits & ~0xffffff) == 0 &&
4029         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4030       // Value = 0x00nnffff: Op=x, Cmode=1101.
4031       OpCmode = 0xd;
4032       Imm = SplatBits >> 16;
4033       SplatBits |= 0xffff;
4034       break;
4035     }
4036
4037     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4038     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4039     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4040     // and fall through here to test for a valid 64-bit splat.  But, then the
4041     // caller would also need to check and handle the change in size.
4042     return SDValue();
4043
4044   case 64: {
4045     if (type != VMOVModImm)
4046       return SDValue();
4047     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4048     uint64_t BitMask = 0xff;
4049     uint64_t Val = 0;
4050     unsigned ImmMask = 1;
4051     Imm = 0;
4052     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4053       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4054         Val |= BitMask;
4055         Imm |= ImmMask;
4056       } else if ((SplatBits & BitMask) != 0) {
4057         return SDValue();
4058       }
4059       BitMask <<= 8;
4060       ImmMask <<= 1;
4061     }
4062     // Op=1, Cmode=1110.
4063     OpCmode = 0x1e;
4064     SplatBits = Val;
4065     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4066     break;
4067   }
4068
4069   default:
4070     llvm_unreachable("unexpected size for isNEONModifiedImm");
4071   }
4072
4073   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4074   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4075 }
4076
4077 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4078                                            const ARMSubtarget *ST) const {
4079   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4080     return SDValue();
4081
4082   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4083   assert(Op.getValueType() == MVT::f32 &&
4084          "ConstantFP custom lowering should only occur for f32.");
4085
4086   // Try splatting with a VMOV.f32...
4087   APFloat FPVal = CFP->getValueAPF();
4088   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4089   if (ImmVal != -1) {
4090     DebugLoc DL = Op.getDebugLoc();
4091     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4092     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4093                                       NewVal);
4094     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4095                        DAG.getConstant(0, MVT::i32));
4096   }
4097
4098   // If that fails, try a VMOV.i32
4099   EVT VMovVT;
4100   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4101   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4102                                      VMOVModImm);
4103   if (NewVal != SDValue()) {
4104     DebugLoc DL = Op.getDebugLoc();
4105     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4106                                       NewVal);
4107     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4108                                        VecConstant);
4109     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4110                        DAG.getConstant(0, MVT::i32));
4111   }
4112
4113   // Finally, try a VMVN.i32
4114   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4115                              VMVNModImm);
4116   if (NewVal != SDValue()) {
4117     DebugLoc DL = Op.getDebugLoc();
4118     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4119     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4120                                        VecConstant);
4121     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4122                        DAG.getConstant(0, MVT::i32));
4123   }
4124
4125   return SDValue();
4126 }
4127
4128 // check if an VEXT instruction can handle the shuffle mask when the
4129 // vector sources of the shuffle are the same.
4130 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4131   unsigned NumElts = VT.getVectorNumElements();
4132
4133   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4134   if (M[0] < 0)
4135     return false;
4136
4137   Imm = M[0];
4138
4139   // If this is a VEXT shuffle, the immediate value is the index of the first
4140   // element.  The other shuffle indices must be the successive elements after
4141   // the first one.
4142   unsigned ExpectedElt = Imm;
4143   for (unsigned i = 1; i < NumElts; ++i) {
4144     // Increment the expected index.  If it wraps around, just follow it
4145     // back to index zero and keep going.
4146     ++ExpectedElt;
4147     if (ExpectedElt == NumElts)
4148       ExpectedElt = 0;
4149
4150     if (M[i] < 0) continue; // ignore UNDEF indices
4151     if (ExpectedElt != static_cast<unsigned>(M[i]))
4152       return false;
4153   }
4154
4155   return true;
4156 }
4157
4158
4159 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4160                        bool &ReverseVEXT, unsigned &Imm) {
4161   unsigned NumElts = VT.getVectorNumElements();
4162   ReverseVEXT = false;
4163
4164   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4165   if (M[0] < 0)
4166     return false;
4167
4168   Imm = M[0];
4169
4170   // If this is a VEXT shuffle, the immediate value is the index of the first
4171   // element.  The other shuffle indices must be the successive elements after
4172   // the first one.
4173   unsigned ExpectedElt = Imm;
4174   for (unsigned i = 1; i < NumElts; ++i) {
4175     // Increment the expected index.  If it wraps around, it may still be
4176     // a VEXT but the source vectors must be swapped.
4177     ExpectedElt += 1;
4178     if (ExpectedElt == NumElts * 2) {
4179       ExpectedElt = 0;
4180       ReverseVEXT = true;
4181     }
4182
4183     if (M[i] < 0) continue; // ignore UNDEF indices
4184     if (ExpectedElt != static_cast<unsigned>(M[i]))
4185       return false;
4186   }
4187
4188   // Adjust the index value if the source operands will be swapped.
4189   if (ReverseVEXT)
4190     Imm -= NumElts;
4191
4192   return true;
4193 }
4194
4195 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4196 /// instruction with the specified blocksize.  (The order of the elements
4197 /// within each block of the vector is reversed.)
4198 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4199   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4200          "Only possible block sizes for VREV are: 16, 32, 64");
4201
4202   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4203   if (EltSz == 64)
4204     return false;
4205
4206   unsigned NumElts = VT.getVectorNumElements();
4207   unsigned BlockElts = M[0] + 1;
4208   // If the first shuffle index is UNDEF, be optimistic.
4209   if (M[0] < 0)
4210     BlockElts = BlockSize / EltSz;
4211
4212   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4213     return false;
4214
4215   for (unsigned i = 0; i < NumElts; ++i) {
4216     if (M[i] < 0) continue; // ignore UNDEF indices
4217     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4218       return false;
4219   }
4220
4221   return true;
4222 }
4223
4224 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4225   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4226   // range, then 0 is placed into the resulting vector. So pretty much any mask
4227   // of 8 elements can work here.
4228   return VT == MVT::v8i8 && M.size() == 8;
4229 }
4230
4231 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4232   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4233   if (EltSz == 64)
4234     return false;
4235
4236   unsigned NumElts = VT.getVectorNumElements();
4237   WhichResult = (M[0] == 0 ? 0 : 1);
4238   for (unsigned i = 0; i < NumElts; i += 2) {
4239     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4240         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4241       return false;
4242   }
4243   return true;
4244 }
4245
4246 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4247 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4248 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4249 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4250   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4251   if (EltSz == 64)
4252     return false;
4253
4254   unsigned NumElts = VT.getVectorNumElements();
4255   WhichResult = (M[0] == 0 ? 0 : 1);
4256   for (unsigned i = 0; i < NumElts; i += 2) {
4257     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4258         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4259       return false;
4260   }
4261   return true;
4262 }
4263
4264 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4265   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4266   if (EltSz == 64)
4267     return false;
4268
4269   unsigned NumElts = VT.getVectorNumElements();
4270   WhichResult = (M[0] == 0 ? 0 : 1);
4271   for (unsigned i = 0; i != NumElts; ++i) {
4272     if (M[i] < 0) continue; // ignore UNDEF indices
4273     if ((unsigned) M[i] != 2 * i + WhichResult)
4274       return false;
4275   }
4276
4277   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4278   if (VT.is64BitVector() && EltSz == 32)
4279     return false;
4280
4281   return true;
4282 }
4283
4284 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4285 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4286 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4287 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4288   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4289   if (EltSz == 64)
4290     return false;
4291
4292   unsigned Half = VT.getVectorNumElements() / 2;
4293   WhichResult = (M[0] == 0 ? 0 : 1);
4294   for (unsigned j = 0; j != 2; ++j) {
4295     unsigned Idx = WhichResult;
4296     for (unsigned i = 0; i != Half; ++i) {
4297       int MIdx = M[i + j * Half];
4298       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4299         return false;
4300       Idx += 2;
4301     }
4302   }
4303
4304   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4305   if (VT.is64BitVector() && EltSz == 32)
4306     return false;
4307
4308   return true;
4309 }
4310
4311 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4312   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4313   if (EltSz == 64)
4314     return false;
4315
4316   unsigned NumElts = VT.getVectorNumElements();
4317   WhichResult = (M[0] == 0 ? 0 : 1);
4318   unsigned Idx = WhichResult * NumElts / 2;
4319   for (unsigned i = 0; i != NumElts; i += 2) {
4320     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4321         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4322       return false;
4323     Idx += 1;
4324   }
4325
4326   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4327   if (VT.is64BitVector() && EltSz == 32)
4328     return false;
4329
4330   return true;
4331 }
4332
4333 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4334 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4335 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4336 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4337   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4338   if (EltSz == 64)
4339     return false;
4340
4341   unsigned NumElts = VT.getVectorNumElements();
4342   WhichResult = (M[0] == 0 ? 0 : 1);
4343   unsigned Idx = WhichResult * NumElts / 2;
4344   for (unsigned i = 0; i != NumElts; i += 2) {
4345     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4346         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4347       return false;
4348     Idx += 1;
4349   }
4350
4351   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4352   if (VT.is64BitVector() && EltSz == 32)
4353     return false;
4354
4355   return true;
4356 }
4357
4358 /// \return true if this is a reverse operation on an vector.
4359 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4360   unsigned NumElts = VT.getVectorNumElements();
4361   // Make sure the mask has the right size.
4362   if (NumElts != M.size())
4363       return false;
4364
4365   // Look for <15, ..., 3, -1, 1, 0>.
4366   for (unsigned i = 0; i != NumElts; ++i)
4367     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4368       return false;
4369
4370   return true;
4371 }
4372
4373 // If N is an integer constant that can be moved into a register in one
4374 // instruction, return an SDValue of such a constant (will become a MOV
4375 // instruction).  Otherwise return null.
4376 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4377                                      const ARMSubtarget *ST, DebugLoc dl) {
4378   uint64_t Val;
4379   if (!isa<ConstantSDNode>(N))
4380     return SDValue();
4381   Val = cast<ConstantSDNode>(N)->getZExtValue();
4382
4383   if (ST->isThumb1Only()) {
4384     if (Val <= 255 || ~Val <= 255)
4385       return DAG.getConstant(Val, MVT::i32);
4386   } else {
4387     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4388       return DAG.getConstant(Val, MVT::i32);
4389   }
4390   return SDValue();
4391 }
4392
4393 // If this is a case we can't handle, return null and let the default
4394 // expansion code take care of it.
4395 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4396                                              const ARMSubtarget *ST) const {
4397   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4398   DebugLoc dl = Op.getDebugLoc();
4399   EVT VT = Op.getValueType();
4400
4401   APInt SplatBits, SplatUndef;
4402   unsigned SplatBitSize;
4403   bool HasAnyUndefs;
4404   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4405     if (SplatBitSize <= 64) {
4406       // Check if an immediate VMOV works.
4407       EVT VmovVT;
4408       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4409                                       SplatUndef.getZExtValue(), SplatBitSize,
4410                                       DAG, VmovVT, VT.is128BitVector(),
4411                                       VMOVModImm);
4412       if (Val.getNode()) {
4413         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4414         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4415       }
4416
4417       // Try an immediate VMVN.
4418       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4419       Val = isNEONModifiedImm(NegatedImm,
4420                                       SplatUndef.getZExtValue(), SplatBitSize,
4421                                       DAG, VmovVT, VT.is128BitVector(),
4422                                       VMVNModImm);
4423       if (Val.getNode()) {
4424         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4425         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4426       }
4427
4428       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4429       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4430         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4431         if (ImmVal != -1) {
4432           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4433           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4434         }
4435       }
4436     }
4437   }
4438
4439   // Scan through the operands to see if only one value is used.
4440   //
4441   // As an optimisation, even if more than one value is used it may be more
4442   // profitable to splat with one value then change some lanes.
4443   //
4444   // Heuristically we decide to do this if the vector has a "dominant" value,
4445   // defined as splatted to more than half of the lanes.
4446   unsigned NumElts = VT.getVectorNumElements();
4447   bool isOnlyLowElement = true;
4448   bool usesOnlyOneValue = true;
4449   bool hasDominantValue = false;
4450   bool isConstant = true;
4451
4452   // Map of the number of times a particular SDValue appears in the
4453   // element list.
4454   DenseMap<SDValue, unsigned> ValueCounts;
4455   SDValue Value;
4456   for (unsigned i = 0; i < NumElts; ++i) {
4457     SDValue V = Op.getOperand(i);
4458     if (V.getOpcode() == ISD::UNDEF)
4459       continue;
4460     if (i > 0)
4461       isOnlyLowElement = false;
4462     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4463       isConstant = false;
4464
4465     ValueCounts.insert(std::make_pair(V, 0));
4466     unsigned &Count = ValueCounts[V];
4467
4468     // Is this value dominant? (takes up more than half of the lanes)
4469     if (++Count > (NumElts / 2)) {
4470       hasDominantValue = true;
4471       Value = V;
4472     }
4473   }
4474   if (ValueCounts.size() != 1)
4475     usesOnlyOneValue = false;
4476   if (!Value.getNode() && ValueCounts.size() > 0)
4477     Value = ValueCounts.begin()->first;
4478
4479   if (ValueCounts.size() == 0)
4480     return DAG.getUNDEF(VT);
4481
4482   if (isOnlyLowElement)
4483     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4484
4485   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4486
4487   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4488   // i32 and try again.
4489   if (hasDominantValue && EltSize <= 32) {
4490     if (!isConstant) {
4491       SDValue N;
4492
4493       // If we are VDUPing a value that comes directly from a vector, that will
4494       // cause an unnecessary move to and from a GPR, where instead we could
4495       // just use VDUPLANE. We can only do this if the lane being extracted
4496       // is at a constant index, as the VDUP from lane instructions only have
4497       // constant-index forms.
4498       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4499           isa<ConstantSDNode>(Value->getOperand(1))) {
4500         // We need to create a new undef vector to use for the VDUPLANE if the
4501         // size of the vector from which we get the value is different than the
4502         // size of the vector that we need to create. We will insert the element
4503         // such that the register coalescer will remove unnecessary copies.
4504         if (VT != Value->getOperand(0).getValueType()) {
4505           ConstantSDNode *constIndex;
4506           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4507           assert(constIndex && "The index is not a constant!");
4508           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4509                              VT.getVectorNumElements();
4510           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4511                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4512                         Value, DAG.getConstant(index, MVT::i32)),
4513                            DAG.getConstant(index, MVT::i32));
4514         } else
4515           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4516                         Value->getOperand(0), Value->getOperand(1));
4517       } else
4518         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4519
4520       if (!usesOnlyOneValue) {
4521         // The dominant value was splatted as 'N', but we now have to insert
4522         // all differing elements.
4523         for (unsigned I = 0; I < NumElts; ++I) {
4524           if (Op.getOperand(I) == Value)
4525             continue;
4526           SmallVector<SDValue, 3> Ops;
4527           Ops.push_back(N);
4528           Ops.push_back(Op.getOperand(I));
4529           Ops.push_back(DAG.getConstant(I, MVT::i32));
4530           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4531         }
4532       }
4533       return N;
4534     }
4535     if (VT.getVectorElementType().isFloatingPoint()) {
4536       SmallVector<SDValue, 8> Ops;
4537       for (unsigned i = 0; i < NumElts; ++i)
4538         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4539                                   Op.getOperand(i)));
4540       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4541       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4542       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4543       if (Val.getNode())
4544         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4545     }
4546     if (usesOnlyOneValue) {
4547       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4548       if (isConstant && Val.getNode())
4549         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4550     }
4551   }
4552
4553   // If all elements are constants and the case above didn't get hit, fall back
4554   // to the default expansion, which will generate a load from the constant
4555   // pool.
4556   if (isConstant)
4557     return SDValue();
4558
4559   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4560   if (NumElts >= 4) {
4561     SDValue shuffle = ReconstructShuffle(Op, DAG);
4562     if (shuffle != SDValue())
4563       return shuffle;
4564   }
4565
4566   // Vectors with 32- or 64-bit elements can be built by directly assigning
4567   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4568   // will be legalized.
4569   if (EltSize >= 32) {
4570     // Do the expansion with floating-point types, since that is what the VFP
4571     // registers are defined to use, and since i64 is not legal.
4572     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4573     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4574     SmallVector<SDValue, 8> Ops;
4575     for (unsigned i = 0; i < NumElts; ++i)
4576       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4577     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4578     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4579   }
4580
4581   return SDValue();
4582 }
4583
4584 // Gather data to see if the operation can be modelled as a
4585 // shuffle in combination with VEXTs.
4586 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4587                                               SelectionDAG &DAG) const {
4588   DebugLoc dl = Op.getDebugLoc();
4589   EVT VT = Op.getValueType();
4590   unsigned NumElts = VT.getVectorNumElements();
4591
4592   SmallVector<SDValue, 2> SourceVecs;
4593   SmallVector<unsigned, 2> MinElts;
4594   SmallVector<unsigned, 2> MaxElts;
4595
4596   for (unsigned i = 0; i < NumElts; ++i) {
4597     SDValue V = Op.getOperand(i);
4598     if (V.getOpcode() == ISD::UNDEF)
4599       continue;
4600     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4601       // A shuffle can only come from building a vector from various
4602       // elements of other vectors.
4603       return SDValue();
4604     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4605                VT.getVectorElementType()) {
4606       // This code doesn't know how to handle shuffles where the vector
4607       // element types do not match (this happens because type legalization
4608       // promotes the return type of EXTRACT_VECTOR_ELT).
4609       // FIXME: It might be appropriate to extend this code to handle
4610       // mismatched types.
4611       return SDValue();
4612     }
4613
4614     // Record this extraction against the appropriate vector if possible...
4615     SDValue SourceVec = V.getOperand(0);
4616     // If the element number isn't a constant, we can't effectively
4617     // analyze what's going on.
4618     if (!isa<ConstantSDNode>(V.getOperand(1)))
4619       return SDValue();
4620     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4621     bool FoundSource = false;
4622     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4623       if (SourceVecs[j] == SourceVec) {
4624         if (MinElts[j] > EltNo)
4625           MinElts[j] = EltNo;
4626         if (MaxElts[j] < EltNo)
4627           MaxElts[j] = EltNo;
4628         FoundSource = true;
4629         break;
4630       }
4631     }
4632
4633     // Or record a new source if not...
4634     if (!FoundSource) {
4635       SourceVecs.push_back(SourceVec);
4636       MinElts.push_back(EltNo);
4637       MaxElts.push_back(EltNo);
4638     }
4639   }
4640
4641   // Currently only do something sane when at most two source vectors
4642   // involved.
4643   if (SourceVecs.size() > 2)
4644     return SDValue();
4645
4646   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4647   int VEXTOffsets[2] = {0, 0};
4648
4649   // This loop extracts the usage patterns of the source vectors
4650   // and prepares appropriate SDValues for a shuffle if possible.
4651   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4652     if (SourceVecs[i].getValueType() == VT) {
4653       // No VEXT necessary
4654       ShuffleSrcs[i] = SourceVecs[i];
4655       VEXTOffsets[i] = 0;
4656       continue;
4657     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4658       // It probably isn't worth padding out a smaller vector just to
4659       // break it down again in a shuffle.
4660       return SDValue();
4661     }
4662
4663     // Since only 64-bit and 128-bit vectors are legal on ARM and
4664     // we've eliminated the other cases...
4665     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4666            "unexpected vector sizes in ReconstructShuffle");
4667
4668     if (MaxElts[i] - MinElts[i] >= NumElts) {
4669       // Span too large for a VEXT to cope
4670       return SDValue();
4671     }
4672
4673     if (MinElts[i] >= NumElts) {
4674       // The extraction can just take the second half
4675       VEXTOffsets[i] = NumElts;
4676       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4677                                    SourceVecs[i],
4678                                    DAG.getIntPtrConstant(NumElts));
4679     } else if (MaxElts[i] < NumElts) {
4680       // The extraction can just take the first half
4681       VEXTOffsets[i] = 0;
4682       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4683                                    SourceVecs[i],
4684                                    DAG.getIntPtrConstant(0));
4685     } else {
4686       // An actual VEXT is needed
4687       VEXTOffsets[i] = MinElts[i];
4688       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4689                                      SourceVecs[i],
4690                                      DAG.getIntPtrConstant(0));
4691       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4692                                      SourceVecs[i],
4693                                      DAG.getIntPtrConstant(NumElts));
4694       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4695                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4696     }
4697   }
4698
4699   SmallVector<int, 8> Mask;
4700
4701   for (unsigned i = 0; i < NumElts; ++i) {
4702     SDValue Entry = Op.getOperand(i);
4703     if (Entry.getOpcode() == ISD::UNDEF) {
4704       Mask.push_back(-1);
4705       continue;
4706     }
4707
4708     SDValue ExtractVec = Entry.getOperand(0);
4709     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4710                                           .getOperand(1))->getSExtValue();
4711     if (ExtractVec == SourceVecs[0]) {
4712       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4713     } else {
4714       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4715     }
4716   }
4717
4718   // Final check before we try to produce nonsense...
4719   if (isShuffleMaskLegal(Mask, VT))
4720     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4721                                 &Mask[0]);
4722
4723   return SDValue();
4724 }
4725
4726 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4727 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4728 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4729 /// are assumed to be legal.
4730 bool
4731 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4732                                       EVT VT) const {
4733   if (VT.getVectorNumElements() == 4 &&
4734       (VT.is128BitVector() || VT.is64BitVector())) {
4735     unsigned PFIndexes[4];
4736     for (unsigned i = 0; i != 4; ++i) {
4737       if (M[i] < 0)
4738         PFIndexes[i] = 8;
4739       else
4740         PFIndexes[i] = M[i];
4741     }
4742
4743     // Compute the index in the perfect shuffle table.
4744     unsigned PFTableIndex =
4745       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4746     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4747     unsigned Cost = (PFEntry >> 30);
4748
4749     if (Cost <= 4)
4750       return true;
4751   }
4752
4753   bool ReverseVEXT;
4754   unsigned Imm, WhichResult;
4755
4756   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4757   return (EltSize >= 32 ||
4758           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4759           isVREVMask(M, VT, 64) ||
4760           isVREVMask(M, VT, 32) ||
4761           isVREVMask(M, VT, 16) ||
4762           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4763           isVTBLMask(M, VT) ||
4764           isVTRNMask(M, VT, WhichResult) ||
4765           isVUZPMask(M, VT, WhichResult) ||
4766           isVZIPMask(M, VT, WhichResult) ||
4767           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4768           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4769           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4770           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4771 }
4772
4773 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4774 /// the specified operations to build the shuffle.
4775 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4776                                       SDValue RHS, SelectionDAG &DAG,
4777                                       DebugLoc dl) {
4778   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4779   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4780   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4781
4782   enum {
4783     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4784     OP_VREV,
4785     OP_VDUP0,
4786     OP_VDUP1,
4787     OP_VDUP2,
4788     OP_VDUP3,
4789     OP_VEXT1,
4790     OP_VEXT2,
4791     OP_VEXT3,
4792     OP_VUZPL, // VUZP, left result
4793     OP_VUZPR, // VUZP, right result
4794     OP_VZIPL, // VZIP, left result
4795     OP_VZIPR, // VZIP, right result
4796     OP_VTRNL, // VTRN, left result
4797     OP_VTRNR  // VTRN, right result
4798   };
4799
4800   if (OpNum == OP_COPY) {
4801     if (LHSID == (1*9+2)*9+3) return LHS;
4802     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4803     return RHS;
4804   }
4805
4806   SDValue OpLHS, OpRHS;
4807   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4808   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4809   EVT VT = OpLHS.getValueType();
4810
4811   switch (OpNum) {
4812   default: llvm_unreachable("Unknown shuffle opcode!");
4813   case OP_VREV:
4814     // VREV divides the vector in half and swaps within the half.
4815     if (VT.getVectorElementType() == MVT::i32 ||
4816         VT.getVectorElementType() == MVT::f32)
4817       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4818     // vrev <4 x i16> -> VREV32
4819     if (VT.getVectorElementType() == MVT::i16)
4820       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4821     // vrev <4 x i8> -> VREV16
4822     assert(VT.getVectorElementType() == MVT::i8);
4823     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4824   case OP_VDUP0:
4825   case OP_VDUP1:
4826   case OP_VDUP2:
4827   case OP_VDUP3:
4828     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4829                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4830   case OP_VEXT1:
4831   case OP_VEXT2:
4832   case OP_VEXT3:
4833     return DAG.getNode(ARMISD::VEXT, dl, VT,
4834                        OpLHS, OpRHS,
4835                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4836   case OP_VUZPL:
4837   case OP_VUZPR:
4838     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4839                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4840   case OP_VZIPL:
4841   case OP_VZIPR:
4842     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4843                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4844   case OP_VTRNL:
4845   case OP_VTRNR:
4846     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4847                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4848   }
4849 }
4850
4851 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4852                                        ArrayRef<int> ShuffleMask,
4853                                        SelectionDAG &DAG) {
4854   // Check to see if we can use the VTBL instruction.
4855   SDValue V1 = Op.getOperand(0);
4856   SDValue V2 = Op.getOperand(1);
4857   DebugLoc DL = Op.getDebugLoc();
4858
4859   SmallVector<SDValue, 8> VTBLMask;
4860   for (ArrayRef<int>::iterator
4861          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4862     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4863
4864   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4865     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4866                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4867                                    &VTBLMask[0], 8));
4868
4869   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4870                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4871                                  &VTBLMask[0], 8));
4872 }
4873
4874 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4875                                                       SelectionDAG &DAG) {
4876   DebugLoc DL = Op.getDebugLoc();
4877   SDValue OpLHS = Op.getOperand(0);
4878   EVT VT = OpLHS.getValueType();
4879
4880   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4881          "Expect an v8i16/v16i8 type");
4882   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4883   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4884   // extract the first 8 bytes into the top double word and the last 8 bytes
4885   // into the bottom double word. The v8i16 case is similar.
4886   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4887   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4888                      DAG.getConstant(ExtractNum, MVT::i32));
4889 }
4890
4891 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4892   SDValue V1 = Op.getOperand(0);
4893   SDValue V2 = Op.getOperand(1);
4894   DebugLoc dl = Op.getDebugLoc();
4895   EVT VT = Op.getValueType();
4896   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4897
4898   // Convert shuffles that are directly supported on NEON to target-specific
4899   // DAG nodes, instead of keeping them as shuffles and matching them again
4900   // during code selection.  This is more efficient and avoids the possibility
4901   // of inconsistencies between legalization and selection.
4902   // FIXME: floating-point vectors should be canonicalized to integer vectors
4903   // of the same time so that they get CSEd properly.
4904   ArrayRef<int> ShuffleMask = SVN->getMask();
4905
4906   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4907   if (EltSize <= 32) {
4908     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4909       int Lane = SVN->getSplatIndex();
4910       // If this is undef splat, generate it via "just" vdup, if possible.
4911       if (Lane == -1) Lane = 0;
4912
4913       // Test if V1 is a SCALAR_TO_VECTOR.
4914       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4915         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4916       }
4917       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4918       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4919       // reaches it).
4920       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4921           !isa<ConstantSDNode>(V1.getOperand(0))) {
4922         bool IsScalarToVector = true;
4923         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4924           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4925             IsScalarToVector = false;
4926             break;
4927           }
4928         if (IsScalarToVector)
4929           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4930       }
4931       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4932                          DAG.getConstant(Lane, MVT::i32));
4933     }
4934
4935     bool ReverseVEXT;
4936     unsigned Imm;
4937     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4938       if (ReverseVEXT)
4939         std::swap(V1, V2);
4940       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4941                          DAG.getConstant(Imm, MVT::i32));
4942     }
4943
4944     if (isVREVMask(ShuffleMask, VT, 64))
4945       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4946     if (isVREVMask(ShuffleMask, VT, 32))
4947       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4948     if (isVREVMask(ShuffleMask, VT, 16))
4949       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4950
4951     if (V2->getOpcode() == ISD::UNDEF &&
4952         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4953       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4954                          DAG.getConstant(Imm, MVT::i32));
4955     }
4956
4957     // Check for Neon shuffles that modify both input vectors in place.
4958     // If both results are used, i.e., if there are two shuffles with the same
4959     // source operands and with masks corresponding to both results of one of
4960     // these operations, DAG memoization will ensure that a single node is
4961     // used for both shuffles.
4962     unsigned WhichResult;
4963     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4964       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4965                          V1, V2).getValue(WhichResult);
4966     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4967       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4968                          V1, V2).getValue(WhichResult);
4969     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4970       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4971                          V1, V2).getValue(WhichResult);
4972
4973     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4974       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4975                          V1, V1).getValue(WhichResult);
4976     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4977       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4978                          V1, V1).getValue(WhichResult);
4979     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4980       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4981                          V1, V1).getValue(WhichResult);
4982   }
4983
4984   // If the shuffle is not directly supported and it has 4 elements, use
4985   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4986   unsigned NumElts = VT.getVectorNumElements();
4987   if (NumElts == 4) {
4988     unsigned PFIndexes[4];
4989     for (unsigned i = 0; i != 4; ++i) {
4990       if (ShuffleMask[i] < 0)
4991         PFIndexes[i] = 8;
4992       else
4993         PFIndexes[i] = ShuffleMask[i];
4994     }
4995
4996     // Compute the index in the perfect shuffle table.
4997     unsigned PFTableIndex =
4998       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4999     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5000     unsigned Cost = (PFEntry >> 30);
5001
5002     if (Cost <= 4)
5003       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5004   }
5005
5006   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5007   if (EltSize >= 32) {
5008     // Do the expansion with floating-point types, since that is what the VFP
5009     // registers are defined to use, and since i64 is not legal.
5010     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5011     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5012     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5013     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5014     SmallVector<SDValue, 8> Ops;
5015     for (unsigned i = 0; i < NumElts; ++i) {
5016       if (ShuffleMask[i] < 0)
5017         Ops.push_back(DAG.getUNDEF(EltVT));
5018       else
5019         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5020                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5021                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5022                                                   MVT::i32)));
5023     }
5024     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5025     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5026   }
5027
5028   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5029     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5030
5031   if (VT == MVT::v8i8) {
5032     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5033     if (NewOp.getNode())
5034       return NewOp;
5035   }
5036
5037   return SDValue();
5038 }
5039
5040 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5041   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5042   SDValue Lane = Op.getOperand(2);
5043   if (!isa<ConstantSDNode>(Lane))
5044     return SDValue();
5045
5046   return Op;
5047 }
5048
5049 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5050   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5051   SDValue Lane = Op.getOperand(1);
5052   if (!isa<ConstantSDNode>(Lane))
5053     return SDValue();
5054
5055   SDValue Vec = Op.getOperand(0);
5056   if (Op.getValueType() == MVT::i32 &&
5057       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5058     DebugLoc dl = Op.getDebugLoc();
5059     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5060   }
5061
5062   return Op;
5063 }
5064
5065 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5066   // The only time a CONCAT_VECTORS operation can have legal types is when
5067   // two 64-bit vectors are concatenated to a 128-bit vector.
5068   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5069          "unexpected CONCAT_VECTORS");
5070   DebugLoc dl = Op.getDebugLoc();
5071   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5072   SDValue Op0 = Op.getOperand(0);
5073   SDValue Op1 = Op.getOperand(1);
5074   if (Op0.getOpcode() != ISD::UNDEF)
5075     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5076                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5077                       DAG.getIntPtrConstant(0));
5078   if (Op1.getOpcode() != ISD::UNDEF)
5079     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5080                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5081                       DAG.getIntPtrConstant(1));
5082   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5083 }
5084
5085 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5086 /// element has been zero/sign-extended, depending on the isSigned parameter,
5087 /// from an integer type half its size.
5088 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5089                                    bool isSigned) {
5090   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5091   EVT VT = N->getValueType(0);
5092   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5093     SDNode *BVN = N->getOperand(0).getNode();
5094     if (BVN->getValueType(0) != MVT::v4i32 ||
5095         BVN->getOpcode() != ISD::BUILD_VECTOR)
5096       return false;
5097     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5098     unsigned HiElt = 1 - LoElt;
5099     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5100     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5101     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5102     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5103     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5104       return false;
5105     if (isSigned) {
5106       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5107           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5108         return true;
5109     } else {
5110       if (Hi0->isNullValue() && Hi1->isNullValue())
5111         return true;
5112     }
5113     return false;
5114   }
5115
5116   if (N->getOpcode() != ISD::BUILD_VECTOR)
5117     return false;
5118
5119   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5120     SDNode *Elt = N->getOperand(i).getNode();
5121     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5122       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5123       unsigned HalfSize = EltSize / 2;
5124       if (isSigned) {
5125         if (!isIntN(HalfSize, C->getSExtValue()))
5126           return false;
5127       } else {
5128         if (!isUIntN(HalfSize, C->getZExtValue()))
5129           return false;
5130       }
5131       continue;
5132     }
5133     return false;
5134   }
5135
5136   return true;
5137 }
5138
5139 /// isSignExtended - Check if a node is a vector value that is sign-extended
5140 /// or a constant BUILD_VECTOR with sign-extended elements.
5141 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5142   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5143     return true;
5144   if (isExtendedBUILD_VECTOR(N, DAG, true))
5145     return true;
5146   return false;
5147 }
5148
5149 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5150 /// or a constant BUILD_VECTOR with zero-extended elements.
5151 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5152   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5153     return true;
5154   if (isExtendedBUILD_VECTOR(N, DAG, false))
5155     return true;
5156   return false;
5157 }
5158
5159 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5160 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5161 /// We insert the required extension here to get the vector to fill a D register.
5162 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5163                                             const EVT &OrigTy,
5164                                             const EVT &ExtTy,
5165                                             unsigned ExtOpcode) {
5166   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5167   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5168   // 64-bits we need to insert a new extension so that it will be 64-bits.
5169   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5170   if (OrigTy.getSizeInBits() >= 64)
5171     return N;
5172
5173   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5174   MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5175   EVT NewVT;
5176   switch (OrigSimpleTy) {
5177   default: llvm_unreachable("Unexpected Orig Vector Type");
5178   case MVT::v2i8:
5179   case MVT::v2i16:
5180     NewVT = MVT::v2i32;
5181     break;
5182   case MVT::v4i8:
5183     NewVT = MVT::v4i16;
5184     break;
5185   }
5186   return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5187 }
5188
5189 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5190 /// does not do any sign/zero extension. If the original vector is less
5191 /// than 64 bits, an appropriate extension will be added after the load to
5192 /// reach a total size of 64 bits. We have to add the extension separately
5193 /// because ARM does not have a sign/zero extending load for vectors.
5194 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5195   SDValue NonExtendingLoad =
5196     DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5197                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5198                 LD->isNonTemporal(), LD->isInvariant(),
5199                 LD->getAlignment());
5200   unsigned ExtOp = 0;
5201   switch (LD->getExtensionType()) {
5202   default: llvm_unreachable("Unexpected LoadExtType");
5203   case ISD::EXTLOAD:
5204   case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5205   case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5206   }
5207   MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5208   MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5209   return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5210                                       MemType, ExtType, ExtOp);
5211 }
5212
5213 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5214 /// extending load, or BUILD_VECTOR with extended elements, return the
5215 /// unextended value. The unextended vector should be 64 bits so that it can
5216 /// be used as an operand to a VMULL instruction. If the original vector size
5217 /// before extension is less than 64 bits we add a an extension to resize
5218 /// the vector to 64 bits.
5219 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5220   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5221     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5222                                         N->getOperand(0)->getValueType(0),
5223                                         N->getValueType(0),
5224                                         N->getOpcode());
5225
5226   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5227     return SkipLoadExtensionForVMULL(LD, DAG);
5228
5229   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5230   // have been legalized as a BITCAST from v4i32.
5231   if (N->getOpcode() == ISD::BITCAST) {
5232     SDNode *BVN = N->getOperand(0).getNode();
5233     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5234            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5235     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5236     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5237                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5238   }
5239   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5240   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5241   EVT VT = N->getValueType(0);
5242   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5243   unsigned NumElts = VT.getVectorNumElements();
5244   MVT TruncVT = MVT::getIntegerVT(EltSize);
5245   SmallVector<SDValue, 8> Ops;
5246   for (unsigned i = 0; i != NumElts; ++i) {
5247     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5248     const APInt &CInt = C->getAPIntValue();
5249     // Element types smaller than 32 bits are not legal, so use i32 elements.
5250     // The values are implicitly truncated so sext vs. zext doesn't matter.
5251     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5252   }
5253   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5254                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5255 }
5256
5257 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5258   unsigned Opcode = N->getOpcode();
5259   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5260     SDNode *N0 = N->getOperand(0).getNode();
5261     SDNode *N1 = N->getOperand(1).getNode();
5262     return N0->hasOneUse() && N1->hasOneUse() &&
5263       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5264   }
5265   return false;
5266 }
5267
5268 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5269   unsigned Opcode = N->getOpcode();
5270   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5271     SDNode *N0 = N->getOperand(0).getNode();
5272     SDNode *N1 = N->getOperand(1).getNode();
5273     return N0->hasOneUse() && N1->hasOneUse() &&
5274       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5275   }
5276   return false;
5277 }
5278
5279 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5280   // Multiplications are only custom-lowered for 128-bit vectors so that
5281   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5282   EVT VT = Op.getValueType();
5283   assert(VT.is128BitVector() && VT.isInteger() &&
5284          "unexpected type for custom-lowering ISD::MUL");
5285   SDNode *N0 = Op.getOperand(0).getNode();
5286   SDNode *N1 = Op.getOperand(1).getNode();
5287   unsigned NewOpc = 0;
5288   bool isMLA = false;
5289   bool isN0SExt = isSignExtended(N0, DAG);
5290   bool isN1SExt = isSignExtended(N1, DAG);
5291   if (isN0SExt && isN1SExt)
5292     NewOpc = ARMISD::VMULLs;
5293   else {
5294     bool isN0ZExt = isZeroExtended(N0, DAG);
5295     bool isN1ZExt = isZeroExtended(N1, DAG);
5296     if (isN0ZExt && isN1ZExt)
5297       NewOpc = ARMISD::VMULLu;
5298     else if (isN1SExt || isN1ZExt) {
5299       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5300       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5301       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5302         NewOpc = ARMISD::VMULLs;
5303         isMLA = true;
5304       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5305         NewOpc = ARMISD::VMULLu;
5306         isMLA = true;
5307       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5308         std::swap(N0, N1);
5309         NewOpc = ARMISD::VMULLu;
5310         isMLA = true;
5311       }
5312     }
5313
5314     if (!NewOpc) {
5315       if (VT == MVT::v2i64)
5316         // Fall through to expand this.  It is not legal.
5317         return SDValue();
5318       else
5319         // Other vector multiplications are legal.
5320         return Op;
5321     }
5322   }
5323
5324   // Legalize to a VMULL instruction.
5325   DebugLoc DL = Op.getDebugLoc();
5326   SDValue Op0;
5327   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5328   if (!isMLA) {
5329     Op0 = SkipExtensionForVMULL(N0, DAG);
5330     assert(Op0.getValueType().is64BitVector() &&
5331            Op1.getValueType().is64BitVector() &&
5332            "unexpected types for extended operands to VMULL");
5333     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5334   }
5335
5336   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5337   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5338   //   vmull q0, d4, d6
5339   //   vmlal q0, d5, d6
5340   // is faster than
5341   //   vaddl q0, d4, d5
5342   //   vmovl q1, d6
5343   //   vmul  q0, q0, q1
5344   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5345   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5346   EVT Op1VT = Op1.getValueType();
5347   return DAG.getNode(N0->getOpcode(), DL, VT,
5348                      DAG.getNode(NewOpc, DL, VT,
5349                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5350                      DAG.getNode(NewOpc, DL, VT,
5351                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5352 }
5353
5354 static SDValue
5355 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5356   // Convert to float
5357   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5358   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5359   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5360   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5361   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5362   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5363   // Get reciprocal estimate.
5364   // float4 recip = vrecpeq_f32(yf);
5365   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5366                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5367   // Because char has a smaller range than uchar, we can actually get away
5368   // without any newton steps.  This requires that we use a weird bias
5369   // of 0xb000, however (again, this has been exhaustively tested).
5370   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5371   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5372   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5373   Y = DAG.getConstant(0xb000, MVT::i32);
5374   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5375   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5376   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5377   // Convert back to short.
5378   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5379   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5380   return X;
5381 }
5382
5383 static SDValue
5384 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5385   SDValue N2;
5386   // Convert to float.
5387   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5388   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5389   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5390   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5391   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5392   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5393
5394   // Use reciprocal estimate and one refinement step.
5395   // float4 recip = vrecpeq_f32(yf);
5396   // recip *= vrecpsq_f32(yf, recip);
5397   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5398                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5399   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5400                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5401                    N1, N2);
5402   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5403   // Because short has a smaller range than ushort, we can actually get away
5404   // with only a single newton step.  This requires that we use a weird bias
5405   // of 89, however (again, this has been exhaustively tested).
5406   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5407   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5408   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5409   N1 = DAG.getConstant(0x89, MVT::i32);
5410   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5411   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5412   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5413   // Convert back to integer and return.
5414   // return vmovn_s32(vcvt_s32_f32(result));
5415   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5416   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5417   return N0;
5418 }
5419
5420 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5421   EVT VT = Op.getValueType();
5422   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5423          "unexpected type for custom-lowering ISD::SDIV");
5424
5425   DebugLoc dl = Op.getDebugLoc();
5426   SDValue N0 = Op.getOperand(0);
5427   SDValue N1 = Op.getOperand(1);
5428   SDValue N2, N3;
5429
5430   if (VT == MVT::v8i8) {
5431     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5432     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5433
5434     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5435                      DAG.getIntPtrConstant(4));
5436     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5437                      DAG.getIntPtrConstant(4));
5438     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5439                      DAG.getIntPtrConstant(0));
5440     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5441                      DAG.getIntPtrConstant(0));
5442
5443     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5444     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5445
5446     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5447     N0 = LowerCONCAT_VECTORS(N0, DAG);
5448
5449     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5450     return N0;
5451   }
5452   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5453 }
5454
5455 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5456   EVT VT = Op.getValueType();
5457   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5458          "unexpected type for custom-lowering ISD::UDIV");
5459
5460   DebugLoc dl = Op.getDebugLoc();
5461   SDValue N0 = Op.getOperand(0);
5462   SDValue N1 = Op.getOperand(1);
5463   SDValue N2, N3;
5464
5465   if (VT == MVT::v8i8) {
5466     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5467     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5468
5469     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5470                      DAG.getIntPtrConstant(4));
5471     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5472                      DAG.getIntPtrConstant(4));
5473     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5474                      DAG.getIntPtrConstant(0));
5475     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5476                      DAG.getIntPtrConstant(0));
5477
5478     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5479     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5480
5481     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5482     N0 = LowerCONCAT_VECTORS(N0, DAG);
5483
5484     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5485                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5486                      N0);
5487     return N0;
5488   }
5489
5490   // v4i16 sdiv ... Convert to float.
5491   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5492   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5493   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5494   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5495   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5496   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5497
5498   // Use reciprocal estimate and two refinement steps.
5499   // float4 recip = vrecpeq_f32(yf);
5500   // recip *= vrecpsq_f32(yf, recip);
5501   // recip *= vrecpsq_f32(yf, recip);
5502   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5503                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5504   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5505                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5506                    BN1, N2);
5507   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5508   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5509                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5510                    BN1, N2);
5511   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5512   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5513   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5514   // and that it will never cause us to return an answer too large).
5515   // float4 result = as_float4(as_int4(xf*recip) + 2);
5516   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5517   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5518   N1 = DAG.getConstant(2, MVT::i32);
5519   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5520   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5521   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5522   // Convert back to integer and return.
5523   // return vmovn_u32(vcvt_s32_f32(result));
5524   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5525   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5526   return N0;
5527 }
5528
5529 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5530   EVT VT = Op.getNode()->getValueType(0);
5531   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5532
5533   unsigned Opc;
5534   bool ExtraOp = false;
5535   switch (Op.getOpcode()) {
5536   default: llvm_unreachable("Invalid code");
5537   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5538   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5539   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5540   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5541   }
5542
5543   if (!ExtraOp)
5544     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5545                        Op.getOperand(1));
5546   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5547                      Op.getOperand(1), Op.getOperand(2));
5548 }
5549
5550 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5551   // Monotonic load/store is legal for all targets
5552   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5553     return Op;
5554
5555   // Aquire/Release load/store is not legal for targets without a
5556   // dmb or equivalent available.
5557   return SDValue();
5558 }
5559
5560
5561 static void
5562 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5563                     SelectionDAG &DAG, unsigned NewOp) {
5564   DebugLoc dl = Node->getDebugLoc();
5565   assert (Node->getValueType(0) == MVT::i64 &&
5566           "Only know how to expand i64 atomics");
5567
5568   SmallVector<SDValue, 6> Ops;
5569   Ops.push_back(Node->getOperand(0)); // Chain
5570   Ops.push_back(Node->getOperand(1)); // Ptr
5571   // Low part of Val1
5572   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5573                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5574   // High part of Val1
5575   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5576                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5577   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5578     // High part of Val1
5579     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5580                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5581     // High part of Val2
5582     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5583                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5584   }
5585   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5586   SDValue Result =
5587     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5588                             cast<MemSDNode>(Node)->getMemOperand());
5589   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5590   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5591   Results.push_back(Result.getValue(2));
5592 }
5593
5594 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5595   switch (Op.getOpcode()) {
5596   default: llvm_unreachable("Don't know how to custom lower this!");
5597   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5598   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5599   case ISD::GlobalAddress:
5600     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5601       LowerGlobalAddressELF(Op, DAG);
5602   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5603   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5604   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5605   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5606   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5607   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5608   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5609   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5610   case ISD::SINT_TO_FP:
5611   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5612   case ISD::FP_TO_SINT:
5613   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5614   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5615   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5616   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5617   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5618   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5619   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5620   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5621                                                                Subtarget);
5622   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5623   case ISD::SHL:
5624   case ISD::SRL:
5625   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5626   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5627   case ISD::SRL_PARTS:
5628   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5629   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5630   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5631   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5632   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5633   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5634   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5635   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5636   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5637   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5638   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5639   case ISD::MUL:           return LowerMUL(Op, DAG);
5640   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5641   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5642   case ISD::ADDC:
5643   case ISD::ADDE:
5644   case ISD::SUBC:
5645   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5646   case ISD::ATOMIC_LOAD:
5647   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5648   }
5649 }
5650
5651 /// ReplaceNodeResults - Replace the results of node with an illegal result
5652 /// type with new values built out of custom code.
5653 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5654                                            SmallVectorImpl<SDValue>&Results,
5655                                            SelectionDAG &DAG) const {
5656   SDValue Res;
5657   switch (N->getOpcode()) {
5658   default:
5659     llvm_unreachable("Don't know how to custom expand this!");
5660   case ISD::BITCAST:
5661     Res = ExpandBITCAST(N, DAG);
5662     break;
5663   case ISD::SIGN_EXTEND:
5664   case ISD::ZERO_EXTEND:
5665     Res = ExpandVectorExtension(N, DAG);
5666     break;
5667   case ISD::SRL:
5668   case ISD::SRA:
5669     Res = Expand64BitShift(N, DAG, Subtarget);
5670     break;
5671   case ISD::ATOMIC_LOAD_ADD:
5672     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5673     return;
5674   case ISD::ATOMIC_LOAD_AND:
5675     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5676     return;
5677   case ISD::ATOMIC_LOAD_NAND:
5678     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5679     return;
5680   case ISD::ATOMIC_LOAD_OR:
5681     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5682     return;
5683   case ISD::ATOMIC_LOAD_SUB:
5684     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5685     return;
5686   case ISD::ATOMIC_LOAD_XOR:
5687     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5688     return;
5689   case ISD::ATOMIC_SWAP:
5690     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5691     return;
5692   case ISD::ATOMIC_CMP_SWAP:
5693     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5694     return;
5695   case ISD::ATOMIC_LOAD_MIN:
5696     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5697     return;
5698   case ISD::ATOMIC_LOAD_UMIN:
5699     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5700     return;
5701   case ISD::ATOMIC_LOAD_MAX:
5702     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5703     return;
5704   case ISD::ATOMIC_LOAD_UMAX:
5705     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5706     return;
5707   }
5708   if (Res.getNode())
5709     Results.push_back(Res);
5710 }
5711
5712 //===----------------------------------------------------------------------===//
5713 //                           ARM Scheduler Hooks
5714 //===----------------------------------------------------------------------===//
5715
5716 MachineBasicBlock *
5717 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5718                                      MachineBasicBlock *BB,
5719                                      unsigned Size) const {
5720   unsigned dest    = MI->getOperand(0).getReg();
5721   unsigned ptr     = MI->getOperand(1).getReg();
5722   unsigned oldval  = MI->getOperand(2).getReg();
5723   unsigned newval  = MI->getOperand(3).getReg();
5724   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5725   DebugLoc dl = MI->getDebugLoc();
5726   bool isThumb2 = Subtarget->isThumb2();
5727
5728   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5729   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5730     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5731     (const TargetRegisterClass*)&ARM::GPRRegClass);
5732
5733   if (isThumb2) {
5734     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5735     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5736     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5737   }
5738
5739   unsigned ldrOpc, strOpc;
5740   switch (Size) {
5741   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5742   case 1:
5743     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5744     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5745     break;
5746   case 2:
5747     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5748     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5749     break;
5750   case 4:
5751     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5752     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5753     break;
5754   }
5755
5756   MachineFunction *MF = BB->getParent();
5757   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5758   MachineFunction::iterator It = BB;
5759   ++It; // insert the new blocks after the current block
5760
5761   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5762   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5763   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5764   MF->insert(It, loop1MBB);
5765   MF->insert(It, loop2MBB);
5766   MF->insert(It, exitMBB);
5767
5768   // Transfer the remainder of BB and its successor edges to exitMBB.
5769   exitMBB->splice(exitMBB->begin(), BB,
5770                   llvm::next(MachineBasicBlock::iterator(MI)),
5771                   BB->end());
5772   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5773
5774   //  thisMBB:
5775   //   ...
5776   //   fallthrough --> loop1MBB
5777   BB->addSuccessor(loop1MBB);
5778
5779   // loop1MBB:
5780   //   ldrex dest, [ptr]
5781   //   cmp dest, oldval
5782   //   bne exitMBB
5783   BB = loop1MBB;
5784   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5785   if (ldrOpc == ARM::t2LDREX)
5786     MIB.addImm(0);
5787   AddDefaultPred(MIB);
5788   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5789                  .addReg(dest).addReg(oldval));
5790   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5791     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5792   BB->addSuccessor(loop2MBB);
5793   BB->addSuccessor(exitMBB);
5794
5795   // loop2MBB:
5796   //   strex scratch, newval, [ptr]
5797   //   cmp scratch, #0
5798   //   bne loop1MBB
5799   BB = loop2MBB;
5800   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5801   if (strOpc == ARM::t2STREX)
5802     MIB.addImm(0);
5803   AddDefaultPred(MIB);
5804   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5805                  .addReg(scratch).addImm(0));
5806   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5807     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5808   BB->addSuccessor(loop1MBB);
5809   BB->addSuccessor(exitMBB);
5810
5811   //  exitMBB:
5812   //   ...
5813   BB = exitMBB;
5814
5815   MI->eraseFromParent();   // The instruction is gone now.
5816
5817   return BB;
5818 }
5819
5820 MachineBasicBlock *
5821 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5822                                     unsigned Size, unsigned BinOpcode) const {
5823   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5824   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5825
5826   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5827   MachineFunction *MF = BB->getParent();
5828   MachineFunction::iterator It = BB;
5829   ++It;
5830
5831   unsigned dest = MI->getOperand(0).getReg();
5832   unsigned ptr = MI->getOperand(1).getReg();
5833   unsigned incr = MI->getOperand(2).getReg();
5834   DebugLoc dl = MI->getDebugLoc();
5835   bool isThumb2 = Subtarget->isThumb2();
5836
5837   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5838   if (isThumb2) {
5839     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5840     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5841   }
5842
5843   unsigned ldrOpc, strOpc;
5844   switch (Size) {
5845   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5846   case 1:
5847     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5848     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5849     break;
5850   case 2:
5851     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5852     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5853     break;
5854   case 4:
5855     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5856     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5857     break;
5858   }
5859
5860   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5861   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5862   MF->insert(It, loopMBB);
5863   MF->insert(It, exitMBB);
5864
5865   // Transfer the remainder of BB and its successor edges to exitMBB.
5866   exitMBB->splice(exitMBB->begin(), BB,
5867                   llvm::next(MachineBasicBlock::iterator(MI)),
5868                   BB->end());
5869   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5870
5871   const TargetRegisterClass *TRC = isThumb2 ?
5872     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5873     (const TargetRegisterClass*)&ARM::GPRRegClass;
5874   unsigned scratch = MRI.createVirtualRegister(TRC);
5875   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5876
5877   //  thisMBB:
5878   //   ...
5879   //   fallthrough --> loopMBB
5880   BB->addSuccessor(loopMBB);
5881
5882   //  loopMBB:
5883   //   ldrex dest, ptr
5884   //   <binop> scratch2, dest, incr
5885   //   strex scratch, scratch2, ptr
5886   //   cmp scratch, #0
5887   //   bne- loopMBB
5888   //   fallthrough --> exitMBB
5889   BB = loopMBB;
5890   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5891   if (ldrOpc == ARM::t2LDREX)
5892     MIB.addImm(0);
5893   AddDefaultPred(MIB);
5894   if (BinOpcode) {
5895     // operand order needs to go the other way for NAND
5896     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5897       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5898                      addReg(incr).addReg(dest)).addReg(0);
5899     else
5900       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5901                      addReg(dest).addReg(incr)).addReg(0);
5902   }
5903
5904   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5905   if (strOpc == ARM::t2STREX)
5906     MIB.addImm(0);
5907   AddDefaultPred(MIB);
5908   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5909                  .addReg(scratch).addImm(0));
5910   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5911     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5912
5913   BB->addSuccessor(loopMBB);
5914   BB->addSuccessor(exitMBB);
5915
5916   //  exitMBB:
5917   //   ...
5918   BB = exitMBB;
5919
5920   MI->eraseFromParent();   // The instruction is gone now.
5921
5922   return BB;
5923 }
5924
5925 MachineBasicBlock *
5926 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5927                                           MachineBasicBlock *BB,
5928                                           unsigned Size,
5929                                           bool signExtend,
5930                                           ARMCC::CondCodes Cond) const {
5931   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5932
5933   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5934   MachineFunction *MF = BB->getParent();
5935   MachineFunction::iterator It = BB;
5936   ++It;
5937
5938   unsigned dest = MI->getOperand(0).getReg();
5939   unsigned ptr = MI->getOperand(1).getReg();
5940   unsigned incr = MI->getOperand(2).getReg();
5941   unsigned oldval = dest;
5942   DebugLoc dl = MI->getDebugLoc();
5943   bool isThumb2 = Subtarget->isThumb2();
5944
5945   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5946   if (isThumb2) {
5947     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5948     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5949   }
5950
5951   unsigned ldrOpc, strOpc, extendOpc;
5952   switch (Size) {
5953   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5954   case 1:
5955     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5956     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5957     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5958     break;
5959   case 2:
5960     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5961     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5962     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5963     break;
5964   case 4:
5965     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5966     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5967     extendOpc = 0;
5968     break;
5969   }
5970
5971   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5972   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5973   MF->insert(It, loopMBB);
5974   MF->insert(It, exitMBB);
5975
5976   // Transfer the remainder of BB and its successor edges to exitMBB.
5977   exitMBB->splice(exitMBB->begin(), BB,
5978                   llvm::next(MachineBasicBlock::iterator(MI)),
5979                   BB->end());
5980   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5981
5982   const TargetRegisterClass *TRC = isThumb2 ?
5983     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5984     (const TargetRegisterClass*)&ARM::GPRRegClass;
5985   unsigned scratch = MRI.createVirtualRegister(TRC);
5986   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5987
5988   //  thisMBB:
5989   //   ...
5990   //   fallthrough --> loopMBB
5991   BB->addSuccessor(loopMBB);
5992
5993   //  loopMBB:
5994   //   ldrex dest, ptr
5995   //   (sign extend dest, if required)
5996   //   cmp dest, incr
5997   //   cmov.cond scratch2, incr, dest
5998   //   strex scratch, scratch2, ptr
5999   //   cmp scratch, #0
6000   //   bne- loopMBB
6001   //   fallthrough --> exitMBB
6002   BB = loopMBB;
6003   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6004   if (ldrOpc == ARM::t2LDREX)
6005     MIB.addImm(0);
6006   AddDefaultPred(MIB);
6007
6008   // Sign extend the value, if necessary.
6009   if (signExtend && extendOpc) {
6010     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6011     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6012                      .addReg(dest)
6013                      .addImm(0));
6014   }
6015
6016   // Build compare and cmov instructions.
6017   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6018                  .addReg(oldval).addReg(incr));
6019   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6020          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6021
6022   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6023   if (strOpc == ARM::t2STREX)
6024     MIB.addImm(0);
6025   AddDefaultPred(MIB);
6026   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6027                  .addReg(scratch).addImm(0));
6028   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6029     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6030
6031   BB->addSuccessor(loopMBB);
6032   BB->addSuccessor(exitMBB);
6033
6034   //  exitMBB:
6035   //   ...
6036   BB = exitMBB;
6037
6038   MI->eraseFromParent();   // The instruction is gone now.
6039
6040   return BB;
6041 }
6042
6043 MachineBasicBlock *
6044 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6045                                       unsigned Op1, unsigned Op2,
6046                                       bool NeedsCarry, bool IsCmpxchg,
6047                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6048   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6049   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6050
6051   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6052   MachineFunction *MF = BB->getParent();
6053   MachineFunction::iterator It = BB;
6054   ++It;
6055
6056   unsigned destlo = MI->getOperand(0).getReg();
6057   unsigned desthi = MI->getOperand(1).getReg();
6058   unsigned ptr = MI->getOperand(2).getReg();
6059   unsigned vallo = MI->getOperand(3).getReg();
6060   unsigned valhi = MI->getOperand(4).getReg();
6061   DebugLoc dl = MI->getDebugLoc();
6062   bool isThumb2 = Subtarget->isThumb2();
6063
6064   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6065   if (isThumb2) {
6066     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6067     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6068     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6069   }
6070
6071   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6072   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6073   if (IsCmpxchg || IsMinMax)
6074     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6075   if (IsCmpxchg)
6076     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6077   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6078
6079   MF->insert(It, loopMBB);
6080   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6081   if (IsCmpxchg) MF->insert(It, cont2BB);
6082   MF->insert(It, exitMBB);
6083
6084   // Transfer the remainder of BB and its successor edges to exitMBB.
6085   exitMBB->splice(exitMBB->begin(), BB,
6086                   llvm::next(MachineBasicBlock::iterator(MI)),
6087                   BB->end());
6088   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6089
6090   const TargetRegisterClass *TRC = isThumb2 ?
6091     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6092     (const TargetRegisterClass*)&ARM::GPRRegClass;
6093   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6094
6095   //  thisMBB:
6096   //   ...
6097   //   fallthrough --> loopMBB
6098   BB->addSuccessor(loopMBB);
6099
6100   //  loopMBB:
6101   //   ldrexd r2, r3, ptr
6102   //   <binopa> r0, r2, incr
6103   //   <binopb> r1, r3, incr
6104   //   strexd storesuccess, r0, r1, ptr
6105   //   cmp storesuccess, #0
6106   //   bne- loopMBB
6107   //   fallthrough --> exitMBB
6108   BB = loopMBB;
6109
6110   // Load
6111   if (isThumb2) {
6112     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6113                    .addReg(destlo, RegState::Define)
6114                    .addReg(desthi, RegState::Define)
6115                    .addReg(ptr));
6116   } else {
6117     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6118     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6119                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6120     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6121     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6122       .addReg(GPRPair0, 0, ARM::gsub_0);
6123     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6124       .addReg(GPRPair0, 0, ARM::gsub_1);
6125   }
6126
6127   unsigned StoreLo, StoreHi;
6128   if (IsCmpxchg) {
6129     // Add early exit
6130     for (unsigned i = 0; i < 2; i++) {
6131       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6132                                                          ARM::CMPrr))
6133                      .addReg(i == 0 ? destlo : desthi)
6134                      .addReg(i == 0 ? vallo : valhi));
6135       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6136         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6137       BB->addSuccessor(exitMBB);
6138       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6139       BB = (i == 0 ? contBB : cont2BB);
6140     }
6141
6142     // Copy to physregs for strexd
6143     StoreLo = MI->getOperand(5).getReg();
6144     StoreHi = MI->getOperand(6).getReg();
6145   } else if (Op1) {
6146     // Perform binary operation
6147     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6148     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6149                    .addReg(destlo).addReg(vallo))
6150         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6151     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6152     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6153                    .addReg(desthi).addReg(valhi))
6154         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6155
6156     StoreLo = tmpRegLo;
6157     StoreHi = tmpRegHi;
6158   } else {
6159     // Copy to physregs for strexd
6160     StoreLo = vallo;
6161     StoreHi = valhi;
6162   }
6163   if (IsMinMax) {
6164     // Compare and branch to exit block.
6165     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6166       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6167     BB->addSuccessor(exitMBB);
6168     BB->addSuccessor(contBB);
6169     BB = contBB;
6170     StoreLo = vallo;
6171     StoreHi = valhi;
6172   }
6173
6174   // Store
6175   if (isThumb2) {
6176     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6177                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6178   } else {
6179     // Marshal a pair...
6180     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6181     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6182     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6183     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6184     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6185       .addReg(UndefPair)
6186       .addReg(StoreLo)
6187       .addImm(ARM::gsub_0);
6188     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6189       .addReg(r1)
6190       .addReg(StoreHi)
6191       .addImm(ARM::gsub_1);
6192
6193     // ...and store it
6194     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6195                    .addReg(StorePair).addReg(ptr));
6196   }
6197   // Cmp+jump
6198   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6199                  .addReg(storesuccess).addImm(0));
6200   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6201     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6202
6203   BB->addSuccessor(loopMBB);
6204   BB->addSuccessor(exitMBB);
6205
6206   //  exitMBB:
6207   //   ...
6208   BB = exitMBB;
6209
6210   MI->eraseFromParent();   // The instruction is gone now.
6211
6212   return BB;
6213 }
6214
6215 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6216 /// registers the function context.
6217 void ARMTargetLowering::
6218 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6219                        MachineBasicBlock *DispatchBB, int FI) const {
6220   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6221   DebugLoc dl = MI->getDebugLoc();
6222   MachineFunction *MF = MBB->getParent();
6223   MachineRegisterInfo *MRI = &MF->getRegInfo();
6224   MachineConstantPool *MCP = MF->getConstantPool();
6225   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6226   const Function *F = MF->getFunction();
6227
6228   bool isThumb = Subtarget->isThumb();
6229   bool isThumb2 = Subtarget->isThumb2();
6230
6231   unsigned PCLabelId = AFI->createPICLabelUId();
6232   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6233   ARMConstantPoolValue *CPV =
6234     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6235   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6236
6237   const TargetRegisterClass *TRC = isThumb ?
6238     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6239     (const TargetRegisterClass*)&ARM::GPRRegClass;
6240
6241   // Grab constant pool and fixed stack memory operands.
6242   MachineMemOperand *CPMMO =
6243     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6244                              MachineMemOperand::MOLoad, 4, 4);
6245
6246   MachineMemOperand *FIMMOSt =
6247     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6248                              MachineMemOperand::MOStore, 4, 4);
6249
6250   // Load the address of the dispatch MBB into the jump buffer.
6251   if (isThumb2) {
6252     // Incoming value: jbuf
6253     //   ldr.n  r5, LCPI1_1
6254     //   orr    r5, r5, #1
6255     //   add    r5, pc
6256     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6257     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6258     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6259                    .addConstantPoolIndex(CPI)
6260                    .addMemOperand(CPMMO));
6261     // Set the low bit because of thumb mode.
6262     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6263     AddDefaultCC(
6264       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6265                      .addReg(NewVReg1, RegState::Kill)
6266                      .addImm(0x01)));
6267     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6268     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6269       .addReg(NewVReg2, RegState::Kill)
6270       .addImm(PCLabelId);
6271     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6272                    .addReg(NewVReg3, RegState::Kill)
6273                    .addFrameIndex(FI)
6274                    .addImm(36)  // &jbuf[1] :: pc
6275                    .addMemOperand(FIMMOSt));
6276   } else if (isThumb) {
6277     // Incoming value: jbuf
6278     //   ldr.n  r1, LCPI1_4
6279     //   add    r1, pc
6280     //   mov    r2, #1
6281     //   orrs   r1, r2
6282     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6283     //   str    r1, [r2]
6284     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6285     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6286                    .addConstantPoolIndex(CPI)
6287                    .addMemOperand(CPMMO));
6288     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6289     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6290       .addReg(NewVReg1, RegState::Kill)
6291       .addImm(PCLabelId);
6292     // Set the low bit because of thumb mode.
6293     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6294     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6295                    .addReg(ARM::CPSR, RegState::Define)
6296                    .addImm(1));
6297     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6298     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6299                    .addReg(ARM::CPSR, RegState::Define)
6300                    .addReg(NewVReg2, RegState::Kill)
6301                    .addReg(NewVReg3, RegState::Kill));
6302     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6303     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6304                    .addFrameIndex(FI)
6305                    .addImm(36)); // &jbuf[1] :: pc
6306     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6307                    .addReg(NewVReg4, RegState::Kill)
6308                    .addReg(NewVReg5, RegState::Kill)
6309                    .addImm(0)
6310                    .addMemOperand(FIMMOSt));
6311   } else {
6312     // Incoming value: jbuf
6313     //   ldr  r1, LCPI1_1
6314     //   add  r1, pc, r1
6315     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6316     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6317     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6318                    .addConstantPoolIndex(CPI)
6319                    .addImm(0)
6320                    .addMemOperand(CPMMO));
6321     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6322     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6323                    .addReg(NewVReg1, RegState::Kill)
6324                    .addImm(PCLabelId));
6325     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6326                    .addReg(NewVReg2, RegState::Kill)
6327                    .addFrameIndex(FI)
6328                    .addImm(36)  // &jbuf[1] :: pc
6329                    .addMemOperand(FIMMOSt));
6330   }
6331 }
6332
6333 MachineBasicBlock *ARMTargetLowering::
6334 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6335   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6336   DebugLoc dl = MI->getDebugLoc();
6337   MachineFunction *MF = MBB->getParent();
6338   MachineRegisterInfo *MRI = &MF->getRegInfo();
6339   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6340   MachineFrameInfo *MFI = MF->getFrameInfo();
6341   int FI = MFI->getFunctionContextIndex();
6342
6343   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6344     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6345     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6346
6347   // Get a mapping of the call site numbers to all of the landing pads they're
6348   // associated with.
6349   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6350   unsigned MaxCSNum = 0;
6351   MachineModuleInfo &MMI = MF->getMMI();
6352   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6353        ++BB) {
6354     if (!BB->isLandingPad()) continue;
6355
6356     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6357     // pad.
6358     for (MachineBasicBlock::iterator
6359            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6360       if (!II->isEHLabel()) continue;
6361
6362       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6363       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6364
6365       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6366       for (SmallVectorImpl<unsigned>::iterator
6367              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6368            CSI != CSE; ++CSI) {
6369         CallSiteNumToLPad[*CSI].push_back(BB);
6370         MaxCSNum = std::max(MaxCSNum, *CSI);
6371       }
6372       break;
6373     }
6374   }
6375
6376   // Get an ordered list of the machine basic blocks for the jump table.
6377   std::vector<MachineBasicBlock*> LPadList;
6378   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6379   LPadList.reserve(CallSiteNumToLPad.size());
6380   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6381     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6382     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6383            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6384       LPadList.push_back(*II);
6385       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6386     }
6387   }
6388
6389   assert(!LPadList.empty() &&
6390          "No landing pad destinations for the dispatch jump table!");
6391
6392   // Create the jump table and associated information.
6393   MachineJumpTableInfo *JTI =
6394     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6395   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6396   unsigned UId = AFI->createJumpTableUId();
6397   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6398
6399   // Create the MBBs for the dispatch code.
6400
6401   // Shove the dispatch's address into the return slot in the function context.
6402   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6403   DispatchBB->setIsLandingPad();
6404
6405   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6406   unsigned trap_opcode;
6407   if (Subtarget->isThumb())
6408     trap_opcode = ARM::tTRAP;
6409   else
6410     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6411
6412   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6413   DispatchBB->addSuccessor(TrapBB);
6414
6415   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6416   DispatchBB->addSuccessor(DispContBB);
6417
6418   // Insert and MBBs.
6419   MF->insert(MF->end(), DispatchBB);
6420   MF->insert(MF->end(), DispContBB);
6421   MF->insert(MF->end(), TrapBB);
6422
6423   // Insert code into the entry block that creates and registers the function
6424   // context.
6425   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6426
6427   MachineMemOperand *FIMMOLd =
6428     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6429                              MachineMemOperand::MOLoad |
6430                              MachineMemOperand::MOVolatile, 4, 4);
6431
6432   MachineInstrBuilder MIB;
6433   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6434
6435   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6436   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6437
6438   // Add a register mask with no preserved registers.  This results in all
6439   // registers being marked as clobbered.
6440   MIB.addRegMask(RI.getNoPreservedMask());
6441
6442   unsigned NumLPads = LPadList.size();
6443   if (Subtarget->isThumb2()) {
6444     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6445     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6446                    .addFrameIndex(FI)
6447                    .addImm(4)
6448                    .addMemOperand(FIMMOLd));
6449
6450     if (NumLPads < 256) {
6451       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6452                      .addReg(NewVReg1)
6453                      .addImm(LPadList.size()));
6454     } else {
6455       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6456       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6457                      .addImm(NumLPads & 0xFFFF));
6458
6459       unsigned VReg2 = VReg1;
6460       if ((NumLPads & 0xFFFF0000) != 0) {
6461         VReg2 = MRI->createVirtualRegister(TRC);
6462         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6463                        .addReg(VReg1)
6464                        .addImm(NumLPads >> 16));
6465       }
6466
6467       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6468                      .addReg(NewVReg1)
6469                      .addReg(VReg2));
6470     }
6471
6472     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6473       .addMBB(TrapBB)
6474       .addImm(ARMCC::HI)
6475       .addReg(ARM::CPSR);
6476
6477     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6478     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6479                    .addJumpTableIndex(MJTI)
6480                    .addImm(UId));
6481
6482     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6483     AddDefaultCC(
6484       AddDefaultPred(
6485         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6486         .addReg(NewVReg3, RegState::Kill)
6487         .addReg(NewVReg1)
6488         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6489
6490     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6491       .addReg(NewVReg4, RegState::Kill)
6492       .addReg(NewVReg1)
6493       .addJumpTableIndex(MJTI)
6494       .addImm(UId);
6495   } else if (Subtarget->isThumb()) {
6496     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6497     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6498                    .addFrameIndex(FI)
6499                    .addImm(1)
6500                    .addMemOperand(FIMMOLd));
6501
6502     if (NumLPads < 256) {
6503       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6504                      .addReg(NewVReg1)
6505                      .addImm(NumLPads));
6506     } else {
6507       MachineConstantPool *ConstantPool = MF->getConstantPool();
6508       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6509       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6510
6511       // MachineConstantPool wants an explicit alignment.
6512       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6513       if (Align == 0)
6514         Align = getDataLayout()->getTypeAllocSize(C->getType());
6515       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6516
6517       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6518       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6519                      .addReg(VReg1, RegState::Define)
6520                      .addConstantPoolIndex(Idx));
6521       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6522                      .addReg(NewVReg1)
6523                      .addReg(VReg1));
6524     }
6525
6526     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6527       .addMBB(TrapBB)
6528       .addImm(ARMCC::HI)
6529       .addReg(ARM::CPSR);
6530
6531     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6532     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6533                    .addReg(ARM::CPSR, RegState::Define)
6534                    .addReg(NewVReg1)
6535                    .addImm(2));
6536
6537     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6538     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6539                    .addJumpTableIndex(MJTI)
6540                    .addImm(UId));
6541
6542     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6543     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6544                    .addReg(ARM::CPSR, RegState::Define)
6545                    .addReg(NewVReg2, RegState::Kill)
6546                    .addReg(NewVReg3));
6547
6548     MachineMemOperand *JTMMOLd =
6549       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6550                                MachineMemOperand::MOLoad, 4, 4);
6551
6552     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6553     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6554                    .addReg(NewVReg4, RegState::Kill)
6555                    .addImm(0)
6556                    .addMemOperand(JTMMOLd));
6557
6558     unsigned NewVReg6 = NewVReg5;
6559     if (RelocM == Reloc::PIC_) {
6560       NewVReg6 = MRI->createVirtualRegister(TRC);
6561       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6562                      .addReg(ARM::CPSR, RegState::Define)
6563                      .addReg(NewVReg5, RegState::Kill)
6564                      .addReg(NewVReg3));
6565     }
6566
6567     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6568       .addReg(NewVReg6, RegState::Kill)
6569       .addJumpTableIndex(MJTI)
6570       .addImm(UId);
6571   } else {
6572     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6573     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6574                    .addFrameIndex(FI)
6575                    .addImm(4)
6576                    .addMemOperand(FIMMOLd));
6577
6578     if (NumLPads < 256) {
6579       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6580                      .addReg(NewVReg1)
6581                      .addImm(NumLPads));
6582     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6583       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6584       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6585                      .addImm(NumLPads & 0xFFFF));
6586
6587       unsigned VReg2 = VReg1;
6588       if ((NumLPads & 0xFFFF0000) != 0) {
6589         VReg2 = MRI->createVirtualRegister(TRC);
6590         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6591                        .addReg(VReg1)
6592                        .addImm(NumLPads >> 16));
6593       }
6594
6595       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6596                      .addReg(NewVReg1)
6597                      .addReg(VReg2));
6598     } else {
6599       MachineConstantPool *ConstantPool = MF->getConstantPool();
6600       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6601       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6602
6603       // MachineConstantPool wants an explicit alignment.
6604       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6605       if (Align == 0)
6606         Align = getDataLayout()->getTypeAllocSize(C->getType());
6607       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6608
6609       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6610       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6611                      .addReg(VReg1, RegState::Define)
6612                      .addConstantPoolIndex(Idx)
6613                      .addImm(0));
6614       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6615                      .addReg(NewVReg1)
6616                      .addReg(VReg1, RegState::Kill));
6617     }
6618
6619     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6620       .addMBB(TrapBB)
6621       .addImm(ARMCC::HI)
6622       .addReg(ARM::CPSR);
6623
6624     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6625     AddDefaultCC(
6626       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6627                      .addReg(NewVReg1)
6628                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6629     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6630     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6631                    .addJumpTableIndex(MJTI)
6632                    .addImm(UId));
6633
6634     MachineMemOperand *JTMMOLd =
6635       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6636                                MachineMemOperand::MOLoad, 4, 4);
6637     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6638     AddDefaultPred(
6639       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6640       .addReg(NewVReg3, RegState::Kill)
6641       .addReg(NewVReg4)
6642       .addImm(0)
6643       .addMemOperand(JTMMOLd));
6644
6645     if (RelocM == Reloc::PIC_) {
6646       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6647         .addReg(NewVReg5, RegState::Kill)
6648         .addReg(NewVReg4)
6649         .addJumpTableIndex(MJTI)
6650         .addImm(UId);
6651     } else {
6652       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6653         .addReg(NewVReg5, RegState::Kill)
6654         .addJumpTableIndex(MJTI)
6655         .addImm(UId);
6656     }
6657   }
6658
6659   // Add the jump table entries as successors to the MBB.
6660   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6661   for (std::vector<MachineBasicBlock*>::iterator
6662          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6663     MachineBasicBlock *CurMBB = *I;
6664     if (SeenMBBs.insert(CurMBB))
6665       DispContBB->addSuccessor(CurMBB);
6666   }
6667
6668   // N.B. the order the invoke BBs are processed in doesn't matter here.
6669   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6670   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6671   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6672          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6673     MachineBasicBlock *BB = *I;
6674
6675     // Remove the landing pad successor from the invoke block and replace it
6676     // with the new dispatch block.
6677     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6678                                                   BB->succ_end());
6679     while (!Successors.empty()) {
6680       MachineBasicBlock *SMBB = Successors.pop_back_val();
6681       if (SMBB->isLandingPad()) {
6682         BB->removeSuccessor(SMBB);
6683         MBBLPads.push_back(SMBB);
6684       }
6685     }
6686
6687     BB->addSuccessor(DispatchBB);
6688
6689     // Find the invoke call and mark all of the callee-saved registers as
6690     // 'implicit defined' so that they're spilled. This prevents code from
6691     // moving instructions to before the EH block, where they will never be
6692     // executed.
6693     for (MachineBasicBlock::reverse_iterator
6694            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6695       if (!II->isCall()) continue;
6696
6697       DenseMap<unsigned, bool> DefRegs;
6698       for (MachineInstr::mop_iterator
6699              OI = II->operands_begin(), OE = II->operands_end();
6700            OI != OE; ++OI) {
6701         if (!OI->isReg()) continue;
6702         DefRegs[OI->getReg()] = true;
6703       }
6704
6705       MachineInstrBuilder MIB(*MF, &*II);
6706
6707       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6708         unsigned Reg = SavedRegs[i];
6709         if (Subtarget->isThumb2() &&
6710             !ARM::tGPRRegClass.contains(Reg) &&
6711             !ARM::hGPRRegClass.contains(Reg))
6712           continue;
6713         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6714           continue;
6715         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6716           continue;
6717         if (!DefRegs[Reg])
6718           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6719       }
6720
6721       break;
6722     }
6723   }
6724
6725   // Mark all former landing pads as non-landing pads. The dispatch is the only
6726   // landing pad now.
6727   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6728          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6729     (*I)->setIsLandingPad(false);
6730
6731   // The instruction is gone now.
6732   MI->eraseFromParent();
6733
6734   return MBB;
6735 }
6736
6737 static
6738 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6739   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6740        E = MBB->succ_end(); I != E; ++I)
6741     if (*I != Succ)
6742       return *I;
6743   llvm_unreachable("Expecting a BB with two successors!");
6744 }
6745
6746 MachineBasicBlock *ARMTargetLowering::
6747 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6748   // This pseudo instruction has 3 operands: dst, src, size
6749   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6750   // Otherwise, we will generate unrolled scalar copies.
6751   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6752   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6753   MachineFunction::iterator It = BB;
6754   ++It;
6755
6756   unsigned dest = MI->getOperand(0).getReg();
6757   unsigned src = MI->getOperand(1).getReg();
6758   unsigned SizeVal = MI->getOperand(2).getImm();
6759   unsigned Align = MI->getOperand(3).getImm();
6760   DebugLoc dl = MI->getDebugLoc();
6761
6762   bool isThumb2 = Subtarget->isThumb2();
6763   MachineFunction *MF = BB->getParent();
6764   MachineRegisterInfo &MRI = MF->getRegInfo();
6765   unsigned ldrOpc, strOpc, UnitSize = 0;
6766
6767   const TargetRegisterClass *TRC = isThumb2 ?
6768     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6769     (const TargetRegisterClass*)&ARM::GPRRegClass;
6770   const TargetRegisterClass *TRC_Vec = 0;
6771
6772   if (Align & 1) {
6773     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6774     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6775     UnitSize = 1;
6776   } else if (Align & 2) {
6777     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6778     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6779     UnitSize = 2;
6780   } else {
6781     // Check whether we can use NEON instructions.
6782     if (!MF->getFunction()->getAttributes().
6783           hasAttribute(AttributeSet::FunctionIndex,
6784                        Attribute::NoImplicitFloat) &&
6785         Subtarget->hasNEON()) {
6786       if ((Align % 16 == 0) && SizeVal >= 16) {
6787         ldrOpc = ARM::VLD1q32wb_fixed;
6788         strOpc = ARM::VST1q32wb_fixed;
6789         UnitSize = 16;
6790         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6791       }
6792       else if ((Align % 8 == 0) && SizeVal >= 8) {
6793         ldrOpc = ARM::VLD1d32wb_fixed;
6794         strOpc = ARM::VST1d32wb_fixed;
6795         UnitSize = 8;
6796         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6797       }
6798     }
6799     // Can't use NEON instructions.
6800     if (UnitSize == 0) {
6801       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6802       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6803       UnitSize = 4;
6804     }
6805   }
6806
6807   unsigned BytesLeft = SizeVal % UnitSize;
6808   unsigned LoopSize = SizeVal - BytesLeft;
6809
6810   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6811     // Use LDR and STR to copy.
6812     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6813     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6814     unsigned srcIn = src;
6815     unsigned destIn = dest;
6816     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6817       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6818       unsigned srcOut = MRI.createVirtualRegister(TRC);
6819       unsigned destOut = MRI.createVirtualRegister(TRC);
6820       if (UnitSize >= 8) {
6821         AddDefaultPred(BuildMI(*BB, MI, dl,
6822           TII->get(ldrOpc), scratch)
6823           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6824
6825         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6826           .addReg(destIn).addImm(0).addReg(scratch));
6827       } else if (isThumb2) {
6828         AddDefaultPred(BuildMI(*BB, MI, dl,
6829           TII->get(ldrOpc), scratch)
6830           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6831
6832         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6833           .addReg(scratch).addReg(destIn)
6834           .addImm(UnitSize));
6835       } else {
6836         AddDefaultPred(BuildMI(*BB, MI, dl,
6837           TII->get(ldrOpc), scratch)
6838           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6839           .addImm(UnitSize));
6840
6841         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6842           .addReg(scratch).addReg(destIn)
6843           .addReg(0).addImm(UnitSize));
6844       }
6845       srcIn = srcOut;
6846       destIn = destOut;
6847     }
6848
6849     // Handle the leftover bytes with LDRB and STRB.
6850     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6851     // [destOut] = STRB_POST(scratch, destIn, 1)
6852     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6853     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6854     for (unsigned i = 0; i < BytesLeft; i++) {
6855       unsigned scratch = MRI.createVirtualRegister(TRC);
6856       unsigned srcOut = MRI.createVirtualRegister(TRC);
6857       unsigned destOut = MRI.createVirtualRegister(TRC);
6858       if (isThumb2) {
6859         AddDefaultPred(BuildMI(*BB, MI, dl,
6860           TII->get(ldrOpc),scratch)
6861           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6862
6863         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6864           .addReg(scratch).addReg(destIn)
6865           .addReg(0).addImm(1));
6866       } else {
6867         AddDefaultPred(BuildMI(*BB, MI, dl,
6868           TII->get(ldrOpc),scratch)
6869           .addReg(srcOut, RegState::Define).addReg(srcIn)
6870           .addReg(0).addImm(1));
6871
6872         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6873           .addReg(scratch).addReg(destIn)
6874           .addReg(0).addImm(1));
6875       }
6876       srcIn = srcOut;
6877       destIn = destOut;
6878     }
6879     MI->eraseFromParent();   // The instruction is gone now.
6880     return BB;
6881   }
6882
6883   // Expand the pseudo op to a loop.
6884   // thisMBB:
6885   //   ...
6886   //   movw varEnd, # --> with thumb2
6887   //   movt varEnd, #
6888   //   ldrcp varEnd, idx --> without thumb2
6889   //   fallthrough --> loopMBB
6890   // loopMBB:
6891   //   PHI varPhi, varEnd, varLoop
6892   //   PHI srcPhi, src, srcLoop
6893   //   PHI destPhi, dst, destLoop
6894   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6895   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6896   //   subs varLoop, varPhi, #UnitSize
6897   //   bne loopMBB
6898   //   fallthrough --> exitMBB
6899   // exitMBB:
6900   //   epilogue to handle left-over bytes
6901   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6902   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6903   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6904   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6905   MF->insert(It, loopMBB);
6906   MF->insert(It, exitMBB);
6907
6908   // Transfer the remainder of BB and its successor edges to exitMBB.
6909   exitMBB->splice(exitMBB->begin(), BB,
6910                   llvm::next(MachineBasicBlock::iterator(MI)),
6911                   BB->end());
6912   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6913
6914   // Load an immediate to varEnd.
6915   unsigned varEnd = MRI.createVirtualRegister(TRC);
6916   if (isThumb2) {
6917     unsigned VReg1 = varEnd;
6918     if ((LoopSize & 0xFFFF0000) != 0)
6919       VReg1 = MRI.createVirtualRegister(TRC);
6920     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6921                    .addImm(LoopSize & 0xFFFF));
6922
6923     if ((LoopSize & 0xFFFF0000) != 0)
6924       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6925                      .addReg(VReg1)
6926                      .addImm(LoopSize >> 16));
6927   } else {
6928     MachineConstantPool *ConstantPool = MF->getConstantPool();
6929     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6930     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6931
6932     // MachineConstantPool wants an explicit alignment.
6933     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6934     if (Align == 0)
6935       Align = getDataLayout()->getTypeAllocSize(C->getType());
6936     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6937
6938     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6939                    .addReg(varEnd, RegState::Define)
6940                    .addConstantPoolIndex(Idx)
6941                    .addImm(0));
6942   }
6943   BB->addSuccessor(loopMBB);
6944
6945   // Generate the loop body:
6946   //   varPhi = PHI(varLoop, varEnd)
6947   //   srcPhi = PHI(srcLoop, src)
6948   //   destPhi = PHI(destLoop, dst)
6949   MachineBasicBlock *entryBB = BB;
6950   BB = loopMBB;
6951   unsigned varLoop = MRI.createVirtualRegister(TRC);
6952   unsigned varPhi = MRI.createVirtualRegister(TRC);
6953   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6954   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6955   unsigned destLoop = MRI.createVirtualRegister(TRC);
6956   unsigned destPhi = MRI.createVirtualRegister(TRC);
6957
6958   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6959     .addReg(varLoop).addMBB(loopMBB)
6960     .addReg(varEnd).addMBB(entryBB);
6961   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6962     .addReg(srcLoop).addMBB(loopMBB)
6963     .addReg(src).addMBB(entryBB);
6964   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6965     .addReg(destLoop).addMBB(loopMBB)
6966     .addReg(dest).addMBB(entryBB);
6967
6968   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6969   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6970   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6971   if (UnitSize >= 8) {
6972     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6973       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6974
6975     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6976       .addReg(destPhi).addImm(0).addReg(scratch));
6977   } else if (isThumb2) {
6978     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6979       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6980
6981     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6982       .addReg(scratch).addReg(destPhi)
6983       .addImm(UnitSize));
6984   } else {
6985     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6986       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6987       .addImm(UnitSize));
6988
6989     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6990       .addReg(scratch).addReg(destPhi)
6991       .addReg(0).addImm(UnitSize));
6992   }
6993
6994   // Decrement loop variable by UnitSize.
6995   MachineInstrBuilder MIB = BuildMI(BB, dl,
6996     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6997   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6998   MIB->getOperand(5).setReg(ARM::CPSR);
6999   MIB->getOperand(5).setIsDef(true);
7000
7001   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7002     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7003
7004   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7005   BB->addSuccessor(loopMBB);
7006   BB->addSuccessor(exitMBB);
7007
7008   // Add epilogue to handle BytesLeft.
7009   BB = exitMBB;
7010   MachineInstr *StartOfExit = exitMBB->begin();
7011   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7012   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7013
7014   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7015   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7016   unsigned srcIn = srcLoop;
7017   unsigned destIn = destLoop;
7018   for (unsigned i = 0; i < BytesLeft; i++) {
7019     unsigned scratch = MRI.createVirtualRegister(TRC);
7020     unsigned srcOut = MRI.createVirtualRegister(TRC);
7021     unsigned destOut = MRI.createVirtualRegister(TRC);
7022     if (isThumb2) {
7023       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7024         TII->get(ldrOpc),scratch)
7025         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7026
7027       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7028         .addReg(scratch).addReg(destIn)
7029         .addImm(1));
7030     } else {
7031       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7032         TII->get(ldrOpc),scratch)
7033         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7034
7035       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7036         .addReg(scratch).addReg(destIn)
7037         .addReg(0).addImm(1));
7038     }
7039     srcIn = srcOut;
7040     destIn = destOut;
7041   }
7042
7043   MI->eraseFromParent();   // The instruction is gone now.
7044   return BB;
7045 }
7046
7047 MachineBasicBlock *
7048 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7049                                                MachineBasicBlock *BB) const {
7050   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7051   DebugLoc dl = MI->getDebugLoc();
7052   bool isThumb2 = Subtarget->isThumb2();
7053   switch (MI->getOpcode()) {
7054   default: {
7055     MI->dump();
7056     llvm_unreachable("Unexpected instr type to insert");
7057   }
7058   // The Thumb2 pre-indexed stores have the same MI operands, they just
7059   // define them differently in the .td files from the isel patterns, so
7060   // they need pseudos.
7061   case ARM::t2STR_preidx:
7062     MI->setDesc(TII->get(ARM::t2STR_PRE));
7063     return BB;
7064   case ARM::t2STRB_preidx:
7065     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7066     return BB;
7067   case ARM::t2STRH_preidx:
7068     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7069     return BB;
7070
7071   case ARM::STRi_preidx:
7072   case ARM::STRBi_preidx: {
7073     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7074       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7075     // Decode the offset.
7076     unsigned Offset = MI->getOperand(4).getImm();
7077     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7078     Offset = ARM_AM::getAM2Offset(Offset);
7079     if (isSub)
7080       Offset = -Offset;
7081
7082     MachineMemOperand *MMO = *MI->memoperands_begin();
7083     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7084       .addOperand(MI->getOperand(0))  // Rn_wb
7085       .addOperand(MI->getOperand(1))  // Rt
7086       .addOperand(MI->getOperand(2))  // Rn
7087       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7088       .addOperand(MI->getOperand(5))  // pred
7089       .addOperand(MI->getOperand(6))
7090       .addMemOperand(MMO);
7091     MI->eraseFromParent();
7092     return BB;
7093   }
7094   case ARM::STRr_preidx:
7095   case ARM::STRBr_preidx:
7096   case ARM::STRH_preidx: {
7097     unsigned NewOpc;
7098     switch (MI->getOpcode()) {
7099     default: llvm_unreachable("unexpected opcode!");
7100     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7101     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7102     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7103     }
7104     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7105     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7106       MIB.addOperand(MI->getOperand(i));
7107     MI->eraseFromParent();
7108     return BB;
7109   }
7110   case ARM::ATOMIC_LOAD_ADD_I8:
7111      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7112   case ARM::ATOMIC_LOAD_ADD_I16:
7113      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7114   case ARM::ATOMIC_LOAD_ADD_I32:
7115      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7116
7117   case ARM::ATOMIC_LOAD_AND_I8:
7118      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7119   case ARM::ATOMIC_LOAD_AND_I16:
7120      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7121   case ARM::ATOMIC_LOAD_AND_I32:
7122      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7123
7124   case ARM::ATOMIC_LOAD_OR_I8:
7125      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7126   case ARM::ATOMIC_LOAD_OR_I16:
7127      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7128   case ARM::ATOMIC_LOAD_OR_I32:
7129      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7130
7131   case ARM::ATOMIC_LOAD_XOR_I8:
7132      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7133   case ARM::ATOMIC_LOAD_XOR_I16:
7134      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7135   case ARM::ATOMIC_LOAD_XOR_I32:
7136      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7137
7138   case ARM::ATOMIC_LOAD_NAND_I8:
7139      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7140   case ARM::ATOMIC_LOAD_NAND_I16:
7141      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7142   case ARM::ATOMIC_LOAD_NAND_I32:
7143      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7144
7145   case ARM::ATOMIC_LOAD_SUB_I8:
7146      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7147   case ARM::ATOMIC_LOAD_SUB_I16:
7148      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7149   case ARM::ATOMIC_LOAD_SUB_I32:
7150      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7151
7152   case ARM::ATOMIC_LOAD_MIN_I8:
7153      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7154   case ARM::ATOMIC_LOAD_MIN_I16:
7155      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7156   case ARM::ATOMIC_LOAD_MIN_I32:
7157      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7158
7159   case ARM::ATOMIC_LOAD_MAX_I8:
7160      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7161   case ARM::ATOMIC_LOAD_MAX_I16:
7162      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7163   case ARM::ATOMIC_LOAD_MAX_I32:
7164      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7165
7166   case ARM::ATOMIC_LOAD_UMIN_I8:
7167      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7168   case ARM::ATOMIC_LOAD_UMIN_I16:
7169      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7170   case ARM::ATOMIC_LOAD_UMIN_I32:
7171      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7172
7173   case ARM::ATOMIC_LOAD_UMAX_I8:
7174      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7175   case ARM::ATOMIC_LOAD_UMAX_I16:
7176      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7177   case ARM::ATOMIC_LOAD_UMAX_I32:
7178      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7179
7180   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7181   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7182   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7183
7184   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7185   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7186   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7187
7188
7189   case ARM::ATOMADD6432:
7190     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7191                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7192                               /*NeedsCarry*/ true);
7193   case ARM::ATOMSUB6432:
7194     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7195                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7196                               /*NeedsCarry*/ true);
7197   case ARM::ATOMOR6432:
7198     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7199                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7200   case ARM::ATOMXOR6432:
7201     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7202                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7203   case ARM::ATOMAND6432:
7204     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7205                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7206   case ARM::ATOMSWAP6432:
7207     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7208   case ARM::ATOMCMPXCHG6432:
7209     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7210                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7211                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7212   case ARM::ATOMMIN6432:
7213     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7214                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7215                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7216                               /*IsMinMax*/ true, ARMCC::LT);
7217   case ARM::ATOMMAX6432:
7218     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7219                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7220                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7221                               /*IsMinMax*/ true, ARMCC::GE);
7222   case ARM::ATOMUMIN6432:
7223     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7224                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7225                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7226                               /*IsMinMax*/ true, ARMCC::LO);
7227   case ARM::ATOMUMAX6432:
7228     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7229                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7230                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7231                               /*IsMinMax*/ true, ARMCC::HS);
7232
7233   case ARM::tMOVCCr_pseudo: {
7234     // To "insert" a SELECT_CC instruction, we actually have to insert the
7235     // diamond control-flow pattern.  The incoming instruction knows the
7236     // destination vreg to set, the condition code register to branch on, the
7237     // true/false values to select between, and a branch opcode to use.
7238     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7239     MachineFunction::iterator It = BB;
7240     ++It;
7241
7242     //  thisMBB:
7243     //  ...
7244     //   TrueVal = ...
7245     //   cmpTY ccX, r1, r2
7246     //   bCC copy1MBB
7247     //   fallthrough --> copy0MBB
7248     MachineBasicBlock *thisMBB  = BB;
7249     MachineFunction *F = BB->getParent();
7250     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7251     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7252     F->insert(It, copy0MBB);
7253     F->insert(It, sinkMBB);
7254
7255     // Transfer the remainder of BB and its successor edges to sinkMBB.
7256     sinkMBB->splice(sinkMBB->begin(), BB,
7257                     llvm::next(MachineBasicBlock::iterator(MI)),
7258                     BB->end());
7259     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7260
7261     BB->addSuccessor(copy0MBB);
7262     BB->addSuccessor(sinkMBB);
7263
7264     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7265       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7266
7267     //  copy0MBB:
7268     //   %FalseValue = ...
7269     //   # fallthrough to sinkMBB
7270     BB = copy0MBB;
7271
7272     // Update machine-CFG edges
7273     BB->addSuccessor(sinkMBB);
7274
7275     //  sinkMBB:
7276     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7277     //  ...
7278     BB = sinkMBB;
7279     BuildMI(*BB, BB->begin(), dl,
7280             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7281       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7282       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7283
7284     MI->eraseFromParent();   // The pseudo instruction is gone now.
7285     return BB;
7286   }
7287
7288   case ARM::BCCi64:
7289   case ARM::BCCZi64: {
7290     // If there is an unconditional branch to the other successor, remove it.
7291     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7292
7293     // Compare both parts that make up the double comparison separately for
7294     // equality.
7295     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7296
7297     unsigned LHS1 = MI->getOperand(1).getReg();
7298     unsigned LHS2 = MI->getOperand(2).getReg();
7299     if (RHSisZero) {
7300       AddDefaultPred(BuildMI(BB, dl,
7301                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7302                      .addReg(LHS1).addImm(0));
7303       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7304         .addReg(LHS2).addImm(0)
7305         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7306     } else {
7307       unsigned RHS1 = MI->getOperand(3).getReg();
7308       unsigned RHS2 = MI->getOperand(4).getReg();
7309       AddDefaultPred(BuildMI(BB, dl,
7310                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7311                      .addReg(LHS1).addReg(RHS1));
7312       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7313         .addReg(LHS2).addReg(RHS2)
7314         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7315     }
7316
7317     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7318     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7319     if (MI->getOperand(0).getImm() == ARMCC::NE)
7320       std::swap(destMBB, exitMBB);
7321
7322     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7323       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7324     if (isThumb2)
7325       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7326     else
7327       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7328
7329     MI->eraseFromParent();   // The pseudo instruction is gone now.
7330     return BB;
7331   }
7332
7333   case ARM::Int_eh_sjlj_setjmp:
7334   case ARM::Int_eh_sjlj_setjmp_nofp:
7335   case ARM::tInt_eh_sjlj_setjmp:
7336   case ARM::t2Int_eh_sjlj_setjmp:
7337   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7338     EmitSjLjDispatchBlock(MI, BB);
7339     return BB;
7340
7341   case ARM::ABS:
7342   case ARM::t2ABS: {
7343     // To insert an ABS instruction, we have to insert the
7344     // diamond control-flow pattern.  The incoming instruction knows the
7345     // source vreg to test against 0, the destination vreg to set,
7346     // the condition code register to branch on, the
7347     // true/false values to select between, and a branch opcode to use.
7348     // It transforms
7349     //     V1 = ABS V0
7350     // into
7351     //     V2 = MOVS V0
7352     //     BCC                      (branch to SinkBB if V0 >= 0)
7353     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7354     //     SinkBB: V1 = PHI(V2, V3)
7355     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7356     MachineFunction::iterator BBI = BB;
7357     ++BBI;
7358     MachineFunction *Fn = BB->getParent();
7359     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7360     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7361     Fn->insert(BBI, RSBBB);
7362     Fn->insert(BBI, SinkBB);
7363
7364     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7365     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7366     bool isThumb2 = Subtarget->isThumb2();
7367     MachineRegisterInfo &MRI = Fn->getRegInfo();
7368     // In Thumb mode S must not be specified if source register is the SP or
7369     // PC and if destination register is the SP, so restrict register class
7370     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7371       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7372       (const TargetRegisterClass*)&ARM::GPRRegClass);
7373
7374     // Transfer the remainder of BB and its successor edges to sinkMBB.
7375     SinkBB->splice(SinkBB->begin(), BB,
7376       llvm::next(MachineBasicBlock::iterator(MI)),
7377       BB->end());
7378     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7379
7380     BB->addSuccessor(RSBBB);
7381     BB->addSuccessor(SinkBB);
7382
7383     // fall through to SinkMBB
7384     RSBBB->addSuccessor(SinkBB);
7385
7386     // insert a cmp at the end of BB
7387     AddDefaultPred(BuildMI(BB, dl,
7388                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7389                    .addReg(ABSSrcReg).addImm(0));
7390
7391     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7392     BuildMI(BB, dl,
7393       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7394       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7395
7396     // insert rsbri in RSBBB
7397     // Note: BCC and rsbri will be converted into predicated rsbmi
7398     // by if-conversion pass
7399     BuildMI(*RSBBB, RSBBB->begin(), dl,
7400       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7401       .addReg(ABSSrcReg, RegState::Kill)
7402       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7403
7404     // insert PHI in SinkBB,
7405     // reuse ABSDstReg to not change uses of ABS instruction
7406     BuildMI(*SinkBB, SinkBB->begin(), dl,
7407       TII->get(ARM::PHI), ABSDstReg)
7408       .addReg(NewRsbDstReg).addMBB(RSBBB)
7409       .addReg(ABSSrcReg).addMBB(BB);
7410
7411     // remove ABS instruction
7412     MI->eraseFromParent();
7413
7414     // return last added BB
7415     return SinkBB;
7416   }
7417   case ARM::COPY_STRUCT_BYVAL_I32:
7418     ++NumLoopByVals;
7419     return EmitStructByval(MI, BB);
7420   }
7421 }
7422
7423 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7424                                                       SDNode *Node) const {
7425   if (!MI->hasPostISelHook()) {
7426     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7427            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7428     return;
7429   }
7430
7431   const MCInstrDesc *MCID = &MI->getDesc();
7432   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7433   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7434   // operand is still set to noreg. If needed, set the optional operand's
7435   // register to CPSR, and remove the redundant implicit def.
7436   //
7437   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7438
7439   // Rename pseudo opcodes.
7440   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7441   if (NewOpc) {
7442     const ARMBaseInstrInfo *TII =
7443       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7444     MCID = &TII->get(NewOpc);
7445
7446     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7447            "converted opcode should be the same except for cc_out");
7448
7449     MI->setDesc(*MCID);
7450
7451     // Add the optional cc_out operand
7452     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7453   }
7454   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7455
7456   // Any ARM instruction that sets the 's' bit should specify an optional
7457   // "cc_out" operand in the last operand position.
7458   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7459     assert(!NewOpc && "Optional cc_out operand required");
7460     return;
7461   }
7462   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7463   // since we already have an optional CPSR def.
7464   bool definesCPSR = false;
7465   bool deadCPSR = false;
7466   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7467        i != e; ++i) {
7468     const MachineOperand &MO = MI->getOperand(i);
7469     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7470       definesCPSR = true;
7471       if (MO.isDead())
7472         deadCPSR = true;
7473       MI->RemoveOperand(i);
7474       break;
7475     }
7476   }
7477   if (!definesCPSR) {
7478     assert(!NewOpc && "Optional cc_out operand required");
7479     return;
7480   }
7481   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7482   if (deadCPSR) {
7483     assert(!MI->getOperand(ccOutIdx).getReg() &&
7484            "expect uninitialized optional cc_out operand");
7485     return;
7486   }
7487
7488   // If this instruction was defined with an optional CPSR def and its dag node
7489   // had a live implicit CPSR def, then activate the optional CPSR def.
7490   MachineOperand &MO = MI->getOperand(ccOutIdx);
7491   MO.setReg(ARM::CPSR);
7492   MO.setIsDef(true);
7493 }
7494
7495 //===----------------------------------------------------------------------===//
7496 //                           ARM Optimization Hooks
7497 //===----------------------------------------------------------------------===//
7498
7499 // Helper function that checks if N is a null or all ones constant.
7500 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7501   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7502   if (!C)
7503     return false;
7504   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7505 }
7506
7507 // Return true if N is conditionally 0 or all ones.
7508 // Detects these expressions where cc is an i1 value:
7509 //
7510 //   (select cc 0, y)   [AllOnes=0]
7511 //   (select cc y, 0)   [AllOnes=0]
7512 //   (zext cc)          [AllOnes=0]
7513 //   (sext cc)          [AllOnes=0/1]
7514 //   (select cc -1, y)  [AllOnes=1]
7515 //   (select cc y, -1)  [AllOnes=1]
7516 //
7517 // Invert is set when N is the null/all ones constant when CC is false.
7518 // OtherOp is set to the alternative value of N.
7519 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7520                                        SDValue &CC, bool &Invert,
7521                                        SDValue &OtherOp,
7522                                        SelectionDAG &DAG) {
7523   switch (N->getOpcode()) {
7524   default: return false;
7525   case ISD::SELECT: {
7526     CC = N->getOperand(0);
7527     SDValue N1 = N->getOperand(1);
7528     SDValue N2 = N->getOperand(2);
7529     if (isZeroOrAllOnes(N1, AllOnes)) {
7530       Invert = false;
7531       OtherOp = N2;
7532       return true;
7533     }
7534     if (isZeroOrAllOnes(N2, AllOnes)) {
7535       Invert = true;
7536       OtherOp = N1;
7537       return true;
7538     }
7539     return false;
7540   }
7541   case ISD::ZERO_EXTEND:
7542     // (zext cc) can never be the all ones value.
7543     if (AllOnes)
7544       return false;
7545     // Fall through.
7546   case ISD::SIGN_EXTEND: {
7547     EVT VT = N->getValueType(0);
7548     CC = N->getOperand(0);
7549     if (CC.getValueType() != MVT::i1)
7550       return false;
7551     Invert = !AllOnes;
7552     if (AllOnes)
7553       // When looking for an AllOnes constant, N is an sext, and the 'other'
7554       // value is 0.
7555       OtherOp = DAG.getConstant(0, VT);
7556     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7557       // When looking for a 0 constant, N can be zext or sext.
7558       OtherOp = DAG.getConstant(1, VT);
7559     else
7560       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7561     return true;
7562   }
7563   }
7564 }
7565
7566 // Combine a constant select operand into its use:
7567 //
7568 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7569 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7570 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7571 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7572 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7573 //
7574 // The transform is rejected if the select doesn't have a constant operand that
7575 // is null, or all ones when AllOnes is set.
7576 //
7577 // Also recognize sext/zext from i1:
7578 //
7579 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7580 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7581 //
7582 // These transformations eventually create predicated instructions.
7583 //
7584 // @param N       The node to transform.
7585 // @param Slct    The N operand that is a select.
7586 // @param OtherOp The other N operand (x above).
7587 // @param DCI     Context.
7588 // @param AllOnes Require the select constant to be all ones instead of null.
7589 // @returns The new node, or SDValue() on failure.
7590 static
7591 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7592                             TargetLowering::DAGCombinerInfo &DCI,
7593                             bool AllOnes = false) {
7594   SelectionDAG &DAG = DCI.DAG;
7595   EVT VT = N->getValueType(0);
7596   SDValue NonConstantVal;
7597   SDValue CCOp;
7598   bool SwapSelectOps;
7599   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7600                                   NonConstantVal, DAG))
7601     return SDValue();
7602
7603   // Slct is now know to be the desired identity constant when CC is true.
7604   SDValue TrueVal = OtherOp;
7605   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7606                                  OtherOp, NonConstantVal);
7607   // Unless SwapSelectOps says CC should be false.
7608   if (SwapSelectOps)
7609     std::swap(TrueVal, FalseVal);
7610
7611   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7612                      CCOp, TrueVal, FalseVal);
7613 }
7614
7615 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7616 static
7617 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7618                                        TargetLowering::DAGCombinerInfo &DCI) {
7619   SDValue N0 = N->getOperand(0);
7620   SDValue N1 = N->getOperand(1);
7621   if (N0.getNode()->hasOneUse()) {
7622     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7623     if (Result.getNode())
7624       return Result;
7625   }
7626   if (N1.getNode()->hasOneUse()) {
7627     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7628     if (Result.getNode())
7629       return Result;
7630   }
7631   return SDValue();
7632 }
7633
7634 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7635 // (only after legalization).
7636 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7637                                  TargetLowering::DAGCombinerInfo &DCI,
7638                                  const ARMSubtarget *Subtarget) {
7639
7640   // Only perform optimization if after legalize, and if NEON is available. We
7641   // also expected both operands to be BUILD_VECTORs.
7642   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7643       || N0.getOpcode() != ISD::BUILD_VECTOR
7644       || N1.getOpcode() != ISD::BUILD_VECTOR)
7645     return SDValue();
7646
7647   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7648   EVT VT = N->getValueType(0);
7649   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7650     return SDValue();
7651
7652   // Check that the vector operands are of the right form.
7653   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7654   // operands, where N is the size of the formed vector.
7655   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7656   // index such that we have a pair wise add pattern.
7657
7658   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7659   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7660     return SDValue();
7661   SDValue Vec = N0->getOperand(0)->getOperand(0);
7662   SDNode *V = Vec.getNode();
7663   unsigned nextIndex = 0;
7664
7665   // For each operands to the ADD which are BUILD_VECTORs,
7666   // check to see if each of their operands are an EXTRACT_VECTOR with
7667   // the same vector and appropriate index.
7668   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7669     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7670         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7671
7672       SDValue ExtVec0 = N0->getOperand(i);
7673       SDValue ExtVec1 = N1->getOperand(i);
7674
7675       // First operand is the vector, verify its the same.
7676       if (V != ExtVec0->getOperand(0).getNode() ||
7677           V != ExtVec1->getOperand(0).getNode())
7678         return SDValue();
7679
7680       // Second is the constant, verify its correct.
7681       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7682       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7683
7684       // For the constant, we want to see all the even or all the odd.
7685       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7686           || C1->getZExtValue() != nextIndex+1)
7687         return SDValue();
7688
7689       // Increment index.
7690       nextIndex+=2;
7691     } else
7692       return SDValue();
7693   }
7694
7695   // Create VPADDL node.
7696   SelectionDAG &DAG = DCI.DAG;
7697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7698
7699   // Build operand list.
7700   SmallVector<SDValue, 8> Ops;
7701   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7702                                 TLI.getPointerTy()));
7703
7704   // Input is the vector.
7705   Ops.push_back(Vec);
7706
7707   // Get widened type and narrowed type.
7708   MVT widenType;
7709   unsigned numElem = VT.getVectorNumElements();
7710   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7711     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7712     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7713     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7714     default:
7715       llvm_unreachable("Invalid vector element type for padd optimization.");
7716   }
7717
7718   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7719                             widenType, &Ops[0], Ops.size());
7720   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7721 }
7722
7723 static SDValue findMUL_LOHI(SDValue V) {
7724   if (V->getOpcode() == ISD::UMUL_LOHI ||
7725       V->getOpcode() == ISD::SMUL_LOHI)
7726     return V;
7727   return SDValue();
7728 }
7729
7730 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7731                                      TargetLowering::DAGCombinerInfo &DCI,
7732                                      const ARMSubtarget *Subtarget) {
7733
7734   if (Subtarget->isThumb1Only()) return SDValue();
7735
7736   // Only perform the checks after legalize when the pattern is available.
7737   if (DCI.isBeforeLegalize()) return SDValue();
7738
7739   // Look for multiply add opportunities.
7740   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7741   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7742   // a glue link from the first add to the second add.
7743   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7744   // a S/UMLAL instruction.
7745   //          loAdd   UMUL_LOHI
7746   //            \    / :lo    \ :hi
7747   //             \  /          \          [no multiline comment]
7748   //              ADDC         |  hiAdd
7749   //                 \ :glue  /  /
7750   //                  \      /  /
7751   //                    ADDE
7752   //
7753   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7754   SDValue AddcOp0 = AddcNode->getOperand(0);
7755   SDValue AddcOp1 = AddcNode->getOperand(1);
7756
7757   // Check if the two operands are from the same mul_lohi node.
7758   if (AddcOp0.getNode() == AddcOp1.getNode())
7759     return SDValue();
7760
7761   assert(AddcNode->getNumValues() == 2 &&
7762          AddcNode->getValueType(0) == MVT::i32 &&
7763          AddcNode->getValueType(1) == MVT::Glue &&
7764          "Expect ADDC with two result values: i32, glue");
7765
7766   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7767   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7768       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7769       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7770       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7771     return SDValue();
7772
7773   // Look for the glued ADDE.
7774   SDNode* AddeNode = AddcNode->getGluedUser();
7775   if (AddeNode == NULL)
7776     return SDValue();
7777
7778   // Make sure it is really an ADDE.
7779   if (AddeNode->getOpcode() != ISD::ADDE)
7780     return SDValue();
7781
7782   assert(AddeNode->getNumOperands() == 3 &&
7783          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7784          "ADDE node has the wrong inputs");
7785
7786   // Check for the triangle shape.
7787   SDValue AddeOp0 = AddeNode->getOperand(0);
7788   SDValue AddeOp1 = AddeNode->getOperand(1);
7789
7790   // Make sure that the ADDE operands are not coming from the same node.
7791   if (AddeOp0.getNode() == AddeOp1.getNode())
7792     return SDValue();
7793
7794   // Find the MUL_LOHI node walking up ADDE's operands.
7795   bool IsLeftOperandMUL = false;
7796   SDValue MULOp = findMUL_LOHI(AddeOp0);
7797   if (MULOp == SDValue())
7798    MULOp = findMUL_LOHI(AddeOp1);
7799   else
7800     IsLeftOperandMUL = true;
7801   if (MULOp == SDValue())
7802      return SDValue();
7803
7804   // Figure out the right opcode.
7805   unsigned Opc = MULOp->getOpcode();
7806   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7807
7808   // Figure out the high and low input values to the MLAL node.
7809   SDValue* HiMul = &MULOp;
7810   SDValue* HiAdd = NULL;
7811   SDValue* LoMul = NULL;
7812   SDValue* LowAdd = NULL;
7813
7814   if (IsLeftOperandMUL)
7815     HiAdd = &AddeOp1;
7816   else
7817     HiAdd = &AddeOp0;
7818
7819
7820   if (AddcOp0->getOpcode() == Opc) {
7821     LoMul = &AddcOp0;
7822     LowAdd = &AddcOp1;
7823   }
7824   if (AddcOp1->getOpcode() == Opc) {
7825     LoMul = &AddcOp1;
7826     LowAdd = &AddcOp0;
7827   }
7828
7829   if (LoMul == NULL)
7830     return SDValue();
7831
7832   if (LoMul->getNode() != HiMul->getNode())
7833     return SDValue();
7834
7835   // Create the merged node.
7836   SelectionDAG &DAG = DCI.DAG;
7837
7838   // Build operand list.
7839   SmallVector<SDValue, 8> Ops;
7840   Ops.push_back(LoMul->getOperand(0));
7841   Ops.push_back(LoMul->getOperand(1));
7842   Ops.push_back(*LowAdd);
7843   Ops.push_back(*HiAdd);
7844
7845   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7846                                  DAG.getVTList(MVT::i32, MVT::i32),
7847                                  &Ops[0], Ops.size());
7848
7849   // Replace the ADDs' nodes uses by the MLA node's values.
7850   SDValue HiMLALResult(MLALNode.getNode(), 1);
7851   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7852
7853   SDValue LoMLALResult(MLALNode.getNode(), 0);
7854   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7855
7856   // Return original node to notify the driver to stop replacing.
7857   SDValue resNode(AddcNode, 0);
7858   return resNode;
7859 }
7860
7861 /// PerformADDCCombine - Target-specific dag combine transform from
7862 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7863 static SDValue PerformADDCCombine(SDNode *N,
7864                                  TargetLowering::DAGCombinerInfo &DCI,
7865                                  const ARMSubtarget *Subtarget) {
7866
7867   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7868
7869 }
7870
7871 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7872 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7873 /// called with the default operands, and if that fails, with commuted
7874 /// operands.
7875 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7876                                           TargetLowering::DAGCombinerInfo &DCI,
7877                                           const ARMSubtarget *Subtarget){
7878
7879   // Attempt to create vpaddl for this add.
7880   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7881   if (Result.getNode())
7882     return Result;
7883
7884   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7885   if (N0.getNode()->hasOneUse()) {
7886     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7887     if (Result.getNode()) return Result;
7888   }
7889   return SDValue();
7890 }
7891
7892 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7893 ///
7894 static SDValue PerformADDCombine(SDNode *N,
7895                                  TargetLowering::DAGCombinerInfo &DCI,
7896                                  const ARMSubtarget *Subtarget) {
7897   SDValue N0 = N->getOperand(0);
7898   SDValue N1 = N->getOperand(1);
7899
7900   // First try with the default operand order.
7901   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7902   if (Result.getNode())
7903     return Result;
7904
7905   // If that didn't work, try again with the operands commuted.
7906   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7907 }
7908
7909 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7910 ///
7911 static SDValue PerformSUBCombine(SDNode *N,
7912                                  TargetLowering::DAGCombinerInfo &DCI) {
7913   SDValue N0 = N->getOperand(0);
7914   SDValue N1 = N->getOperand(1);
7915
7916   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7917   if (N1.getNode()->hasOneUse()) {
7918     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7919     if (Result.getNode()) return Result;
7920   }
7921
7922   return SDValue();
7923 }
7924
7925 /// PerformVMULCombine
7926 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7927 /// special multiplier accumulator forwarding.
7928 ///   vmul d3, d0, d2
7929 ///   vmla d3, d1, d2
7930 /// is faster than
7931 ///   vadd d3, d0, d1
7932 ///   vmul d3, d3, d2
7933 static SDValue PerformVMULCombine(SDNode *N,
7934                                   TargetLowering::DAGCombinerInfo &DCI,
7935                                   const ARMSubtarget *Subtarget) {
7936   if (!Subtarget->hasVMLxForwarding())
7937     return SDValue();
7938
7939   SelectionDAG &DAG = DCI.DAG;
7940   SDValue N0 = N->getOperand(0);
7941   SDValue N1 = N->getOperand(1);
7942   unsigned Opcode = N0.getOpcode();
7943   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7944       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7945     Opcode = N1.getOpcode();
7946     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7947         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7948       return SDValue();
7949     std::swap(N0, N1);
7950   }
7951
7952   EVT VT = N->getValueType(0);
7953   DebugLoc DL = N->getDebugLoc();
7954   SDValue N00 = N0->getOperand(0);
7955   SDValue N01 = N0->getOperand(1);
7956   return DAG.getNode(Opcode, DL, VT,
7957                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7958                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7959 }
7960
7961 static SDValue PerformMULCombine(SDNode *N,
7962                                  TargetLowering::DAGCombinerInfo &DCI,
7963                                  const ARMSubtarget *Subtarget) {
7964   SelectionDAG &DAG = DCI.DAG;
7965
7966   if (Subtarget->isThumb1Only())
7967     return SDValue();
7968
7969   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7970     return SDValue();
7971
7972   EVT VT = N->getValueType(0);
7973   if (VT.is64BitVector() || VT.is128BitVector())
7974     return PerformVMULCombine(N, DCI, Subtarget);
7975   if (VT != MVT::i32)
7976     return SDValue();
7977
7978   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7979   if (!C)
7980     return SDValue();
7981
7982   int64_t MulAmt = C->getSExtValue();
7983   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7984
7985   ShiftAmt = ShiftAmt & (32 - 1);
7986   SDValue V = N->getOperand(0);
7987   DebugLoc DL = N->getDebugLoc();
7988
7989   SDValue Res;
7990   MulAmt >>= ShiftAmt;
7991
7992   if (MulAmt >= 0) {
7993     if (isPowerOf2_32(MulAmt - 1)) {
7994       // (mul x, 2^N + 1) => (add (shl x, N), x)
7995       Res = DAG.getNode(ISD::ADD, DL, VT,
7996                         V,
7997                         DAG.getNode(ISD::SHL, DL, VT,
7998                                     V,
7999                                     DAG.getConstant(Log2_32(MulAmt - 1),
8000                                                     MVT::i32)));
8001     } else if (isPowerOf2_32(MulAmt + 1)) {
8002       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8003       Res = DAG.getNode(ISD::SUB, DL, VT,
8004                         DAG.getNode(ISD::SHL, DL, VT,
8005                                     V,
8006                                     DAG.getConstant(Log2_32(MulAmt + 1),
8007                                                     MVT::i32)),
8008                         V);
8009     } else
8010       return SDValue();
8011   } else {
8012     uint64_t MulAmtAbs = -MulAmt;
8013     if (isPowerOf2_32(MulAmtAbs + 1)) {
8014       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8015       Res = DAG.getNode(ISD::SUB, DL, VT,
8016                         V,
8017                         DAG.getNode(ISD::SHL, DL, VT,
8018                                     V,
8019                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8020                                                     MVT::i32)));
8021     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8022       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8023       Res = DAG.getNode(ISD::ADD, DL, VT,
8024                         V,
8025                         DAG.getNode(ISD::SHL, DL, VT,
8026                                     V,
8027                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8028                                                     MVT::i32)));
8029       Res = DAG.getNode(ISD::SUB, DL, VT,
8030                         DAG.getConstant(0, MVT::i32),Res);
8031
8032     } else
8033       return SDValue();
8034   }
8035
8036   if (ShiftAmt != 0)
8037     Res = DAG.getNode(ISD::SHL, DL, VT,
8038                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8039
8040   // Do not add new nodes to DAG combiner worklist.
8041   DCI.CombineTo(N, Res, false);
8042   return SDValue();
8043 }
8044
8045 static SDValue PerformANDCombine(SDNode *N,
8046                                  TargetLowering::DAGCombinerInfo &DCI,
8047                                  const ARMSubtarget *Subtarget) {
8048
8049   // Attempt to use immediate-form VBIC
8050   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8051   DebugLoc dl = N->getDebugLoc();
8052   EVT VT = N->getValueType(0);
8053   SelectionDAG &DAG = DCI.DAG;
8054
8055   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8056     return SDValue();
8057
8058   APInt SplatBits, SplatUndef;
8059   unsigned SplatBitSize;
8060   bool HasAnyUndefs;
8061   if (BVN &&
8062       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8063     if (SplatBitSize <= 64) {
8064       EVT VbicVT;
8065       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8066                                       SplatUndef.getZExtValue(), SplatBitSize,
8067                                       DAG, VbicVT, VT.is128BitVector(),
8068                                       OtherModImm);
8069       if (Val.getNode()) {
8070         SDValue Input =
8071           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8072         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8073         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8074       }
8075     }
8076   }
8077
8078   if (!Subtarget->isThumb1Only()) {
8079     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8080     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8081     if (Result.getNode())
8082       return Result;
8083   }
8084
8085   return SDValue();
8086 }
8087
8088 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8089 static SDValue PerformORCombine(SDNode *N,
8090                                 TargetLowering::DAGCombinerInfo &DCI,
8091                                 const ARMSubtarget *Subtarget) {
8092   // Attempt to use immediate-form VORR
8093   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8094   DebugLoc dl = N->getDebugLoc();
8095   EVT VT = N->getValueType(0);
8096   SelectionDAG &DAG = DCI.DAG;
8097
8098   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8099     return SDValue();
8100
8101   APInt SplatBits, SplatUndef;
8102   unsigned SplatBitSize;
8103   bool HasAnyUndefs;
8104   if (BVN && Subtarget->hasNEON() &&
8105       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8106     if (SplatBitSize <= 64) {
8107       EVT VorrVT;
8108       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8109                                       SplatUndef.getZExtValue(), SplatBitSize,
8110                                       DAG, VorrVT, VT.is128BitVector(),
8111                                       OtherModImm);
8112       if (Val.getNode()) {
8113         SDValue Input =
8114           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8115         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8116         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8117       }
8118     }
8119   }
8120
8121   if (!Subtarget->isThumb1Only()) {
8122     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8123     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8124     if (Result.getNode())
8125       return Result;
8126   }
8127
8128   // The code below optimizes (or (and X, Y), Z).
8129   // The AND operand needs to have a single user to make these optimizations
8130   // profitable.
8131   SDValue N0 = N->getOperand(0);
8132   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8133     return SDValue();
8134   SDValue N1 = N->getOperand(1);
8135
8136   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8137   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8138       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8139     APInt SplatUndef;
8140     unsigned SplatBitSize;
8141     bool HasAnyUndefs;
8142
8143     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8144     APInt SplatBits0;
8145     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8146                                   HasAnyUndefs) && !HasAnyUndefs) {
8147       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8148       APInt SplatBits1;
8149       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8150                                     HasAnyUndefs) && !HasAnyUndefs &&
8151           SplatBits0 == ~SplatBits1) {
8152         // Canonicalize the vector type to make instruction selection simpler.
8153         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8154         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8155                                      N0->getOperand(1), N0->getOperand(0),
8156                                      N1->getOperand(0));
8157         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8158       }
8159     }
8160   }
8161
8162   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8163   // reasonable.
8164
8165   // BFI is only available on V6T2+
8166   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8167     return SDValue();
8168
8169   DebugLoc DL = N->getDebugLoc();
8170   // 1) or (and A, mask), val => ARMbfi A, val, mask
8171   //      iff (val & mask) == val
8172   //
8173   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8174   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8175   //          && mask == ~mask2
8176   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8177   //          && ~mask == mask2
8178   //  (i.e., copy a bitfield value into another bitfield of the same width)
8179
8180   if (VT != MVT::i32)
8181     return SDValue();
8182
8183   SDValue N00 = N0.getOperand(0);
8184
8185   // The value and the mask need to be constants so we can verify this is
8186   // actually a bitfield set. If the mask is 0xffff, we can do better
8187   // via a movt instruction, so don't use BFI in that case.
8188   SDValue MaskOp = N0.getOperand(1);
8189   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8190   if (!MaskC)
8191     return SDValue();
8192   unsigned Mask = MaskC->getZExtValue();
8193   if (Mask == 0xffff)
8194     return SDValue();
8195   SDValue Res;
8196   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8197   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8198   if (N1C) {
8199     unsigned Val = N1C->getZExtValue();
8200     if ((Val & ~Mask) != Val)
8201       return SDValue();
8202
8203     if (ARM::isBitFieldInvertedMask(Mask)) {
8204       Val >>= CountTrailingZeros_32(~Mask);
8205
8206       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8207                         DAG.getConstant(Val, MVT::i32),
8208                         DAG.getConstant(Mask, MVT::i32));
8209
8210       // Do not add new nodes to DAG combiner worklist.
8211       DCI.CombineTo(N, Res, false);
8212       return SDValue();
8213     }
8214   } else if (N1.getOpcode() == ISD::AND) {
8215     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8216     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8217     if (!N11C)
8218       return SDValue();
8219     unsigned Mask2 = N11C->getZExtValue();
8220
8221     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8222     // as is to match.
8223     if (ARM::isBitFieldInvertedMask(Mask) &&
8224         (Mask == ~Mask2)) {
8225       // The pack halfword instruction works better for masks that fit it,
8226       // so use that when it's available.
8227       if (Subtarget->hasT2ExtractPack() &&
8228           (Mask == 0xffff || Mask == 0xffff0000))
8229         return SDValue();
8230       // 2a
8231       unsigned amt = CountTrailingZeros_32(Mask2);
8232       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8233                         DAG.getConstant(amt, MVT::i32));
8234       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8235                         DAG.getConstant(Mask, MVT::i32));
8236       // Do not add new nodes to DAG combiner worklist.
8237       DCI.CombineTo(N, Res, false);
8238       return SDValue();
8239     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8240                (~Mask == Mask2)) {
8241       // The pack halfword instruction works better for masks that fit it,
8242       // so use that when it's available.
8243       if (Subtarget->hasT2ExtractPack() &&
8244           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8245         return SDValue();
8246       // 2b
8247       unsigned lsb = CountTrailingZeros_32(Mask);
8248       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8249                         DAG.getConstant(lsb, MVT::i32));
8250       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8251                         DAG.getConstant(Mask2, MVT::i32));
8252       // Do not add new nodes to DAG combiner worklist.
8253       DCI.CombineTo(N, Res, false);
8254       return SDValue();
8255     }
8256   }
8257
8258   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8259       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8260       ARM::isBitFieldInvertedMask(~Mask)) {
8261     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8262     // where lsb(mask) == #shamt and masked bits of B are known zero.
8263     SDValue ShAmt = N00.getOperand(1);
8264     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8265     unsigned LSB = CountTrailingZeros_32(Mask);
8266     if (ShAmtC != LSB)
8267       return SDValue();
8268
8269     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8270                       DAG.getConstant(~Mask, MVT::i32));
8271
8272     // Do not add new nodes to DAG combiner worklist.
8273     DCI.CombineTo(N, Res, false);
8274   }
8275
8276   return SDValue();
8277 }
8278
8279 static SDValue PerformXORCombine(SDNode *N,
8280                                  TargetLowering::DAGCombinerInfo &DCI,
8281                                  const ARMSubtarget *Subtarget) {
8282   EVT VT = N->getValueType(0);
8283   SelectionDAG &DAG = DCI.DAG;
8284
8285   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8286     return SDValue();
8287
8288   if (!Subtarget->isThumb1Only()) {
8289     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8290     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8291     if (Result.getNode())
8292       return Result;
8293   }
8294
8295   return SDValue();
8296 }
8297
8298 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8299 /// the bits being cleared by the AND are not demanded by the BFI.
8300 static SDValue PerformBFICombine(SDNode *N,
8301                                  TargetLowering::DAGCombinerInfo &DCI) {
8302   SDValue N1 = N->getOperand(1);
8303   if (N1.getOpcode() == ISD::AND) {
8304     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8305     if (!N11C)
8306       return SDValue();
8307     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8308     unsigned LSB = CountTrailingZeros_32(~InvMask);
8309     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8310     unsigned Mask = (1 << Width)-1;
8311     unsigned Mask2 = N11C->getZExtValue();
8312     if ((Mask & (~Mask2)) == 0)
8313       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8314                              N->getOperand(0), N1.getOperand(0),
8315                              N->getOperand(2));
8316   }
8317   return SDValue();
8318 }
8319
8320 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8321 /// ARMISD::VMOVRRD.
8322 static SDValue PerformVMOVRRDCombine(SDNode *N,
8323                                      TargetLowering::DAGCombinerInfo &DCI) {
8324   // vmovrrd(vmovdrr x, y) -> x,y
8325   SDValue InDouble = N->getOperand(0);
8326   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8327     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8328
8329   // vmovrrd(load f64) -> (load i32), (load i32)
8330   SDNode *InNode = InDouble.getNode();
8331   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8332       InNode->getValueType(0) == MVT::f64 &&
8333       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8334       !cast<LoadSDNode>(InNode)->isVolatile()) {
8335     // TODO: Should this be done for non-FrameIndex operands?
8336     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8337
8338     SelectionDAG &DAG = DCI.DAG;
8339     DebugLoc DL = LD->getDebugLoc();
8340     SDValue BasePtr = LD->getBasePtr();
8341     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8342                                  LD->getPointerInfo(), LD->isVolatile(),
8343                                  LD->isNonTemporal(), LD->isInvariant(),
8344                                  LD->getAlignment());
8345
8346     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8347                                     DAG.getConstant(4, MVT::i32));
8348     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8349                                  LD->getPointerInfo(), LD->isVolatile(),
8350                                  LD->isNonTemporal(), LD->isInvariant(),
8351                                  std::min(4U, LD->getAlignment() / 2));
8352
8353     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8354     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8355     DCI.RemoveFromWorklist(LD);
8356     DAG.DeleteNode(LD);
8357     return Result;
8358   }
8359
8360   return SDValue();
8361 }
8362
8363 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8364 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8365 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8366   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8367   SDValue Op0 = N->getOperand(0);
8368   SDValue Op1 = N->getOperand(1);
8369   if (Op0.getOpcode() == ISD::BITCAST)
8370     Op0 = Op0.getOperand(0);
8371   if (Op1.getOpcode() == ISD::BITCAST)
8372     Op1 = Op1.getOperand(0);
8373   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8374       Op0.getNode() == Op1.getNode() &&
8375       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8376     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8377                        N->getValueType(0), Op0.getOperand(0));
8378   return SDValue();
8379 }
8380
8381 /// PerformSTORECombine - Target-specific dag combine xforms for
8382 /// ISD::STORE.
8383 static SDValue PerformSTORECombine(SDNode *N,
8384                                    TargetLowering::DAGCombinerInfo &DCI) {
8385   StoreSDNode *St = cast<StoreSDNode>(N);
8386   if (St->isVolatile())
8387     return SDValue();
8388
8389   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8390   // pack all of the elements in one place.  Next, store to memory in fewer
8391   // chunks.
8392   SDValue StVal = St->getValue();
8393   EVT VT = StVal.getValueType();
8394   if (St->isTruncatingStore() && VT.isVector()) {
8395     SelectionDAG &DAG = DCI.DAG;
8396     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8397     EVT StVT = St->getMemoryVT();
8398     unsigned NumElems = VT.getVectorNumElements();
8399     assert(StVT != VT && "Cannot truncate to the same type");
8400     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8401     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8402
8403     // From, To sizes and ElemCount must be pow of two
8404     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8405
8406     // We are going to use the original vector elt for storing.
8407     // Accumulated smaller vector elements must be a multiple of the store size.
8408     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8409
8410     unsigned SizeRatio  = FromEltSz / ToEltSz;
8411     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8412
8413     // Create a type on which we perform the shuffle.
8414     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8415                                      NumElems*SizeRatio);
8416     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8417
8418     DebugLoc DL = St->getDebugLoc();
8419     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8420     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8421     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8422
8423     // Can't shuffle using an illegal type.
8424     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8425
8426     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8427                                 DAG.getUNDEF(WideVec.getValueType()),
8428                                 ShuffleVec.data());
8429     // At this point all of the data is stored at the bottom of the
8430     // register. We now need to save it to mem.
8431
8432     // Find the largest store unit
8433     MVT StoreType = MVT::i8;
8434     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8435          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8436       MVT Tp = (MVT::SimpleValueType)tp;
8437       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8438         StoreType = Tp;
8439     }
8440     // Didn't find a legal store type.
8441     if (!TLI.isTypeLegal(StoreType))
8442       return SDValue();
8443
8444     // Bitcast the original vector into a vector of store-size units
8445     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8446             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8447     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8448     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8449     SmallVector<SDValue, 8> Chains;
8450     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8451                                         TLI.getPointerTy());
8452     SDValue BasePtr = St->getBasePtr();
8453
8454     // Perform one or more big stores into memory.
8455     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8456     for (unsigned I = 0; I < E; I++) {
8457       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8458                                    StoreType, ShuffWide,
8459                                    DAG.getIntPtrConstant(I));
8460       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8461                                 St->getPointerInfo(), St->isVolatile(),
8462                                 St->isNonTemporal(), St->getAlignment());
8463       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8464                             Increment);
8465       Chains.push_back(Ch);
8466     }
8467     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8468                        Chains.size());
8469   }
8470
8471   if (!ISD::isNormalStore(St))
8472     return SDValue();
8473
8474   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8475   // ARM stores of arguments in the same cache line.
8476   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8477       StVal.getNode()->hasOneUse()) {
8478     SelectionDAG  &DAG = DCI.DAG;
8479     DebugLoc DL = St->getDebugLoc();
8480     SDValue BasePtr = St->getBasePtr();
8481     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8482                                   StVal.getNode()->getOperand(0), BasePtr,
8483                                   St->getPointerInfo(), St->isVolatile(),
8484                                   St->isNonTemporal(), St->getAlignment());
8485
8486     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8487                                     DAG.getConstant(4, MVT::i32));
8488     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8489                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8490                         St->isNonTemporal(),
8491                         std::min(4U, St->getAlignment() / 2));
8492   }
8493
8494   if (StVal.getValueType() != MVT::i64 ||
8495       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8496     return SDValue();
8497
8498   // Bitcast an i64 store extracted from a vector to f64.
8499   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8500   SelectionDAG &DAG = DCI.DAG;
8501   DebugLoc dl = StVal.getDebugLoc();
8502   SDValue IntVec = StVal.getOperand(0);
8503   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8504                                  IntVec.getValueType().getVectorNumElements());
8505   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8506   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8507                                Vec, StVal.getOperand(1));
8508   dl = N->getDebugLoc();
8509   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8510   // Make the DAGCombiner fold the bitcasts.
8511   DCI.AddToWorklist(Vec.getNode());
8512   DCI.AddToWorklist(ExtElt.getNode());
8513   DCI.AddToWorklist(V.getNode());
8514   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8515                       St->getPointerInfo(), St->isVolatile(),
8516                       St->isNonTemporal(), St->getAlignment(),
8517                       St->getTBAAInfo());
8518 }
8519
8520 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8521 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8522 /// i64 vector to have f64 elements, since the value can then be loaded
8523 /// directly into a VFP register.
8524 static bool hasNormalLoadOperand(SDNode *N) {
8525   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8526   for (unsigned i = 0; i < NumElts; ++i) {
8527     SDNode *Elt = N->getOperand(i).getNode();
8528     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8529       return true;
8530   }
8531   return false;
8532 }
8533
8534 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8535 /// ISD::BUILD_VECTOR.
8536 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8537                                           TargetLowering::DAGCombinerInfo &DCI){
8538   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8539   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8540   // into a pair of GPRs, which is fine when the value is used as a scalar,
8541   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8542   SelectionDAG &DAG = DCI.DAG;
8543   if (N->getNumOperands() == 2) {
8544     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8545     if (RV.getNode())
8546       return RV;
8547   }
8548
8549   // Load i64 elements as f64 values so that type legalization does not split
8550   // them up into i32 values.
8551   EVT VT = N->getValueType(0);
8552   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8553     return SDValue();
8554   DebugLoc dl = N->getDebugLoc();
8555   SmallVector<SDValue, 8> Ops;
8556   unsigned NumElts = VT.getVectorNumElements();
8557   for (unsigned i = 0; i < NumElts; ++i) {
8558     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8559     Ops.push_back(V);
8560     // Make the DAGCombiner fold the bitcast.
8561     DCI.AddToWorklist(V.getNode());
8562   }
8563   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8564   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8565   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8566 }
8567
8568 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8569 /// ISD::INSERT_VECTOR_ELT.
8570 static SDValue PerformInsertEltCombine(SDNode *N,
8571                                        TargetLowering::DAGCombinerInfo &DCI) {
8572   // Bitcast an i64 load inserted into a vector to f64.
8573   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8574   EVT VT = N->getValueType(0);
8575   SDNode *Elt = N->getOperand(1).getNode();
8576   if (VT.getVectorElementType() != MVT::i64 ||
8577       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8578     return SDValue();
8579
8580   SelectionDAG &DAG = DCI.DAG;
8581   DebugLoc dl = N->getDebugLoc();
8582   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8583                                  VT.getVectorNumElements());
8584   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8585   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8586   // Make the DAGCombiner fold the bitcasts.
8587   DCI.AddToWorklist(Vec.getNode());
8588   DCI.AddToWorklist(V.getNode());
8589   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8590                                Vec, V, N->getOperand(2));
8591   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8592 }
8593
8594 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8595 /// ISD::VECTOR_SHUFFLE.
8596 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8597   // The LLVM shufflevector instruction does not require the shuffle mask
8598   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8599   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8600   // operands do not match the mask length, they are extended by concatenating
8601   // them with undef vectors.  That is probably the right thing for other
8602   // targets, but for NEON it is better to concatenate two double-register
8603   // size vector operands into a single quad-register size vector.  Do that
8604   // transformation here:
8605   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8606   //   shuffle(concat(v1, v2), undef)
8607   SDValue Op0 = N->getOperand(0);
8608   SDValue Op1 = N->getOperand(1);
8609   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8610       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8611       Op0.getNumOperands() != 2 ||
8612       Op1.getNumOperands() != 2)
8613     return SDValue();
8614   SDValue Concat0Op1 = Op0.getOperand(1);
8615   SDValue Concat1Op1 = Op1.getOperand(1);
8616   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8617       Concat1Op1.getOpcode() != ISD::UNDEF)
8618     return SDValue();
8619   // Skip the transformation if any of the types are illegal.
8620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8621   EVT VT = N->getValueType(0);
8622   if (!TLI.isTypeLegal(VT) ||
8623       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8624       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8625     return SDValue();
8626
8627   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8628                                   Op0.getOperand(0), Op1.getOperand(0));
8629   // Translate the shuffle mask.
8630   SmallVector<int, 16> NewMask;
8631   unsigned NumElts = VT.getVectorNumElements();
8632   unsigned HalfElts = NumElts/2;
8633   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8634   for (unsigned n = 0; n < NumElts; ++n) {
8635     int MaskElt = SVN->getMaskElt(n);
8636     int NewElt = -1;
8637     if (MaskElt < (int)HalfElts)
8638       NewElt = MaskElt;
8639     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8640       NewElt = HalfElts + MaskElt - NumElts;
8641     NewMask.push_back(NewElt);
8642   }
8643   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8644                               DAG.getUNDEF(VT), NewMask.data());
8645 }
8646
8647 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8648 /// NEON load/store intrinsics to merge base address updates.
8649 static SDValue CombineBaseUpdate(SDNode *N,
8650                                  TargetLowering::DAGCombinerInfo &DCI) {
8651   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8652     return SDValue();
8653
8654   SelectionDAG &DAG = DCI.DAG;
8655   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8656                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8657   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8658   SDValue Addr = N->getOperand(AddrOpIdx);
8659
8660   // Search for a use of the address operand that is an increment.
8661   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8662          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8663     SDNode *User = *UI;
8664     if (User->getOpcode() != ISD::ADD ||
8665         UI.getUse().getResNo() != Addr.getResNo())
8666       continue;
8667
8668     // Check that the add is independent of the load/store.  Otherwise, folding
8669     // it would create a cycle.
8670     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8671       continue;
8672
8673     // Find the new opcode for the updating load/store.
8674     bool isLoad = true;
8675     bool isLaneOp = false;
8676     unsigned NewOpc = 0;
8677     unsigned NumVecs = 0;
8678     if (isIntrinsic) {
8679       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8680       switch (IntNo) {
8681       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8682       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8683         NumVecs = 1; break;
8684       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8685         NumVecs = 2; break;
8686       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8687         NumVecs = 3; break;
8688       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8689         NumVecs = 4; break;
8690       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8691         NumVecs = 2; isLaneOp = true; break;
8692       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8693         NumVecs = 3; isLaneOp = true; break;
8694       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8695         NumVecs = 4; isLaneOp = true; break;
8696       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8697         NumVecs = 1; isLoad = false; break;
8698       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8699         NumVecs = 2; isLoad = false; break;
8700       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8701         NumVecs = 3; isLoad = false; break;
8702       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8703         NumVecs = 4; isLoad = false; break;
8704       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8705         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8706       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8707         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8708       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8709         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8710       }
8711     } else {
8712       isLaneOp = true;
8713       switch (N->getOpcode()) {
8714       default: llvm_unreachable("unexpected opcode for Neon base update");
8715       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8716       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8717       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8718       }
8719     }
8720
8721     // Find the size of memory referenced by the load/store.
8722     EVT VecTy;
8723     if (isLoad)
8724       VecTy = N->getValueType(0);
8725     else
8726       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8727     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8728     if (isLaneOp)
8729       NumBytes /= VecTy.getVectorNumElements();
8730
8731     // If the increment is a constant, it must match the memory ref size.
8732     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8733     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8734       uint64_t IncVal = CInc->getZExtValue();
8735       if (IncVal != NumBytes)
8736         continue;
8737     } else if (NumBytes >= 3 * 16) {
8738       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8739       // separate instructions that make it harder to use a non-constant update.
8740       continue;
8741     }
8742
8743     // Create the new updating load/store node.
8744     EVT Tys[6];
8745     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8746     unsigned n;
8747     for (n = 0; n < NumResultVecs; ++n)
8748       Tys[n] = VecTy;
8749     Tys[n++] = MVT::i32;
8750     Tys[n] = MVT::Other;
8751     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8752     SmallVector<SDValue, 8> Ops;
8753     Ops.push_back(N->getOperand(0)); // incoming chain
8754     Ops.push_back(N->getOperand(AddrOpIdx));
8755     Ops.push_back(Inc);
8756     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8757       Ops.push_back(N->getOperand(i));
8758     }
8759     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8760     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8761                                            Ops.data(), Ops.size(),
8762                                            MemInt->getMemoryVT(),
8763                                            MemInt->getMemOperand());
8764
8765     // Update the uses.
8766     std::vector<SDValue> NewResults;
8767     for (unsigned i = 0; i < NumResultVecs; ++i) {
8768       NewResults.push_back(SDValue(UpdN.getNode(), i));
8769     }
8770     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8771     DCI.CombineTo(N, NewResults);
8772     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8773
8774     break;
8775   }
8776   return SDValue();
8777 }
8778
8779 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8780 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8781 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8782 /// return true.
8783 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8784   SelectionDAG &DAG = DCI.DAG;
8785   EVT VT = N->getValueType(0);
8786   // vldN-dup instructions only support 64-bit vectors for N > 1.
8787   if (!VT.is64BitVector())
8788     return false;
8789
8790   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8791   SDNode *VLD = N->getOperand(0).getNode();
8792   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8793     return false;
8794   unsigned NumVecs = 0;
8795   unsigned NewOpc = 0;
8796   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8797   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8798     NumVecs = 2;
8799     NewOpc = ARMISD::VLD2DUP;
8800   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8801     NumVecs = 3;
8802     NewOpc = ARMISD::VLD3DUP;
8803   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8804     NumVecs = 4;
8805     NewOpc = ARMISD::VLD4DUP;
8806   } else {
8807     return false;
8808   }
8809
8810   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8811   // numbers match the load.
8812   unsigned VLDLaneNo =
8813     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8814   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8815        UI != UE; ++UI) {
8816     // Ignore uses of the chain result.
8817     if (UI.getUse().getResNo() == NumVecs)
8818       continue;
8819     SDNode *User = *UI;
8820     if (User->getOpcode() != ARMISD::VDUPLANE ||
8821         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8822       return false;
8823   }
8824
8825   // Create the vldN-dup node.
8826   EVT Tys[5];
8827   unsigned n;
8828   for (n = 0; n < NumVecs; ++n)
8829     Tys[n] = VT;
8830   Tys[n] = MVT::Other;
8831   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8832   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8833   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8834   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8835                                            Ops, 2, VLDMemInt->getMemoryVT(),
8836                                            VLDMemInt->getMemOperand());
8837
8838   // Update the uses.
8839   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8840        UI != UE; ++UI) {
8841     unsigned ResNo = UI.getUse().getResNo();
8842     // Ignore uses of the chain result.
8843     if (ResNo == NumVecs)
8844       continue;
8845     SDNode *User = *UI;
8846     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8847   }
8848
8849   // Now the vldN-lane intrinsic is dead except for its chain result.
8850   // Update uses of the chain.
8851   std::vector<SDValue> VLDDupResults;
8852   for (unsigned n = 0; n < NumVecs; ++n)
8853     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8854   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8855   DCI.CombineTo(VLD, VLDDupResults);
8856
8857   return true;
8858 }
8859
8860 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8861 /// ARMISD::VDUPLANE.
8862 static SDValue PerformVDUPLANECombine(SDNode *N,
8863                                       TargetLowering::DAGCombinerInfo &DCI) {
8864   SDValue Op = N->getOperand(0);
8865
8866   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8867   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8868   if (CombineVLDDUP(N, DCI))
8869     return SDValue(N, 0);
8870
8871   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8872   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8873   while (Op.getOpcode() == ISD::BITCAST)
8874     Op = Op.getOperand(0);
8875   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8876     return SDValue();
8877
8878   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8879   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8880   // The canonical VMOV for a zero vector uses a 32-bit element size.
8881   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8882   unsigned EltBits;
8883   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8884     EltSize = 8;
8885   EVT VT = N->getValueType(0);
8886   if (EltSize > VT.getVectorElementType().getSizeInBits())
8887     return SDValue();
8888
8889   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8890 }
8891
8892 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8893 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8894 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8895 {
8896   integerPart cN;
8897   integerPart c0 = 0;
8898   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8899        I != E; I++) {
8900     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8901     if (!C)
8902       return false;
8903
8904     bool isExact;
8905     APFloat APF = C->getValueAPF();
8906     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8907         != APFloat::opOK || !isExact)
8908       return false;
8909
8910     c0 = (I == 0) ? cN : c0;
8911     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8912       return false;
8913   }
8914   C = c0;
8915   return true;
8916 }
8917
8918 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8919 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8920 /// when the VMUL has a constant operand that is a power of 2.
8921 ///
8922 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8923 ///  vmul.f32        d16, d17, d16
8924 ///  vcvt.s32.f32    d16, d16
8925 /// becomes:
8926 ///  vcvt.s32.f32    d16, d16, #3
8927 static SDValue PerformVCVTCombine(SDNode *N,
8928                                   TargetLowering::DAGCombinerInfo &DCI,
8929                                   const ARMSubtarget *Subtarget) {
8930   SelectionDAG &DAG = DCI.DAG;
8931   SDValue Op = N->getOperand(0);
8932
8933   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8934       Op.getOpcode() != ISD::FMUL)
8935     return SDValue();
8936
8937   uint64_t C;
8938   SDValue N0 = Op->getOperand(0);
8939   SDValue ConstVec = Op->getOperand(1);
8940   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8941
8942   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8943       !isConstVecPow2(ConstVec, isSigned, C))
8944     return SDValue();
8945
8946   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8947     Intrinsic::arm_neon_vcvtfp2fxu;
8948   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8949                      N->getValueType(0),
8950                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8951                      DAG.getConstant(Log2_64(C), MVT::i32));
8952 }
8953
8954 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8955 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8956 /// when the VDIV has a constant operand that is a power of 2.
8957 ///
8958 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8959 ///  vcvt.f32.s32    d16, d16
8960 ///  vdiv.f32        d16, d17, d16
8961 /// becomes:
8962 ///  vcvt.f32.s32    d16, d16, #3
8963 static SDValue PerformVDIVCombine(SDNode *N,
8964                                   TargetLowering::DAGCombinerInfo &DCI,
8965                                   const ARMSubtarget *Subtarget) {
8966   SelectionDAG &DAG = DCI.DAG;
8967   SDValue Op = N->getOperand(0);
8968   unsigned OpOpcode = Op.getNode()->getOpcode();
8969
8970   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8971       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8972     return SDValue();
8973
8974   uint64_t C;
8975   SDValue ConstVec = N->getOperand(1);
8976   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8977
8978   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8979       !isConstVecPow2(ConstVec, isSigned, C))
8980     return SDValue();
8981
8982   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8983     Intrinsic::arm_neon_vcvtfxu2fp;
8984   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8985                      Op.getValueType(),
8986                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8987                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8988 }
8989
8990 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8991 /// operand of a vector shift operation, where all the elements of the
8992 /// build_vector must have the same constant integer value.
8993 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8994   // Ignore bit_converts.
8995   while (Op.getOpcode() == ISD::BITCAST)
8996     Op = Op.getOperand(0);
8997   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8998   APInt SplatBits, SplatUndef;
8999   unsigned SplatBitSize;
9000   bool HasAnyUndefs;
9001   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9002                                       HasAnyUndefs, ElementBits) ||
9003       SplatBitSize > ElementBits)
9004     return false;
9005   Cnt = SplatBits.getSExtValue();
9006   return true;
9007 }
9008
9009 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9010 /// operand of a vector shift left operation.  That value must be in the range:
9011 ///   0 <= Value < ElementBits for a left shift; or
9012 ///   0 <= Value <= ElementBits for a long left shift.
9013 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9014   assert(VT.isVector() && "vector shift count is not a vector type");
9015   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9016   if (! getVShiftImm(Op, ElementBits, Cnt))
9017     return false;
9018   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9019 }
9020
9021 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9022 /// operand of a vector shift right operation.  For a shift opcode, the value
9023 /// is positive, but for an intrinsic the value count must be negative. The
9024 /// absolute value must be in the range:
9025 ///   1 <= |Value| <= ElementBits for a right shift; or
9026 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9027 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9028                          int64_t &Cnt) {
9029   assert(VT.isVector() && "vector shift count is not a vector type");
9030   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9031   if (! getVShiftImm(Op, ElementBits, Cnt))
9032     return false;
9033   if (isIntrinsic)
9034     Cnt = -Cnt;
9035   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9036 }
9037
9038 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9039 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9040   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9041   switch (IntNo) {
9042   default:
9043     // Don't do anything for most intrinsics.
9044     break;
9045
9046   // Vector shifts: check for immediate versions and lower them.
9047   // Note: This is done during DAG combining instead of DAG legalizing because
9048   // the build_vectors for 64-bit vector element shift counts are generally
9049   // not legal, and it is hard to see their values after they get legalized to
9050   // loads from a constant pool.
9051   case Intrinsic::arm_neon_vshifts:
9052   case Intrinsic::arm_neon_vshiftu:
9053   case Intrinsic::arm_neon_vshiftls:
9054   case Intrinsic::arm_neon_vshiftlu:
9055   case Intrinsic::arm_neon_vshiftn:
9056   case Intrinsic::arm_neon_vrshifts:
9057   case Intrinsic::arm_neon_vrshiftu:
9058   case Intrinsic::arm_neon_vrshiftn:
9059   case Intrinsic::arm_neon_vqshifts:
9060   case Intrinsic::arm_neon_vqshiftu:
9061   case Intrinsic::arm_neon_vqshiftsu:
9062   case Intrinsic::arm_neon_vqshiftns:
9063   case Intrinsic::arm_neon_vqshiftnu:
9064   case Intrinsic::arm_neon_vqshiftnsu:
9065   case Intrinsic::arm_neon_vqrshiftns:
9066   case Intrinsic::arm_neon_vqrshiftnu:
9067   case Intrinsic::arm_neon_vqrshiftnsu: {
9068     EVT VT = N->getOperand(1).getValueType();
9069     int64_t Cnt;
9070     unsigned VShiftOpc = 0;
9071
9072     switch (IntNo) {
9073     case Intrinsic::arm_neon_vshifts:
9074     case Intrinsic::arm_neon_vshiftu:
9075       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9076         VShiftOpc = ARMISD::VSHL;
9077         break;
9078       }
9079       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9080         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9081                      ARMISD::VSHRs : ARMISD::VSHRu);
9082         break;
9083       }
9084       return SDValue();
9085
9086     case Intrinsic::arm_neon_vshiftls:
9087     case Intrinsic::arm_neon_vshiftlu:
9088       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9089         break;
9090       llvm_unreachable("invalid shift count for vshll intrinsic");
9091
9092     case Intrinsic::arm_neon_vrshifts:
9093     case Intrinsic::arm_neon_vrshiftu:
9094       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9095         break;
9096       return SDValue();
9097
9098     case Intrinsic::arm_neon_vqshifts:
9099     case Intrinsic::arm_neon_vqshiftu:
9100       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9101         break;
9102       return SDValue();
9103
9104     case Intrinsic::arm_neon_vqshiftsu:
9105       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9106         break;
9107       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9108
9109     case Intrinsic::arm_neon_vshiftn:
9110     case Intrinsic::arm_neon_vrshiftn:
9111     case Intrinsic::arm_neon_vqshiftns:
9112     case Intrinsic::arm_neon_vqshiftnu:
9113     case Intrinsic::arm_neon_vqshiftnsu:
9114     case Intrinsic::arm_neon_vqrshiftns:
9115     case Intrinsic::arm_neon_vqrshiftnu:
9116     case Intrinsic::arm_neon_vqrshiftnsu:
9117       // Narrowing shifts require an immediate right shift.
9118       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9119         break;
9120       llvm_unreachable("invalid shift count for narrowing vector shift "
9121                        "intrinsic");
9122
9123     default:
9124       llvm_unreachable("unhandled vector shift");
9125     }
9126
9127     switch (IntNo) {
9128     case Intrinsic::arm_neon_vshifts:
9129     case Intrinsic::arm_neon_vshiftu:
9130       // Opcode already set above.
9131       break;
9132     case Intrinsic::arm_neon_vshiftls:
9133     case Intrinsic::arm_neon_vshiftlu:
9134       if (Cnt == VT.getVectorElementType().getSizeInBits())
9135         VShiftOpc = ARMISD::VSHLLi;
9136       else
9137         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9138                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9139       break;
9140     case Intrinsic::arm_neon_vshiftn:
9141       VShiftOpc = ARMISD::VSHRN; break;
9142     case Intrinsic::arm_neon_vrshifts:
9143       VShiftOpc = ARMISD::VRSHRs; break;
9144     case Intrinsic::arm_neon_vrshiftu:
9145       VShiftOpc = ARMISD::VRSHRu; break;
9146     case Intrinsic::arm_neon_vrshiftn:
9147       VShiftOpc = ARMISD::VRSHRN; break;
9148     case Intrinsic::arm_neon_vqshifts:
9149       VShiftOpc = ARMISD::VQSHLs; break;
9150     case Intrinsic::arm_neon_vqshiftu:
9151       VShiftOpc = ARMISD::VQSHLu; break;
9152     case Intrinsic::arm_neon_vqshiftsu:
9153       VShiftOpc = ARMISD::VQSHLsu; break;
9154     case Intrinsic::arm_neon_vqshiftns:
9155       VShiftOpc = ARMISD::VQSHRNs; break;
9156     case Intrinsic::arm_neon_vqshiftnu:
9157       VShiftOpc = ARMISD::VQSHRNu; break;
9158     case Intrinsic::arm_neon_vqshiftnsu:
9159       VShiftOpc = ARMISD::VQSHRNsu; break;
9160     case Intrinsic::arm_neon_vqrshiftns:
9161       VShiftOpc = ARMISD::VQRSHRNs; break;
9162     case Intrinsic::arm_neon_vqrshiftnu:
9163       VShiftOpc = ARMISD::VQRSHRNu; break;
9164     case Intrinsic::arm_neon_vqrshiftnsu:
9165       VShiftOpc = ARMISD::VQRSHRNsu; break;
9166     }
9167
9168     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9169                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9170   }
9171
9172   case Intrinsic::arm_neon_vshiftins: {
9173     EVT VT = N->getOperand(1).getValueType();
9174     int64_t Cnt;
9175     unsigned VShiftOpc = 0;
9176
9177     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9178       VShiftOpc = ARMISD::VSLI;
9179     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9180       VShiftOpc = ARMISD::VSRI;
9181     else {
9182       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9183     }
9184
9185     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9186                        N->getOperand(1), N->getOperand(2),
9187                        DAG.getConstant(Cnt, MVT::i32));
9188   }
9189
9190   case Intrinsic::arm_neon_vqrshifts:
9191   case Intrinsic::arm_neon_vqrshiftu:
9192     // No immediate versions of these to check for.
9193     break;
9194   }
9195
9196   return SDValue();
9197 }
9198
9199 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9200 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9201 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9202 /// vector element shift counts are generally not legal, and it is hard to see
9203 /// their values after they get legalized to loads from a constant pool.
9204 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9205                                    const ARMSubtarget *ST) {
9206   EVT VT = N->getValueType(0);
9207   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9208     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9209     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9210     SDValue N1 = N->getOperand(1);
9211     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9212       SDValue N0 = N->getOperand(0);
9213       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9214           DAG.MaskedValueIsZero(N0.getOperand(0),
9215                                 APInt::getHighBitsSet(32, 16)))
9216         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9217     }
9218   }
9219
9220   // Nothing to be done for scalar shifts.
9221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9222   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9223     return SDValue();
9224
9225   assert(ST->hasNEON() && "unexpected vector shift");
9226   int64_t Cnt;
9227
9228   switch (N->getOpcode()) {
9229   default: llvm_unreachable("unexpected shift opcode");
9230
9231   case ISD::SHL:
9232     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9233       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9234                          DAG.getConstant(Cnt, MVT::i32));
9235     break;
9236
9237   case ISD::SRA:
9238   case ISD::SRL:
9239     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9240       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9241                             ARMISD::VSHRs : ARMISD::VSHRu);
9242       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9243                          DAG.getConstant(Cnt, MVT::i32));
9244     }
9245   }
9246   return SDValue();
9247 }
9248
9249 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9250 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9251 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9252                                     const ARMSubtarget *ST) {
9253   SDValue N0 = N->getOperand(0);
9254
9255   // Check for sign- and zero-extensions of vector extract operations of 8-
9256   // and 16-bit vector elements.  NEON supports these directly.  They are
9257   // handled during DAG combining because type legalization will promote them
9258   // to 32-bit types and it is messy to recognize the operations after that.
9259   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9260     SDValue Vec = N0.getOperand(0);
9261     SDValue Lane = N0.getOperand(1);
9262     EVT VT = N->getValueType(0);
9263     EVT EltVT = N0.getValueType();
9264     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9265
9266     if (VT == MVT::i32 &&
9267         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9268         TLI.isTypeLegal(Vec.getValueType()) &&
9269         isa<ConstantSDNode>(Lane)) {
9270
9271       unsigned Opc = 0;
9272       switch (N->getOpcode()) {
9273       default: llvm_unreachable("unexpected opcode");
9274       case ISD::SIGN_EXTEND:
9275         Opc = ARMISD::VGETLANEs;
9276         break;
9277       case ISD::ZERO_EXTEND:
9278       case ISD::ANY_EXTEND:
9279         Opc = ARMISD::VGETLANEu;
9280         break;
9281       }
9282       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9283     }
9284   }
9285
9286   return SDValue();
9287 }
9288
9289 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9290 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9291 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9292                                        const ARMSubtarget *ST) {
9293   // If the target supports NEON, try to use vmax/vmin instructions for f32
9294   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9295   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9296   // a NaN; only do the transformation when it matches that behavior.
9297
9298   // For now only do this when using NEON for FP operations; if using VFP, it
9299   // is not obvious that the benefit outweighs the cost of switching to the
9300   // NEON pipeline.
9301   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9302       N->getValueType(0) != MVT::f32)
9303     return SDValue();
9304
9305   SDValue CondLHS = N->getOperand(0);
9306   SDValue CondRHS = N->getOperand(1);
9307   SDValue LHS = N->getOperand(2);
9308   SDValue RHS = N->getOperand(3);
9309   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9310
9311   unsigned Opcode = 0;
9312   bool IsReversed;
9313   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9314     IsReversed = false; // x CC y ? x : y
9315   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9316     IsReversed = true ; // x CC y ? y : x
9317   } else {
9318     return SDValue();
9319   }
9320
9321   bool IsUnordered;
9322   switch (CC) {
9323   default: break;
9324   case ISD::SETOLT:
9325   case ISD::SETOLE:
9326   case ISD::SETLT:
9327   case ISD::SETLE:
9328   case ISD::SETULT:
9329   case ISD::SETULE:
9330     // If LHS is NaN, an ordered comparison will be false and the result will
9331     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9332     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9333     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9334     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9335       break;
9336     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9337     // will return -0, so vmin can only be used for unsafe math or if one of
9338     // the operands is known to be nonzero.
9339     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9340         !DAG.getTarget().Options.UnsafeFPMath &&
9341         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9342       break;
9343     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9344     break;
9345
9346   case ISD::SETOGT:
9347   case ISD::SETOGE:
9348   case ISD::SETGT:
9349   case ISD::SETGE:
9350   case ISD::SETUGT:
9351   case ISD::SETUGE:
9352     // If LHS is NaN, an ordered comparison will be false and the result will
9353     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9354     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9355     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9356     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9357       break;
9358     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9359     // will return +0, so vmax can only be used for unsafe math or if one of
9360     // the operands is known to be nonzero.
9361     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9362         !DAG.getTarget().Options.UnsafeFPMath &&
9363         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9364       break;
9365     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9366     break;
9367   }
9368
9369   if (!Opcode)
9370     return SDValue();
9371   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9372 }
9373
9374 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9375 SDValue
9376 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9377   SDValue Cmp = N->getOperand(4);
9378   if (Cmp.getOpcode() != ARMISD::CMPZ)
9379     // Only looking at EQ and NE cases.
9380     return SDValue();
9381
9382   EVT VT = N->getValueType(0);
9383   DebugLoc dl = N->getDebugLoc();
9384   SDValue LHS = Cmp.getOperand(0);
9385   SDValue RHS = Cmp.getOperand(1);
9386   SDValue FalseVal = N->getOperand(0);
9387   SDValue TrueVal = N->getOperand(1);
9388   SDValue ARMcc = N->getOperand(2);
9389   ARMCC::CondCodes CC =
9390     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9391
9392   // Simplify
9393   //   mov     r1, r0
9394   //   cmp     r1, x
9395   //   mov     r0, y
9396   //   moveq   r0, x
9397   // to
9398   //   cmp     r0, x
9399   //   movne   r0, y
9400   //
9401   //   mov     r1, r0
9402   //   cmp     r1, x
9403   //   mov     r0, x
9404   //   movne   r0, y
9405   // to
9406   //   cmp     r0, x
9407   //   movne   r0, y
9408   /// FIXME: Turn this into a target neutral optimization?
9409   SDValue Res;
9410   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9411     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9412                       N->getOperand(3), Cmp);
9413   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9414     SDValue ARMcc;
9415     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9416     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9417                       N->getOperand(3), NewCmp);
9418   }
9419
9420   if (Res.getNode()) {
9421     APInt KnownZero, KnownOne;
9422     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9423     // Capture demanded bits information that would be otherwise lost.
9424     if (KnownZero == 0xfffffffe)
9425       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9426                         DAG.getValueType(MVT::i1));
9427     else if (KnownZero == 0xffffff00)
9428       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9429                         DAG.getValueType(MVT::i8));
9430     else if (KnownZero == 0xffff0000)
9431       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9432                         DAG.getValueType(MVT::i16));
9433   }
9434
9435   return Res;
9436 }
9437
9438 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9439                                              DAGCombinerInfo &DCI) const {
9440   switch (N->getOpcode()) {
9441   default: break;
9442   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9443   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9444   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9445   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9446   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9447   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9448   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9449   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9450   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9451   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9452   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9453   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9454   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9455   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9456   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9457   case ISD::FP_TO_SINT:
9458   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9459   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9460   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9461   case ISD::SHL:
9462   case ISD::SRA:
9463   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9464   case ISD::SIGN_EXTEND:
9465   case ISD::ZERO_EXTEND:
9466   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9467   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9468   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9469   case ARMISD::VLD2DUP:
9470   case ARMISD::VLD3DUP:
9471   case ARMISD::VLD4DUP:
9472     return CombineBaseUpdate(N, DCI);
9473   case ISD::INTRINSIC_VOID:
9474   case ISD::INTRINSIC_W_CHAIN:
9475     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9476     case Intrinsic::arm_neon_vld1:
9477     case Intrinsic::arm_neon_vld2:
9478     case Intrinsic::arm_neon_vld3:
9479     case Intrinsic::arm_neon_vld4:
9480     case Intrinsic::arm_neon_vld2lane:
9481     case Intrinsic::arm_neon_vld3lane:
9482     case Intrinsic::arm_neon_vld4lane:
9483     case Intrinsic::arm_neon_vst1:
9484     case Intrinsic::arm_neon_vst2:
9485     case Intrinsic::arm_neon_vst3:
9486     case Intrinsic::arm_neon_vst4:
9487     case Intrinsic::arm_neon_vst2lane:
9488     case Intrinsic::arm_neon_vst3lane:
9489     case Intrinsic::arm_neon_vst4lane:
9490       return CombineBaseUpdate(N, DCI);
9491     default: break;
9492     }
9493     break;
9494   }
9495   return SDValue();
9496 }
9497
9498 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9499                                                           EVT VT) const {
9500   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9501 }
9502
9503 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9504   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9505   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9506
9507   switch (VT.getSimpleVT().SimpleTy) {
9508   default:
9509     return false;
9510   case MVT::i8:
9511   case MVT::i16:
9512   case MVT::i32: {
9513     // Unaligned access can use (for example) LRDB, LRDH, LDR
9514     if (AllowsUnaligned) {
9515       if (Fast)
9516         *Fast = Subtarget->hasV7Ops();
9517       return true;
9518     }
9519     return false;
9520   }
9521   case MVT::f64:
9522   case MVT::v2f64: {
9523     // For any little-endian targets with neon, we can support unaligned ld/st
9524     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9525     // A big-endian target may also explictly support unaligned accesses
9526     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9527       if (Fast)
9528         *Fast = true;
9529       return true;
9530     }
9531     return false;
9532   }
9533   }
9534 }
9535
9536 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9537                        unsigned AlignCheck) {
9538   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9539           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9540 }
9541
9542 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9543                                            unsigned DstAlign, unsigned SrcAlign,
9544                                            bool IsMemset, bool ZeroMemset,
9545                                            bool MemcpyStrSrc,
9546                                            MachineFunction &MF) const {
9547   const Function *F = MF.getFunction();
9548
9549   // See if we can use NEON instructions for this...
9550   if ((!IsMemset || ZeroMemset) &&
9551       Subtarget->hasNEON() &&
9552       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9553                                        Attribute::NoImplicitFloat)) {
9554     bool Fast;
9555     if (Size >= 16 &&
9556         (memOpAlign(SrcAlign, DstAlign, 16) ||
9557          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9558       return MVT::v2f64;
9559     } else if (Size >= 8 &&
9560                (memOpAlign(SrcAlign, DstAlign, 8) ||
9561                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9562       return MVT::f64;
9563     }
9564   }
9565
9566   // Lowering to i32/i16 if the size permits.
9567   if (Size >= 4)
9568     return MVT::i32;
9569   else if (Size >= 2)
9570     return MVT::i16;
9571
9572   // Let the target-independent logic figure it out.
9573   return MVT::Other;
9574 }
9575
9576 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9577   if (Val.getOpcode() != ISD::LOAD)
9578     return false;
9579
9580   EVT VT1 = Val.getValueType();
9581   if (!VT1.isSimple() || !VT1.isInteger() ||
9582       !VT2.isSimple() || !VT2.isInteger())
9583     return false;
9584
9585   switch (VT1.getSimpleVT().SimpleTy) {
9586   default: break;
9587   case MVT::i1:
9588   case MVT::i8:
9589   case MVT::i16:
9590     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9591     return true;
9592   }
9593
9594   return false;
9595 }
9596
9597 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9598   if (V < 0)
9599     return false;
9600
9601   unsigned Scale = 1;
9602   switch (VT.getSimpleVT().SimpleTy) {
9603   default: return false;
9604   case MVT::i1:
9605   case MVT::i8:
9606     // Scale == 1;
9607     break;
9608   case MVT::i16:
9609     // Scale == 2;
9610     Scale = 2;
9611     break;
9612   case MVT::i32:
9613     // Scale == 4;
9614     Scale = 4;
9615     break;
9616   }
9617
9618   if ((V & (Scale - 1)) != 0)
9619     return false;
9620   V /= Scale;
9621   return V == (V & ((1LL << 5) - 1));
9622 }
9623
9624 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9625                                       const ARMSubtarget *Subtarget) {
9626   bool isNeg = false;
9627   if (V < 0) {
9628     isNeg = true;
9629     V = - V;
9630   }
9631
9632   switch (VT.getSimpleVT().SimpleTy) {
9633   default: return false;
9634   case MVT::i1:
9635   case MVT::i8:
9636   case MVT::i16:
9637   case MVT::i32:
9638     // + imm12 or - imm8
9639     if (isNeg)
9640       return V == (V & ((1LL << 8) - 1));
9641     return V == (V & ((1LL << 12) - 1));
9642   case MVT::f32:
9643   case MVT::f64:
9644     // Same as ARM mode. FIXME: NEON?
9645     if (!Subtarget->hasVFP2())
9646       return false;
9647     if ((V & 3) != 0)
9648       return false;
9649     V >>= 2;
9650     return V == (V & ((1LL << 8) - 1));
9651   }
9652 }
9653
9654 /// isLegalAddressImmediate - Return true if the integer value can be used
9655 /// as the offset of the target addressing mode for load / store of the
9656 /// given type.
9657 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9658                                     const ARMSubtarget *Subtarget) {
9659   if (V == 0)
9660     return true;
9661
9662   if (!VT.isSimple())
9663     return false;
9664
9665   if (Subtarget->isThumb1Only())
9666     return isLegalT1AddressImmediate(V, VT);
9667   else if (Subtarget->isThumb2())
9668     return isLegalT2AddressImmediate(V, VT, Subtarget);
9669
9670   // ARM mode.
9671   if (V < 0)
9672     V = - V;
9673   switch (VT.getSimpleVT().SimpleTy) {
9674   default: return false;
9675   case MVT::i1:
9676   case MVT::i8:
9677   case MVT::i32:
9678     // +- imm12
9679     return V == (V & ((1LL << 12) - 1));
9680   case MVT::i16:
9681     // +- imm8
9682     return V == (V & ((1LL << 8) - 1));
9683   case MVT::f32:
9684   case MVT::f64:
9685     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9686       return false;
9687     if ((V & 3) != 0)
9688       return false;
9689     V >>= 2;
9690     return V == (V & ((1LL << 8) - 1));
9691   }
9692 }
9693
9694 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9695                                                       EVT VT) const {
9696   int Scale = AM.Scale;
9697   if (Scale < 0)
9698     return false;
9699
9700   switch (VT.getSimpleVT().SimpleTy) {
9701   default: return false;
9702   case MVT::i1:
9703   case MVT::i8:
9704   case MVT::i16:
9705   case MVT::i32:
9706     if (Scale == 1)
9707       return true;
9708     // r + r << imm
9709     Scale = Scale & ~1;
9710     return Scale == 2 || Scale == 4 || Scale == 8;
9711   case MVT::i64:
9712     // r + r
9713     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9714       return true;
9715     return false;
9716   case MVT::isVoid:
9717     // Note, we allow "void" uses (basically, uses that aren't loads or
9718     // stores), because arm allows folding a scale into many arithmetic
9719     // operations.  This should be made more precise and revisited later.
9720
9721     // Allow r << imm, but the imm has to be a multiple of two.
9722     if (Scale & 1) return false;
9723     return isPowerOf2_32(Scale);
9724   }
9725 }
9726
9727 /// isLegalAddressingMode - Return true if the addressing mode represented
9728 /// by AM is legal for this target, for a load/store of the specified type.
9729 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9730                                               Type *Ty) const {
9731   EVT VT = getValueType(Ty, true);
9732   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9733     return false;
9734
9735   // Can never fold addr of global into load/store.
9736   if (AM.BaseGV)
9737     return false;
9738
9739   switch (AM.Scale) {
9740   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9741     break;
9742   case 1:
9743     if (Subtarget->isThumb1Only())
9744       return false;
9745     // FALL THROUGH.
9746   default:
9747     // ARM doesn't support any R+R*scale+imm addr modes.
9748     if (AM.BaseOffs)
9749       return false;
9750
9751     if (!VT.isSimple())
9752       return false;
9753
9754     if (Subtarget->isThumb2())
9755       return isLegalT2ScaledAddressingMode(AM, VT);
9756
9757     int Scale = AM.Scale;
9758     switch (VT.getSimpleVT().SimpleTy) {
9759     default: return false;
9760     case MVT::i1:
9761     case MVT::i8:
9762     case MVT::i32:
9763       if (Scale < 0) Scale = -Scale;
9764       if (Scale == 1)
9765         return true;
9766       // r + r << imm
9767       return isPowerOf2_32(Scale & ~1);
9768     case MVT::i16:
9769     case MVT::i64:
9770       // r + r
9771       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9772         return true;
9773       return false;
9774
9775     case MVT::isVoid:
9776       // Note, we allow "void" uses (basically, uses that aren't loads or
9777       // stores), because arm allows folding a scale into many arithmetic
9778       // operations.  This should be made more precise and revisited later.
9779
9780       // Allow r << imm, but the imm has to be a multiple of two.
9781       if (Scale & 1) return false;
9782       return isPowerOf2_32(Scale);
9783     }
9784   }
9785   return true;
9786 }
9787
9788 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9789 /// icmp immediate, that is the target has icmp instructions which can compare
9790 /// a register against the immediate without having to materialize the
9791 /// immediate into a register.
9792 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9793   // Thumb2 and ARM modes can use cmn for negative immediates.
9794   if (!Subtarget->isThumb())
9795     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9796   if (Subtarget->isThumb2())
9797     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9798   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9799   return Imm >= 0 && Imm <= 255;
9800 }
9801
9802 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9803 /// *or sub* immediate, that is the target has add or sub instructions which can
9804 /// add a register with the immediate without having to materialize the
9805 /// immediate into a register.
9806 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9807   // Same encoding for add/sub, just flip the sign.
9808   int64_t AbsImm = llvm::abs64(Imm);
9809   if (!Subtarget->isThumb())
9810     return ARM_AM::getSOImmVal(AbsImm) != -1;
9811   if (Subtarget->isThumb2())
9812     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9813   // Thumb1 only has 8-bit unsigned immediate.
9814   return AbsImm >= 0 && AbsImm <= 255;
9815 }
9816
9817 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9818                                       bool isSEXTLoad, SDValue &Base,
9819                                       SDValue &Offset, bool &isInc,
9820                                       SelectionDAG &DAG) {
9821   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9822     return false;
9823
9824   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9825     // AddressingMode 3
9826     Base = Ptr->getOperand(0);
9827     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9828       int RHSC = (int)RHS->getZExtValue();
9829       if (RHSC < 0 && RHSC > -256) {
9830         assert(Ptr->getOpcode() == ISD::ADD);
9831         isInc = false;
9832         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9833         return true;
9834       }
9835     }
9836     isInc = (Ptr->getOpcode() == ISD::ADD);
9837     Offset = Ptr->getOperand(1);
9838     return true;
9839   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9840     // AddressingMode 2
9841     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9842       int RHSC = (int)RHS->getZExtValue();
9843       if (RHSC < 0 && RHSC > -0x1000) {
9844         assert(Ptr->getOpcode() == ISD::ADD);
9845         isInc = false;
9846         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9847         Base = Ptr->getOperand(0);
9848         return true;
9849       }
9850     }
9851
9852     if (Ptr->getOpcode() == ISD::ADD) {
9853       isInc = true;
9854       ARM_AM::ShiftOpc ShOpcVal=
9855         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9856       if (ShOpcVal != ARM_AM::no_shift) {
9857         Base = Ptr->getOperand(1);
9858         Offset = Ptr->getOperand(0);
9859       } else {
9860         Base = Ptr->getOperand(0);
9861         Offset = Ptr->getOperand(1);
9862       }
9863       return true;
9864     }
9865
9866     isInc = (Ptr->getOpcode() == ISD::ADD);
9867     Base = Ptr->getOperand(0);
9868     Offset = Ptr->getOperand(1);
9869     return true;
9870   }
9871
9872   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9873   return false;
9874 }
9875
9876 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9877                                      bool isSEXTLoad, SDValue &Base,
9878                                      SDValue &Offset, bool &isInc,
9879                                      SelectionDAG &DAG) {
9880   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9881     return false;
9882
9883   Base = Ptr->getOperand(0);
9884   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9885     int RHSC = (int)RHS->getZExtValue();
9886     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9887       assert(Ptr->getOpcode() == ISD::ADD);
9888       isInc = false;
9889       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9890       return true;
9891     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9892       isInc = Ptr->getOpcode() == ISD::ADD;
9893       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9894       return true;
9895     }
9896   }
9897
9898   return false;
9899 }
9900
9901 /// getPreIndexedAddressParts - returns true by value, base pointer and
9902 /// offset pointer and addressing mode by reference if the node's address
9903 /// can be legally represented as pre-indexed load / store address.
9904 bool
9905 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9906                                              SDValue &Offset,
9907                                              ISD::MemIndexedMode &AM,
9908                                              SelectionDAG &DAG) const {
9909   if (Subtarget->isThumb1Only())
9910     return false;
9911
9912   EVT VT;
9913   SDValue Ptr;
9914   bool isSEXTLoad = false;
9915   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9916     Ptr = LD->getBasePtr();
9917     VT  = LD->getMemoryVT();
9918     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9919   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9920     Ptr = ST->getBasePtr();
9921     VT  = ST->getMemoryVT();
9922   } else
9923     return false;
9924
9925   bool isInc;
9926   bool isLegal = false;
9927   if (Subtarget->isThumb2())
9928     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9929                                        Offset, isInc, DAG);
9930   else
9931     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9932                                         Offset, isInc, DAG);
9933   if (!isLegal)
9934     return false;
9935
9936   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9937   return true;
9938 }
9939
9940 /// getPostIndexedAddressParts - returns true by value, base pointer and
9941 /// offset pointer and addressing mode by reference if this node can be
9942 /// combined with a load / store to form a post-indexed load / store.
9943 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9944                                                    SDValue &Base,
9945                                                    SDValue &Offset,
9946                                                    ISD::MemIndexedMode &AM,
9947                                                    SelectionDAG &DAG) const {
9948   if (Subtarget->isThumb1Only())
9949     return false;
9950
9951   EVT VT;
9952   SDValue Ptr;
9953   bool isSEXTLoad = false;
9954   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9955     VT  = LD->getMemoryVT();
9956     Ptr = LD->getBasePtr();
9957     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9958   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9959     VT  = ST->getMemoryVT();
9960     Ptr = ST->getBasePtr();
9961   } else
9962     return false;
9963
9964   bool isInc;
9965   bool isLegal = false;
9966   if (Subtarget->isThumb2())
9967     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9968                                        isInc, DAG);
9969   else
9970     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9971                                         isInc, DAG);
9972   if (!isLegal)
9973     return false;
9974
9975   if (Ptr != Base) {
9976     // Swap base ptr and offset to catch more post-index load / store when
9977     // it's legal. In Thumb2 mode, offset must be an immediate.
9978     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9979         !Subtarget->isThumb2())
9980       std::swap(Base, Offset);
9981
9982     // Post-indexed load / store update the base pointer.
9983     if (Ptr != Base)
9984       return false;
9985   }
9986
9987   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9988   return true;
9989 }
9990
9991 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9992                                                        APInt &KnownZero,
9993                                                        APInt &KnownOne,
9994                                                        const SelectionDAG &DAG,
9995                                                        unsigned Depth) const {
9996   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9997   switch (Op.getOpcode()) {
9998   default: break;
9999   case ARMISD::CMOV: {
10000     // Bits are known zero/one if known on the LHS and RHS.
10001     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10002     if (KnownZero == 0 && KnownOne == 0) return;
10003
10004     APInt KnownZeroRHS, KnownOneRHS;
10005     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10006     KnownZero &= KnownZeroRHS;
10007     KnownOne  &= KnownOneRHS;
10008     return;
10009   }
10010   }
10011 }
10012
10013 //===----------------------------------------------------------------------===//
10014 //                           ARM Inline Assembly Support
10015 //===----------------------------------------------------------------------===//
10016
10017 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10018   // Looking for "rev" which is V6+.
10019   if (!Subtarget->hasV6Ops())
10020     return false;
10021
10022   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10023   std::string AsmStr = IA->getAsmString();
10024   SmallVector<StringRef, 4> AsmPieces;
10025   SplitString(AsmStr, AsmPieces, ";\n");
10026
10027   switch (AsmPieces.size()) {
10028   default: return false;
10029   case 1:
10030     AsmStr = AsmPieces[0];
10031     AsmPieces.clear();
10032     SplitString(AsmStr, AsmPieces, " \t,");
10033
10034     // rev $0, $1
10035     if (AsmPieces.size() == 3 &&
10036         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10037         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10038       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10039       if (Ty && Ty->getBitWidth() == 32)
10040         return IntrinsicLowering::LowerToByteSwap(CI);
10041     }
10042     break;
10043   }
10044
10045   return false;
10046 }
10047
10048 /// getConstraintType - Given a constraint letter, return the type of
10049 /// constraint it is for this target.
10050 ARMTargetLowering::ConstraintType
10051 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10052   if (Constraint.size() == 1) {
10053     switch (Constraint[0]) {
10054     default:  break;
10055     case 'l': return C_RegisterClass;
10056     case 'w': return C_RegisterClass;
10057     case 'h': return C_RegisterClass;
10058     case 'x': return C_RegisterClass;
10059     case 't': return C_RegisterClass;
10060     case 'j': return C_Other; // Constant for movw.
10061       // An address with a single base register. Due to the way we
10062       // currently handle addresses it is the same as an 'r' memory constraint.
10063     case 'Q': return C_Memory;
10064     }
10065   } else if (Constraint.size() == 2) {
10066     switch (Constraint[0]) {
10067     default: break;
10068     // All 'U+' constraints are addresses.
10069     case 'U': return C_Memory;
10070     }
10071   }
10072   return TargetLowering::getConstraintType(Constraint);
10073 }
10074
10075 /// Examine constraint type and operand type and determine a weight value.
10076 /// This object must already have been set up with the operand type
10077 /// and the current alternative constraint selected.
10078 TargetLowering::ConstraintWeight
10079 ARMTargetLowering::getSingleConstraintMatchWeight(
10080     AsmOperandInfo &info, const char *constraint) const {
10081   ConstraintWeight weight = CW_Invalid;
10082   Value *CallOperandVal = info.CallOperandVal;
10083     // If we don't have a value, we can't do a match,
10084     // but allow it at the lowest weight.
10085   if (CallOperandVal == NULL)
10086     return CW_Default;
10087   Type *type = CallOperandVal->getType();
10088   // Look at the constraint type.
10089   switch (*constraint) {
10090   default:
10091     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10092     break;
10093   case 'l':
10094     if (type->isIntegerTy()) {
10095       if (Subtarget->isThumb())
10096         weight = CW_SpecificReg;
10097       else
10098         weight = CW_Register;
10099     }
10100     break;
10101   case 'w':
10102     if (type->isFloatingPointTy())
10103       weight = CW_Register;
10104     break;
10105   }
10106   return weight;
10107 }
10108
10109 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10110 RCPair
10111 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10112                                                 EVT VT) const {
10113   if (Constraint.size() == 1) {
10114     // GCC ARM Constraint Letters
10115     switch (Constraint[0]) {
10116     case 'l': // Low regs or general regs.
10117       if (Subtarget->isThumb())
10118         return RCPair(0U, &ARM::tGPRRegClass);
10119       return RCPair(0U, &ARM::GPRRegClass);
10120     case 'h': // High regs or no regs.
10121       if (Subtarget->isThumb())
10122         return RCPair(0U, &ARM::hGPRRegClass);
10123       break;
10124     case 'r':
10125       return RCPair(0U, &ARM::GPRRegClass);
10126     case 'w':
10127       if (VT == MVT::f32)
10128         return RCPair(0U, &ARM::SPRRegClass);
10129       if (VT.getSizeInBits() == 64)
10130         return RCPair(0U, &ARM::DPRRegClass);
10131       if (VT.getSizeInBits() == 128)
10132         return RCPair(0U, &ARM::QPRRegClass);
10133       break;
10134     case 'x':
10135       if (VT == MVT::f32)
10136         return RCPair(0U, &ARM::SPR_8RegClass);
10137       if (VT.getSizeInBits() == 64)
10138         return RCPair(0U, &ARM::DPR_8RegClass);
10139       if (VT.getSizeInBits() == 128)
10140         return RCPair(0U, &ARM::QPR_8RegClass);
10141       break;
10142     case 't':
10143       if (VT == MVT::f32)
10144         return RCPair(0U, &ARM::SPRRegClass);
10145       break;
10146     }
10147   }
10148   if (StringRef("{cc}").equals_lower(Constraint))
10149     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10150
10151   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10152 }
10153
10154 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10155 /// vector.  If it is invalid, don't add anything to Ops.
10156 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10157                                                      std::string &Constraint,
10158                                                      std::vector<SDValue>&Ops,
10159                                                      SelectionDAG &DAG) const {
10160   SDValue Result(0, 0);
10161
10162   // Currently only support length 1 constraints.
10163   if (Constraint.length() != 1) return;
10164
10165   char ConstraintLetter = Constraint[0];
10166   switch (ConstraintLetter) {
10167   default: break;
10168   case 'j':
10169   case 'I': case 'J': case 'K': case 'L':
10170   case 'M': case 'N': case 'O':
10171     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10172     if (!C)
10173       return;
10174
10175     int64_t CVal64 = C->getSExtValue();
10176     int CVal = (int) CVal64;
10177     // None of these constraints allow values larger than 32 bits.  Check
10178     // that the value fits in an int.
10179     if (CVal != CVal64)
10180       return;
10181
10182     switch (ConstraintLetter) {
10183       case 'j':
10184         // Constant suitable for movw, must be between 0 and
10185         // 65535.
10186         if (Subtarget->hasV6T2Ops())
10187           if (CVal >= 0 && CVal <= 65535)
10188             break;
10189         return;
10190       case 'I':
10191         if (Subtarget->isThumb1Only()) {
10192           // This must be a constant between 0 and 255, for ADD
10193           // immediates.
10194           if (CVal >= 0 && CVal <= 255)
10195             break;
10196         } else if (Subtarget->isThumb2()) {
10197           // A constant that can be used as an immediate value in a
10198           // data-processing instruction.
10199           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10200             break;
10201         } else {
10202           // A constant that can be used as an immediate value in a
10203           // data-processing instruction.
10204           if (ARM_AM::getSOImmVal(CVal) != -1)
10205             break;
10206         }
10207         return;
10208
10209       case 'J':
10210         if (Subtarget->isThumb()) {  // FIXME thumb2
10211           // This must be a constant between -255 and -1, for negated ADD
10212           // immediates. This can be used in GCC with an "n" modifier that
10213           // prints the negated value, for use with SUB instructions. It is
10214           // not useful otherwise but is implemented for compatibility.
10215           if (CVal >= -255 && CVal <= -1)
10216             break;
10217         } else {
10218           // This must be a constant between -4095 and 4095. It is not clear
10219           // what this constraint is intended for. Implemented for
10220           // compatibility with GCC.
10221           if (CVal >= -4095 && CVal <= 4095)
10222             break;
10223         }
10224         return;
10225
10226       case 'K':
10227         if (Subtarget->isThumb1Only()) {
10228           // A 32-bit value where only one byte has a nonzero value. Exclude
10229           // zero to match GCC. This constraint is used by GCC internally for
10230           // constants that can be loaded with a move/shift combination.
10231           // It is not useful otherwise but is implemented for compatibility.
10232           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10233             break;
10234         } else if (Subtarget->isThumb2()) {
10235           // A constant whose bitwise inverse can be used as an immediate
10236           // value in a data-processing instruction. This can be used in GCC
10237           // with a "B" modifier that prints the inverted value, for use with
10238           // BIC and MVN instructions. It is not useful otherwise but is
10239           // implemented for compatibility.
10240           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10241             break;
10242         } else {
10243           // A constant whose bitwise inverse can be used as an immediate
10244           // value in a data-processing instruction. This can be used in GCC
10245           // with a "B" modifier that prints the inverted value, for use with
10246           // BIC and MVN instructions. It is not useful otherwise but is
10247           // implemented for compatibility.
10248           if (ARM_AM::getSOImmVal(~CVal) != -1)
10249             break;
10250         }
10251         return;
10252
10253       case 'L':
10254         if (Subtarget->isThumb1Only()) {
10255           // This must be a constant between -7 and 7,
10256           // for 3-operand ADD/SUB immediate instructions.
10257           if (CVal >= -7 && CVal < 7)
10258             break;
10259         } else if (Subtarget->isThumb2()) {
10260           // A constant whose negation can be used as an immediate value in a
10261           // data-processing instruction. This can be used in GCC with an "n"
10262           // modifier that prints the negated value, for use with SUB
10263           // instructions. It is not useful otherwise but is implemented for
10264           // compatibility.
10265           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10266             break;
10267         } else {
10268           // A constant whose negation can be used as an immediate value in a
10269           // data-processing instruction. This can be used in GCC with an "n"
10270           // modifier that prints the negated value, for use with SUB
10271           // instructions. It is not useful otherwise but is implemented for
10272           // compatibility.
10273           if (ARM_AM::getSOImmVal(-CVal) != -1)
10274             break;
10275         }
10276         return;
10277
10278       case 'M':
10279         if (Subtarget->isThumb()) { // FIXME thumb2
10280           // This must be a multiple of 4 between 0 and 1020, for
10281           // ADD sp + immediate.
10282           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10283             break;
10284         } else {
10285           // A power of two or a constant between 0 and 32.  This is used in
10286           // GCC for the shift amount on shifted register operands, but it is
10287           // useful in general for any shift amounts.
10288           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10289             break;
10290         }
10291         return;
10292
10293       case 'N':
10294         if (Subtarget->isThumb()) {  // FIXME thumb2
10295           // This must be a constant between 0 and 31, for shift amounts.
10296           if (CVal >= 0 && CVal <= 31)
10297             break;
10298         }
10299         return;
10300
10301       case 'O':
10302         if (Subtarget->isThumb()) {  // FIXME thumb2
10303           // This must be a multiple of 4 between -508 and 508, for
10304           // ADD/SUB sp = sp + immediate.
10305           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10306             break;
10307         }
10308         return;
10309     }
10310     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10311     break;
10312   }
10313
10314   if (Result.getNode()) {
10315     Ops.push_back(Result);
10316     return;
10317   }
10318   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10319 }
10320
10321 bool
10322 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10323   // The ARM target isn't yet aware of offsets.
10324   return false;
10325 }
10326
10327 bool ARM::isBitFieldInvertedMask(unsigned v) {
10328   if (v == 0xffffffff)
10329     return 0;
10330   // there can be 1's on either or both "outsides", all the "inside"
10331   // bits must be 0's
10332   unsigned int lsb = 0, msb = 31;
10333   while (v & (1 << msb)) --msb;
10334   while (v & (1 << lsb)) ++lsb;
10335   for (unsigned int i = lsb; i <= msb; ++i) {
10336     if (v & (1 << i))
10337       return 0;
10338   }
10339   return 1;
10340 }
10341
10342 /// isFPImmLegal - Returns true if the target can instruction select the
10343 /// specified FP immediate natively. If false, the legalizer will
10344 /// materialize the FP immediate as a load from a constant pool.
10345 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10346   if (!Subtarget->hasVFP3())
10347     return false;
10348   if (VT == MVT::f32)
10349     return ARM_AM::getFP32Imm(Imm) != -1;
10350   if (VT == MVT::f64)
10351     return ARM_AM::getFP64Imm(Imm) != -1;
10352   return false;
10353 }
10354
10355 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10356 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10357 /// specified in the intrinsic calls.
10358 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10359                                            const CallInst &I,
10360                                            unsigned Intrinsic) const {
10361   switch (Intrinsic) {
10362   case Intrinsic::arm_neon_vld1:
10363   case Intrinsic::arm_neon_vld2:
10364   case Intrinsic::arm_neon_vld3:
10365   case Intrinsic::arm_neon_vld4:
10366   case Intrinsic::arm_neon_vld2lane:
10367   case Intrinsic::arm_neon_vld3lane:
10368   case Intrinsic::arm_neon_vld4lane: {
10369     Info.opc = ISD::INTRINSIC_W_CHAIN;
10370     // Conservatively set memVT to the entire set of vectors loaded.
10371     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10372     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10373     Info.ptrVal = I.getArgOperand(0);
10374     Info.offset = 0;
10375     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10376     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10377     Info.vol = false; // volatile loads with NEON intrinsics not supported
10378     Info.readMem = true;
10379     Info.writeMem = false;
10380     return true;
10381   }
10382   case Intrinsic::arm_neon_vst1:
10383   case Intrinsic::arm_neon_vst2:
10384   case Intrinsic::arm_neon_vst3:
10385   case Intrinsic::arm_neon_vst4:
10386   case Intrinsic::arm_neon_vst2lane:
10387   case Intrinsic::arm_neon_vst3lane:
10388   case Intrinsic::arm_neon_vst4lane: {
10389     Info.opc = ISD::INTRINSIC_VOID;
10390     // Conservatively set memVT to the entire set of vectors stored.
10391     unsigned NumElts = 0;
10392     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10393       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10394       if (!ArgTy->isVectorTy())
10395         break;
10396       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10397     }
10398     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10399     Info.ptrVal = I.getArgOperand(0);
10400     Info.offset = 0;
10401     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10402     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10403     Info.vol = false; // volatile stores with NEON intrinsics not supported
10404     Info.readMem = false;
10405     Info.writeMem = true;
10406     return true;
10407   }
10408   case Intrinsic::arm_strexd: {
10409     Info.opc = ISD::INTRINSIC_W_CHAIN;
10410     Info.memVT = MVT::i64;
10411     Info.ptrVal = I.getArgOperand(2);
10412     Info.offset = 0;
10413     Info.align = 8;
10414     Info.vol = true;
10415     Info.readMem = false;
10416     Info.writeMem = true;
10417     return true;
10418   }
10419   case Intrinsic::arm_ldrexd: {
10420     Info.opc = ISD::INTRINSIC_W_CHAIN;
10421     Info.memVT = MVT::i64;
10422     Info.ptrVal = I.getArgOperand(0);
10423     Info.offset = 0;
10424     Info.align = 8;
10425     Info.vol = true;
10426     Info.readMem = true;
10427     Info.writeMem = false;
10428     return true;
10429   }
10430   default:
10431     break;
10432   }
10433
10434   return false;
10435 }