f8455a4b0e9597a9e3d8b0d5261d70ddf50c7353
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 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::SIGN_EXTEND_INREG, VT, Expand);
126   if (VT.isInteger()) {
127     setOperationAction(ISD::SHL, VT, Custom);
128     setOperationAction(ISD::SRA, VT, Custom);
129     setOperationAction(ISD::SRL, VT, Custom);
130   }
131
132   // Promote all bit-wise operations.
133   if (VT.isInteger() && VT != PromotedBitwiseVT) {
134     setOperationAction(ISD::AND, VT, Promote);
135     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136     setOperationAction(ISD::OR,  VT, Promote);
137     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
138     setOperationAction(ISD::XOR, VT, Promote);
139     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140   }
141
142   // Neon does not support vector divide/remainder operations.
143   setOperationAction(ISD::SDIV, VT, Expand);
144   setOperationAction(ISD::UDIV, VT, Expand);
145   setOperationAction(ISD::FDIV, VT, Expand);
146   setOperationAction(ISD::SREM, VT, Expand);
147   setOperationAction(ISD::UREM, VT, Expand);
148   setOperationAction(ISD::FREM, VT, Expand);
149 }
150
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152   addRegisterClass(VT, &ARM::DPRRegClass);
153   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 }
155
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157   addRegisterClass(VT, &ARM::QPRRegClass);
158   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 }
160
161 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
162   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
163     return new TargetLoweringObjectFileMachO();
164
165   return new ARMElfTargetObjectFile();
166 }
167
168 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
169     : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<ARMSubtarget>();
171   RegInfo = TM.getRegisterInfo();
172   Itins = TM.getInstrItineraryData();
173
174   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175
176   if (Subtarget->isTargetDarwin()) {
177     // Uses VFP for Thumb libfuncs if available.
178     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
179       // Single-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184
185       // Double-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190
191       // Single-precision comparisons.
192       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
199       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
200
201       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
208       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
209
210       // Double-precision comparisons.
211       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
218       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
219
220       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
227       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
228
229       // Floating-point to integer conversions.
230       // i64 conversions are done via library routines even when generating VFP
231       // instructions, so use the same ones.
232       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236
237       // Conversions between floating types.
238       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
240
241       // Integer to floating-point conversions.
242       // i64 conversions are done via library routines even when generating VFP
243       // instructions, so use the same ones.
244       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245       // e.g., __floatunsidf vs. __floatunssidfvfp.
246       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250     }
251   }
252
253   // These libcalls are not available in 32-bit.
254   setLibcallName(RTLIB::SHL_I128, 0);
255   setLibcallName(RTLIB::SRL_I128, 0);
256   setLibcallName(RTLIB::SRA_I128, 0);
257
258   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
259     // Double-precision floating-point arithmetic helper functions
260     // RTABI chapter 4.1.2, Table 2
261     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
269
270     // Double-precision floating-point comparison helper functions
271     // RTABI chapter 4.1.2, Table 3
272     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
286     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
287     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
288     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
296
297     // Single-precision floating-point arithmetic helper functions
298     // RTABI chapter 4.1.2, Table 4
299     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
307
308     // Single-precision floating-point comparison helper functions
309     // RTABI chapter 4.1.2, Table 5
310     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
324     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
325     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
326     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
334
335     // Floating-point to integer conversions.
336     // RTABI chapter 4.1.2, Table 6
337     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
353
354     // Conversions between floating types.
355     // RTABI chapter 4.1.2, Table 7
356     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
358     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
360
361     // Integer to floating-point conversions.
362     // RTABI chapter 4.1.2, Table 8
363     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379
380     // Long long helper functions
381     // RTABI chapter 4.2, Table 9
382     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
383     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
392
393     // Integer division functions
394     // RTABI chapter 4.3.1
395     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
411
412     // Memory operations
413     // RTABI chapter 4.3.4
414     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
415     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
417     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
420   }
421
422   // Use divmod compiler-rt calls for iOS 5.0 and later.
423   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
424       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
425     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
426     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
427   }
428
429   if (Subtarget->isThumb1Only())
430     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
431   else
432     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
433   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
434       !Subtarget->isThumb1Only()) {
435     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
436     if (!Subtarget->isFPOnlySP())
437       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
438
439     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440   }
441
442   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
444     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
445          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
446       setTruncStoreAction((MVT::SimpleValueType)VT,
447                           (MVT::SimpleValueType)InnerVT, Expand);
448     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
449     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
451   }
452
453   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
454
455   if (Subtarget->hasNEON()) {
456     addDRTypeForNEON(MVT::v2f32);
457     addDRTypeForNEON(MVT::v8i8);
458     addDRTypeForNEON(MVT::v4i16);
459     addDRTypeForNEON(MVT::v2i32);
460     addDRTypeForNEON(MVT::v1i64);
461
462     addQRTypeForNEON(MVT::v4f32);
463     addQRTypeForNEON(MVT::v2f64);
464     addQRTypeForNEON(MVT::v16i8);
465     addQRTypeForNEON(MVT::v8i16);
466     addQRTypeForNEON(MVT::v4i32);
467     addQRTypeForNEON(MVT::v2i64);
468
469     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
470     // neither Neon nor VFP support any arithmetic operations on it.
471     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
472     // supported for v4f32.
473     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
474     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
476     // FIXME: Code duplication: FDIV and FREM are expanded always, see
477     // ARMTargetLowering::addTypeForNEON method for details.
478     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
479     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
480     // FIXME: Create unittest.
481     // In another words, find a way when "copysign" appears in DAG with vector
482     // operands.
483     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
484     // FIXME: Code duplication: SETCC has custom operation action, see
485     // ARMTargetLowering::addTypeForNEON method for details.
486     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
487     // FIXME: Create unittest for FNEG and for FABS.
488     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
489     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
490     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
492     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
493     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
495     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
498     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
500     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
501     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
502     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
503     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
504     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
506
507     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
517     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
518
519     // Neon does not support some operations on v1i64 and v2i64 types.
520     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
521     // Custom handling for some quad-vector types to detect VMULL.
522     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
523     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
524     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
525     // Custom handling for some vector types to avoid expensive expansions
526     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
529     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
530     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
531     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
532     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
533     // a destination type that is wider than the source, and nor does
534     // it have a FP_TO_[SU]INT instruction with a narrower destination than
535     // source.
536     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
537     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
538     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
539     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540
541     setTargetDAGCombine(ISD::INTRINSIC_VOID);
542     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
543     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
544     setTargetDAGCombine(ISD::SHL);
545     setTargetDAGCombine(ISD::SRL);
546     setTargetDAGCombine(ISD::SRA);
547     setTargetDAGCombine(ISD::SIGN_EXTEND);
548     setTargetDAGCombine(ISD::ZERO_EXTEND);
549     setTargetDAGCombine(ISD::ANY_EXTEND);
550     setTargetDAGCombine(ISD::SELECT_CC);
551     setTargetDAGCombine(ISD::BUILD_VECTOR);
552     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
553     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
554     setTargetDAGCombine(ISD::STORE);
555     setTargetDAGCombine(ISD::FP_TO_SINT);
556     setTargetDAGCombine(ISD::FP_TO_UINT);
557     setTargetDAGCombine(ISD::FDIV);
558
559     // It is legal to extload from v4i8 to v4i16 or v4i32.
560     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
561                   MVT::v4i16, MVT::v2i16,
562                   MVT::v2i32};
563     for (unsigned i = 0; i < 6; ++i) {
564       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
565       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
566       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
567     }
568   }
569
570   // ARM and Thumb2 support UMLAL/SMLAL.
571   if (!Subtarget->isThumb1Only())
572     setTargetDAGCombine(ISD::ADDC);
573
574
575   computeRegisterProperties();
576
577   // ARM does not have f32 extending load.
578   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
579
580   // ARM does not have i1 sign extending load.
581   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
582
583   // ARM supports all 4 flavors of integer indexed load / store.
584   if (!Subtarget->isThumb1Only()) {
585     for (unsigned im = (unsigned)ISD::PRE_INC;
586          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
587       setIndexedLoadAction(im,  MVT::i1,  Legal);
588       setIndexedLoadAction(im,  MVT::i8,  Legal);
589       setIndexedLoadAction(im,  MVT::i16, Legal);
590       setIndexedLoadAction(im,  MVT::i32, Legal);
591       setIndexedStoreAction(im, MVT::i1,  Legal);
592       setIndexedStoreAction(im, MVT::i8,  Legal);
593       setIndexedStoreAction(im, MVT::i16, Legal);
594       setIndexedStoreAction(im, MVT::i32, Legal);
595     }
596   }
597
598   // i64 operation support.
599   setOperationAction(ISD::MUL,     MVT::i64, Expand);
600   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
601   if (Subtarget->isThumb1Only()) {
602     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
603     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
604   }
605   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
606       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
607     setOperationAction(ISD::MULHS, MVT::i32, Expand);
608
609   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
610   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
611   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
612   setOperationAction(ISD::SRL,       MVT::i64, Custom);
613   setOperationAction(ISD::SRA,       MVT::i64, Custom);
614
615   if (!Subtarget->isThumb1Only()) {
616     // FIXME: We should do this for Thumb1 as well.
617     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
618     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
619     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
620     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
621   }
622
623   // ARM does not have ROTL.
624   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
625   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
626   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
627   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
628     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
629
630   // These just redirect to CTTZ and CTLZ on ARM.
631   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
632   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
633
634   // Only ARMv6 has BSWAP.
635   if (!Subtarget->hasV6Ops())
636     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
637
638   // These are expanded into libcalls.
639   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
640     // v7M has a hardware divider
641     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
642     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
643   }
644   setOperationAction(ISD::SREM,  MVT::i32, Expand);
645   setOperationAction(ISD::UREM,  MVT::i32, Expand);
646   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
647   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
648
649   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
650   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
651   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
652   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
653   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
654
655   setOperationAction(ISD::TRAP, MVT::Other, Legal);
656
657   // Use the default implementation.
658   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
659   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
660   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
661   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
662   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
663   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
664
665   if (!Subtarget->isTargetDarwin()) {
666     // Non-Darwin platforms may return values in these registers via the
667     // personality function.
668     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
669     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
670     setExceptionPointerRegister(ARM::R0);
671     setExceptionSelectorRegister(ARM::R1);
672   }
673
674   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
675   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
676   // the default expansion.
677   // FIXME: This should be checking for v6k, not just v6.
678   if (Subtarget->hasDataBarrier() ||
679       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
680     // membarrier needs custom lowering; the rest are legal and handled
681     // normally.
682     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
683     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
684     // Custom lowering for 64-bit ops
685     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
686     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
690     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
691     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
692     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
693     setInsertFencesForAtomic(true);
694   } else {
695     // Set them all for expansion, which will force libcalls.
696     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
697     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
698     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
710     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
711     // Unordered/Monotonic case.
712     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
713     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
714     // Since the libcalls include locking, fold in the fences
715     setShouldFoldAtomicFences(true);
716   }
717
718   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
719
720   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
721   if (!Subtarget->hasV6Ops()) {
722     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
723     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
724   }
725   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
726
727   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
728       !Subtarget->isThumb1Only()) {
729     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
730     // iff target supports vfp2.
731     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
732     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
733   }
734
735   // We want to custom lower some of our intrinsics.
736   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
737   if (Subtarget->isTargetDarwin()) {
738     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
739     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
740     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
741   }
742
743   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
744   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
745   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
746   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
747   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
748   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
749   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
750   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
751   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
752
753   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
754   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
755   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
756   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
757   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
758
759   // We don't support sin/cos/fmod/copysign/pow
760   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
761   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
762   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
763   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
764   setOperationAction(ISD::FREM,      MVT::f64, Expand);
765   setOperationAction(ISD::FREM,      MVT::f32, Expand);
766   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
767       !Subtarget->isThumb1Only()) {
768     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
769     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
770   }
771   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
772   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
773
774   if (!Subtarget->hasVFP4()) {
775     setOperationAction(ISD::FMA, MVT::f64, Expand);
776     setOperationAction(ISD::FMA, MVT::f32, Expand);
777   }
778
779   // Various VFP goodness
780   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
781     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
782     if (Subtarget->hasVFP2()) {
783       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
784       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
785       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
786       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
787     }
788     // Special handling for half-precision FP.
789     if (!Subtarget->hasFP16()) {
790       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
791       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
792     }
793   }
794
795   // We have target-specific dag combine patterns for the following nodes:
796   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
797   setTargetDAGCombine(ISD::ADD);
798   setTargetDAGCombine(ISD::SUB);
799   setTargetDAGCombine(ISD::MUL);
800   setTargetDAGCombine(ISD::AND);
801   setTargetDAGCombine(ISD::OR);
802   setTargetDAGCombine(ISD::XOR);
803
804   if (Subtarget->hasV6Ops())
805     setTargetDAGCombine(ISD::SRL);
806
807   setStackPointerRegisterToSaveRestore(ARM::SP);
808
809   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
810       !Subtarget->hasVFP2())
811     setSchedulingPreference(Sched::RegPressure);
812   else
813     setSchedulingPreference(Sched::Hybrid);
814
815   //// temporary - rewrite interface to use type
816   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
817   maxStoresPerMemset = 16;
818   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
819
820   // On ARM arguments smaller than 4 bytes are extended, so all arguments
821   // are at least 4 bytes aligned.
822   setMinStackArgumentAlignment(4);
823
824   benefitFromCodePlacementOpt = true;
825
826   // Prefer likely predicted branches to selects on out-of-order cores.
827   predictableSelectIsExpensive = Subtarget->isLikeA9();
828
829   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
830 }
831
832 // FIXME: It might make sense to define the representative register class as the
833 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
834 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
835 // SPR's representative would be DPR_VFP2. This should work well if register
836 // pressure tracking were modified such that a register use would increment the
837 // pressure of the register class's representative and all of it's super
838 // classes' representatives transitively. We have not implemented this because
839 // of the difficulty prior to coalescing of modeling operand register classes
840 // due to the common occurrence of cross class copies and subregister insertions
841 // and extractions.
842 std::pair<const TargetRegisterClass*, uint8_t>
843 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
844   const TargetRegisterClass *RRC = 0;
845   uint8_t Cost = 1;
846   switch (VT.getSimpleVT().SimpleTy) {
847   default:
848     return TargetLowering::findRepresentativeClass(VT);
849   // Use DPR as representative register class for all floating point
850   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
851   // the cost is 1 for both f32 and f64.
852   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
853   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
854     RRC = &ARM::DPRRegClass;
855     // When NEON is used for SP, only half of the register file is available
856     // because operations that define both SP and DP results will be constrained
857     // to the VFP2 class (D0-D15). We currently model this constraint prior to
858     // coalescing by double-counting the SP regs. See the FIXME above.
859     if (Subtarget->useNEONForSinglePrecisionFP())
860       Cost = 2;
861     break;
862   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
863   case MVT::v4f32: case MVT::v2f64:
864     RRC = &ARM::DPRRegClass;
865     Cost = 2;
866     break;
867   case MVT::v4i64:
868     RRC = &ARM::DPRRegClass;
869     Cost = 4;
870     break;
871   case MVT::v8i64:
872     RRC = &ARM::DPRRegClass;
873     Cost = 8;
874     break;
875   }
876   return std::make_pair(RRC, Cost);
877 }
878
879 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
880   switch (Opcode) {
881   default: return 0;
882   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
883   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
884   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
885   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
886   case ARMISD::CALL:          return "ARMISD::CALL";
887   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
888   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
889   case ARMISD::tCALL:         return "ARMISD::tCALL";
890   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
891   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
892   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
893   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
894   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
895   case ARMISD::CMP:           return "ARMISD::CMP";
896   case ARMISD::CMN:           return "ARMISD::CMN";
897   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
898   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
899   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
900   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
901   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
902
903   case ARMISD::CMOV:          return "ARMISD::CMOV";
904
905   case ARMISD::RBIT:          return "ARMISD::RBIT";
906
907   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
908   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
909   case ARMISD::SITOF:         return "ARMISD::SITOF";
910   case ARMISD::UITOF:         return "ARMISD::UITOF";
911
912   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
913   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
914   case ARMISD::RRX:           return "ARMISD::RRX";
915
916   case ARMISD::ADDC:          return "ARMISD::ADDC";
917   case ARMISD::ADDE:          return "ARMISD::ADDE";
918   case ARMISD::SUBC:          return "ARMISD::SUBC";
919   case ARMISD::SUBE:          return "ARMISD::SUBE";
920
921   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
922   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
923
924   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
925   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
926
927   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
928
929   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
930
931   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
932
933   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
934   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
935
936   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
937
938   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
939   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
940   case ARMISD::VCGE:          return "ARMISD::VCGE";
941   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
942   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
943   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
944   case ARMISD::VCGT:          return "ARMISD::VCGT";
945   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
946   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
947   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
948   case ARMISD::VTST:          return "ARMISD::VTST";
949
950   case ARMISD::VSHL:          return "ARMISD::VSHL";
951   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
952   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
953   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
954   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
955   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
956   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
957   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
958   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
959   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
960   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
961   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
962   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
963   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
964   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
965   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
966   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
967   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
968   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
969   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
970   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
971   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
972   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
973   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
974   case ARMISD::VDUP:          return "ARMISD::VDUP";
975   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
976   case ARMISD::VEXT:          return "ARMISD::VEXT";
977   case ARMISD::VREV64:        return "ARMISD::VREV64";
978   case ARMISD::VREV32:        return "ARMISD::VREV32";
979   case ARMISD::VREV16:        return "ARMISD::VREV16";
980   case ARMISD::VZIP:          return "ARMISD::VZIP";
981   case ARMISD::VUZP:          return "ARMISD::VUZP";
982   case ARMISD::VTRN:          return "ARMISD::VTRN";
983   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
984   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
985   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
986   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
987   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
988   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
989   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
990   case ARMISD::FMAX:          return "ARMISD::FMAX";
991   case ARMISD::FMIN:          return "ARMISD::FMIN";
992   case ARMISD::BFI:           return "ARMISD::BFI";
993   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
994   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
995   case ARMISD::VBSL:          return "ARMISD::VBSL";
996   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
997   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
998   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
999   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1000   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1001   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1002   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1003   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1004   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1005   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1006   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1007   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1008   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1009   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1010   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1011   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1012   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1013   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1014   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1015   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1016   }
1017 }
1018
1019 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1020   if (!VT.isVector()) return getPointerTy();
1021   return VT.changeVectorElementTypeToInteger();
1022 }
1023
1024 /// getRegClassFor - Return the register class that should be used for the
1025 /// specified value type.
1026 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1027   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1028   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1029   // load / store 4 to 8 consecutive D registers.
1030   if (Subtarget->hasNEON()) {
1031     if (VT == MVT::v4i64)
1032       return &ARM::QQPRRegClass;
1033     if (VT == MVT::v8i64)
1034       return &ARM::QQQQPRRegClass;
1035   }
1036   return TargetLowering::getRegClassFor(VT);
1037 }
1038
1039 // Create a fast isel object.
1040 FastISel *
1041 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1042                                   const TargetLibraryInfo *libInfo) const {
1043   return ARM::createFastISel(funcInfo, libInfo);
1044 }
1045
1046 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1047 /// be used for loads / stores from the global.
1048 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1049   return (Subtarget->isThumb1Only() ? 127 : 4095);
1050 }
1051
1052 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1053   unsigned NumVals = N->getNumValues();
1054   if (!NumVals)
1055     return Sched::RegPressure;
1056
1057   for (unsigned i = 0; i != NumVals; ++i) {
1058     EVT VT = N->getValueType(i);
1059     if (VT == MVT::Glue || VT == MVT::Other)
1060       continue;
1061     if (VT.isFloatingPoint() || VT.isVector())
1062       return Sched::ILP;
1063   }
1064
1065   if (!N->isMachineOpcode())
1066     return Sched::RegPressure;
1067
1068   // Load are scheduled for latency even if there instruction itinerary
1069   // is not available.
1070   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1071   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1072
1073   if (MCID.getNumDefs() == 0)
1074     return Sched::RegPressure;
1075   if (!Itins->isEmpty() &&
1076       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1077     return Sched::ILP;
1078
1079   return Sched::RegPressure;
1080 }
1081
1082 //===----------------------------------------------------------------------===//
1083 // Lowering Code
1084 //===----------------------------------------------------------------------===//
1085
1086 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1087 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1088   switch (CC) {
1089   default: llvm_unreachable("Unknown condition code!");
1090   case ISD::SETNE:  return ARMCC::NE;
1091   case ISD::SETEQ:  return ARMCC::EQ;
1092   case ISD::SETGT:  return ARMCC::GT;
1093   case ISD::SETGE:  return ARMCC::GE;
1094   case ISD::SETLT:  return ARMCC::LT;
1095   case ISD::SETLE:  return ARMCC::LE;
1096   case ISD::SETUGT: return ARMCC::HI;
1097   case ISD::SETUGE: return ARMCC::HS;
1098   case ISD::SETULT: return ARMCC::LO;
1099   case ISD::SETULE: return ARMCC::LS;
1100   }
1101 }
1102
1103 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1104 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1105                         ARMCC::CondCodes &CondCode2) {
1106   CondCode2 = ARMCC::AL;
1107   switch (CC) {
1108   default: llvm_unreachable("Unknown FP condition!");
1109   case ISD::SETEQ:
1110   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1111   case ISD::SETGT:
1112   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1113   case ISD::SETGE:
1114   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1115   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1116   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1117   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1118   case ISD::SETO:   CondCode = ARMCC::VC; break;
1119   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1120   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1121   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1122   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1123   case ISD::SETLT:
1124   case ISD::SETULT: CondCode = ARMCC::LT; break;
1125   case ISD::SETLE:
1126   case ISD::SETULE: CondCode = ARMCC::LE; break;
1127   case ISD::SETNE:
1128   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1129   }
1130 }
1131
1132 //===----------------------------------------------------------------------===//
1133 //                      Calling Convention Implementation
1134 //===----------------------------------------------------------------------===//
1135
1136 #include "ARMGenCallingConv.inc"
1137
1138 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1139 /// given CallingConvention value.
1140 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1141                                                  bool Return,
1142                                                  bool isVarArg) const {
1143   switch (CC) {
1144   default:
1145     llvm_unreachable("Unsupported calling convention");
1146   case CallingConv::Fast:
1147     if (Subtarget->hasVFP2() && !isVarArg) {
1148       if (!Subtarget->isAAPCS_ABI())
1149         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1150       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1151       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1152     }
1153     // Fallthrough
1154   case CallingConv::C: {
1155     // Use target triple & subtarget features to do actual dispatch.
1156     if (!Subtarget->isAAPCS_ABI())
1157       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1158     else if (Subtarget->hasVFP2() &&
1159              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1160              !isVarArg)
1161       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1162     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1163   }
1164   case CallingConv::ARM_AAPCS_VFP:
1165     if (!isVarArg)
1166       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1167     // Fallthrough
1168   case CallingConv::ARM_AAPCS:
1169     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1170   case CallingConv::ARM_APCS:
1171     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1172   case CallingConv::GHC:
1173     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1174   }
1175 }
1176
1177 /// LowerCallResult - Lower the result values of a call into the
1178 /// appropriate copies out of appropriate physical registers.
1179 SDValue
1180 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1181                                    CallingConv::ID CallConv, bool isVarArg,
1182                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1183                                    DebugLoc dl, SelectionDAG &DAG,
1184                                    SmallVectorImpl<SDValue> &InVals) const {
1185
1186   // Assign locations to each value returned by this call.
1187   SmallVector<CCValAssign, 16> RVLocs;
1188   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1189                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1190   CCInfo.AnalyzeCallResult(Ins,
1191                            CCAssignFnForNode(CallConv, /* Return*/ true,
1192                                              isVarArg));
1193
1194   // Copy all of the result registers out of their specified physreg.
1195   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1196     CCValAssign VA = RVLocs[i];
1197
1198     SDValue Val;
1199     if (VA.needsCustom()) {
1200       // Handle f64 or half of a v2f64.
1201       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1202                                       InFlag);
1203       Chain = Lo.getValue(1);
1204       InFlag = Lo.getValue(2);
1205       VA = RVLocs[++i]; // skip ahead to next loc
1206       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1207                                       InFlag);
1208       Chain = Hi.getValue(1);
1209       InFlag = Hi.getValue(2);
1210       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1211
1212       if (VA.getLocVT() == MVT::v2f64) {
1213         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1214         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1215                           DAG.getConstant(0, MVT::i32));
1216
1217         VA = RVLocs[++i]; // skip ahead to next loc
1218         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1219         Chain = Lo.getValue(1);
1220         InFlag = Lo.getValue(2);
1221         VA = RVLocs[++i]; // skip ahead to next loc
1222         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1223         Chain = Hi.getValue(1);
1224         InFlag = Hi.getValue(2);
1225         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1226         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1227                           DAG.getConstant(1, MVT::i32));
1228       }
1229     } else {
1230       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1231                                InFlag);
1232       Chain = Val.getValue(1);
1233       InFlag = Val.getValue(2);
1234     }
1235
1236     switch (VA.getLocInfo()) {
1237     default: llvm_unreachable("Unknown loc info!");
1238     case CCValAssign::Full: break;
1239     case CCValAssign::BCvt:
1240       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1241       break;
1242     }
1243
1244     InVals.push_back(Val);
1245   }
1246
1247   return Chain;
1248 }
1249
1250 /// LowerMemOpCallTo - Store the argument to the stack.
1251 SDValue
1252 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1253                                     SDValue StackPtr, SDValue Arg,
1254                                     DebugLoc dl, SelectionDAG &DAG,
1255                                     const CCValAssign &VA,
1256                                     ISD::ArgFlagsTy Flags) const {
1257   unsigned LocMemOffset = VA.getLocMemOffset();
1258   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1259   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1260   return DAG.getStore(Chain, dl, Arg, PtrOff,
1261                       MachinePointerInfo::getStack(LocMemOffset),
1262                       false, false, 0);
1263 }
1264
1265 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1266                                          SDValue Chain, SDValue &Arg,
1267                                          RegsToPassVector &RegsToPass,
1268                                          CCValAssign &VA, CCValAssign &NextVA,
1269                                          SDValue &StackPtr,
1270                                          SmallVector<SDValue, 8> &MemOpChains,
1271                                          ISD::ArgFlagsTy Flags) const {
1272
1273   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1274                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1275   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1276
1277   if (NextVA.isRegLoc())
1278     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1279   else {
1280     assert(NextVA.isMemLoc());
1281     if (StackPtr.getNode() == 0)
1282       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1283
1284     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1285                                            dl, DAG, NextVA,
1286                                            Flags));
1287   }
1288 }
1289
1290 /// LowerCall - Lowering a call into a callseq_start <-
1291 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1292 /// nodes.
1293 SDValue
1294 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1295                              SmallVectorImpl<SDValue> &InVals) const {
1296   SelectionDAG &DAG                     = CLI.DAG;
1297   DebugLoc &dl                          = CLI.DL;
1298   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1299   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1300   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1301   SDValue Chain                         = CLI.Chain;
1302   SDValue Callee                        = CLI.Callee;
1303   bool &isTailCall                      = CLI.IsTailCall;
1304   CallingConv::ID CallConv              = CLI.CallConv;
1305   bool doesNotRet                       = CLI.DoesNotReturn;
1306   bool isVarArg                         = CLI.IsVarArg;
1307
1308   MachineFunction &MF = DAG.getMachineFunction();
1309   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1310   bool IsSibCall = false;
1311   // Disable tail calls if they're not supported.
1312   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1313     isTailCall = false;
1314   if (isTailCall) {
1315     // Check if it's really possible to do a tail call.
1316     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1317                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1318                                                    Outs, OutVals, Ins, DAG);
1319     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1320     // detected sibcalls.
1321     if (isTailCall) {
1322       ++NumTailCalls;
1323       IsSibCall = true;
1324     }
1325   }
1326
1327   // Analyze operands of the call, assigning locations to each operand.
1328   SmallVector<CCValAssign, 16> ArgLocs;
1329   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1330                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1331   CCInfo.AnalyzeCallOperands(Outs,
1332                              CCAssignFnForNode(CallConv, /* Return*/ false,
1333                                                isVarArg));
1334
1335   // Get a count of how many bytes are to be pushed on the stack.
1336   unsigned NumBytes = CCInfo.getNextStackOffset();
1337
1338   // For tail calls, memory operands are available in our caller's stack.
1339   if (IsSibCall)
1340     NumBytes = 0;
1341
1342   // Adjust the stack pointer for the new arguments...
1343   // These operations are automatically eliminated by the prolog/epilog pass
1344   if (!IsSibCall)
1345     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1346
1347   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1348
1349   RegsToPassVector RegsToPass;
1350   SmallVector<SDValue, 8> MemOpChains;
1351
1352   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1353   // of tail call optimization, arguments are handled later.
1354   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1355        i != e;
1356        ++i, ++realArgIdx) {
1357     CCValAssign &VA = ArgLocs[i];
1358     SDValue Arg = OutVals[realArgIdx];
1359     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1360     bool isByVal = Flags.isByVal();
1361
1362     // Promote the value if needed.
1363     switch (VA.getLocInfo()) {
1364     default: llvm_unreachable("Unknown loc info!");
1365     case CCValAssign::Full: break;
1366     case CCValAssign::SExt:
1367       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1368       break;
1369     case CCValAssign::ZExt:
1370       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1371       break;
1372     case CCValAssign::AExt:
1373       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1374       break;
1375     case CCValAssign::BCvt:
1376       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1377       break;
1378     }
1379
1380     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1381     if (VA.needsCustom()) {
1382       if (VA.getLocVT() == MVT::v2f64) {
1383         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1384                                   DAG.getConstant(0, MVT::i32));
1385         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1386                                   DAG.getConstant(1, MVT::i32));
1387
1388         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1389                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1390
1391         VA = ArgLocs[++i]; // skip ahead to next loc
1392         if (VA.isRegLoc()) {
1393           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1394                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1395         } else {
1396           assert(VA.isMemLoc());
1397
1398           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1399                                                  dl, DAG, VA, Flags));
1400         }
1401       } else {
1402         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1403                          StackPtr, MemOpChains, Flags);
1404       }
1405     } else if (VA.isRegLoc()) {
1406       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1407     } else if (isByVal) {
1408       assert(VA.isMemLoc());
1409       unsigned offset = 0;
1410
1411       // True if this byval aggregate will be split between registers
1412       // and memory.
1413       if (CCInfo.isFirstByValRegValid()) {
1414         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1415         unsigned int i, j;
1416         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1417           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1418           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1419           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1420                                      MachinePointerInfo(),
1421                                      false, false, false, 0);
1422           MemOpChains.push_back(Load.getValue(1));
1423           RegsToPass.push_back(std::make_pair(j, Load));
1424         }
1425         offset = ARM::R4 - CCInfo.getFirstByValReg();
1426         CCInfo.clearFirstByValReg();
1427       }
1428
1429       if (Flags.getByValSize() - 4*offset > 0) {
1430         unsigned LocMemOffset = VA.getLocMemOffset();
1431         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1432         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1433                                   StkPtrOff);
1434         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1435         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1436         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1437                                            MVT::i32);
1438         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1439
1440         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1441         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1442         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1443                                           Ops, array_lengthof(Ops)));
1444       }
1445     } else if (!IsSibCall) {
1446       assert(VA.isMemLoc());
1447
1448       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1449                                              dl, DAG, VA, Flags));
1450     }
1451   }
1452
1453   if (!MemOpChains.empty())
1454     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1455                         &MemOpChains[0], MemOpChains.size());
1456
1457   // Build a sequence of copy-to-reg nodes chained together with token chain
1458   // and flag operands which copy the outgoing args into the appropriate regs.
1459   SDValue InFlag;
1460   // Tail call byval lowering might overwrite argument registers so in case of
1461   // tail call optimization the copies to registers are lowered later.
1462   if (!isTailCall)
1463     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1464       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1465                                RegsToPass[i].second, InFlag);
1466       InFlag = Chain.getValue(1);
1467     }
1468
1469   // For tail calls lower the arguments to the 'real' stack slot.
1470   if (isTailCall) {
1471     // Force all the incoming stack arguments to be loaded from the stack
1472     // before any new outgoing arguments are stored to the stack, because the
1473     // outgoing stack slots may alias the incoming argument stack slots, and
1474     // the alias isn't otherwise explicit. This is slightly more conservative
1475     // than necessary, because it means that each store effectively depends
1476     // on every argument instead of just those arguments it would clobber.
1477
1478     // Do not flag preceding copytoreg stuff together with the following stuff.
1479     InFlag = SDValue();
1480     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1481       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1482                                RegsToPass[i].second, InFlag);
1483       InFlag = Chain.getValue(1);
1484     }
1485     InFlag =SDValue();
1486   }
1487
1488   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1489   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1490   // node so that legalize doesn't hack it.
1491   bool isDirect = false;
1492   bool isARMFunc = false;
1493   bool isLocalARMFunc = false;
1494   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1495
1496   if (EnableARMLongCalls) {
1497     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1498             && "long-calls with non-static relocation model!");
1499     // Handle a global address or an external symbol. If it's not one of
1500     // those, the target's already in a register, so we don't need to do
1501     // anything extra.
1502     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1503       const GlobalValue *GV = G->getGlobal();
1504       // Create a constant pool entry for the callee address
1505       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1506       ARMConstantPoolValue *CPV =
1507         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1508
1509       // Get the address of the callee into a register
1510       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1511       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1512       Callee = DAG.getLoad(getPointerTy(), dl,
1513                            DAG.getEntryNode(), CPAddr,
1514                            MachinePointerInfo::getConstantPool(),
1515                            false, false, false, 0);
1516     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1517       const char *Sym = S->getSymbol();
1518
1519       // Create a constant pool entry for the callee address
1520       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1521       ARMConstantPoolValue *CPV =
1522         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1523                                       ARMPCLabelIndex, 0);
1524       // Get the address of the callee into a register
1525       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1526       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1527       Callee = DAG.getLoad(getPointerTy(), dl,
1528                            DAG.getEntryNode(), CPAddr,
1529                            MachinePointerInfo::getConstantPool(),
1530                            false, false, false, 0);
1531     }
1532   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1533     const GlobalValue *GV = G->getGlobal();
1534     isDirect = true;
1535     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1536     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1537                    getTargetMachine().getRelocationModel() != Reloc::Static;
1538     isARMFunc = !Subtarget->isThumb() || isStub;
1539     // ARM call to a local ARM function is predicable.
1540     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1541     // tBX takes a register source operand.
1542     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1543       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1544       ARMConstantPoolValue *CPV =
1545         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1546       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1547       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1548       Callee = DAG.getLoad(getPointerTy(), dl,
1549                            DAG.getEntryNode(), CPAddr,
1550                            MachinePointerInfo::getConstantPool(),
1551                            false, false, false, 0);
1552       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1553       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1554                            getPointerTy(), Callee, PICLabel);
1555     } else {
1556       // On ELF targets for PIC code, direct calls should go through the PLT
1557       unsigned OpFlags = 0;
1558       if (Subtarget->isTargetELF() &&
1559                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1560         OpFlags = ARMII::MO_PLT;
1561       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1562     }
1563   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1564     isDirect = true;
1565     bool isStub = Subtarget->isTargetDarwin() &&
1566                   getTargetMachine().getRelocationModel() != Reloc::Static;
1567     isARMFunc = !Subtarget->isThumb() || isStub;
1568     // tBX takes a register source operand.
1569     const char *Sym = S->getSymbol();
1570     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1571       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1572       ARMConstantPoolValue *CPV =
1573         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1574                                       ARMPCLabelIndex, 4);
1575       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1576       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1577       Callee = DAG.getLoad(getPointerTy(), dl,
1578                            DAG.getEntryNode(), CPAddr,
1579                            MachinePointerInfo::getConstantPool(),
1580                            false, false, false, 0);
1581       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1582       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1583                            getPointerTy(), Callee, PICLabel);
1584     } else {
1585       unsigned OpFlags = 0;
1586       // On ELF targets for PIC code, direct calls should go through the PLT
1587       if (Subtarget->isTargetELF() &&
1588                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1589         OpFlags = ARMII::MO_PLT;
1590       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1591     }
1592   }
1593
1594   // FIXME: handle tail calls differently.
1595   unsigned CallOpc;
1596   if (Subtarget->isThumb()) {
1597     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1598       CallOpc = ARMISD::CALL_NOLINK;
1599     else if (doesNotRet && isDirect && !isARMFunc &&
1600              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1601       // "mov lr, pc; b _foo" to avoid confusing the RSP
1602       CallOpc = ARMISD::CALL_NOLINK;
1603     else
1604       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1605   } else {
1606     if (!isDirect && !Subtarget->hasV5TOps()) {
1607       CallOpc = ARMISD::CALL_NOLINK;
1608     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1609       // "mov lr, pc; b _foo" to avoid confusing the RSP
1610       CallOpc = ARMISD::CALL_NOLINK;
1611     else
1612       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1613   }
1614
1615   std::vector<SDValue> Ops;
1616   Ops.push_back(Chain);
1617   Ops.push_back(Callee);
1618
1619   // Add argument registers to the end of the list so that they are known live
1620   // into the call.
1621   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1622     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1623                                   RegsToPass[i].second.getValueType()));
1624
1625   // Add a register mask operand representing the call-preserved registers.
1626   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1627   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1628   assert(Mask && "Missing call preserved mask for calling convention");
1629   Ops.push_back(DAG.getRegisterMask(Mask));
1630
1631   if (InFlag.getNode())
1632     Ops.push_back(InFlag);
1633
1634   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1635   if (isTailCall)
1636     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1637
1638   // Returns a chain and a flag for retval copy to use.
1639   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1640   InFlag = Chain.getValue(1);
1641
1642   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1643                              DAG.getIntPtrConstant(0, true), InFlag);
1644   if (!Ins.empty())
1645     InFlag = Chain.getValue(1);
1646
1647   // Handle result values, copying them out of physregs into vregs that we
1648   // return.
1649   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1650                          dl, DAG, InVals);
1651 }
1652
1653 /// HandleByVal - Every parameter *after* a byval parameter is passed
1654 /// on the stack.  Remember the next parameter register to allocate,
1655 /// and then confiscate the rest of the parameter registers to insure
1656 /// this.
1657 void
1658 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1659   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1660   assert((State->getCallOrPrologue() == Prologue ||
1661           State->getCallOrPrologue() == Call) &&
1662          "unhandled ParmContext");
1663   if ((!State->isFirstByValRegValid()) &&
1664       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1665     State->setFirstByValReg(reg);
1666     // At a call site, a byval parameter that is split between
1667     // registers and memory needs its size truncated here.  In a
1668     // function prologue, such byval parameters are reassembled in
1669     // memory, and are not truncated.
1670     if (State->getCallOrPrologue() == Call) {
1671       unsigned excess = 4 * (ARM::R4 - reg);
1672       assert(size >= excess && "expected larger existing stack allocation");
1673       size -= excess;
1674     }
1675   }
1676   // Confiscate any remaining parameter registers to preclude their
1677   // assignment to subsequent parameters.
1678   while (State->AllocateReg(GPRArgRegs, 4))
1679     ;
1680 }
1681
1682 /// MatchingStackOffset - Return true if the given stack call argument is
1683 /// already available in the same position (relatively) of the caller's
1684 /// incoming argument stack.
1685 static
1686 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1687                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1688                          const TargetInstrInfo *TII) {
1689   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1690   int FI = INT_MAX;
1691   if (Arg.getOpcode() == ISD::CopyFromReg) {
1692     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1693     if (!TargetRegisterInfo::isVirtualRegister(VR))
1694       return false;
1695     MachineInstr *Def = MRI->getVRegDef(VR);
1696     if (!Def)
1697       return false;
1698     if (!Flags.isByVal()) {
1699       if (!TII->isLoadFromStackSlot(Def, FI))
1700         return false;
1701     } else {
1702       return false;
1703     }
1704   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1705     if (Flags.isByVal())
1706       // ByVal argument is passed in as a pointer but it's now being
1707       // dereferenced. e.g.
1708       // define @foo(%struct.X* %A) {
1709       //   tail call @bar(%struct.X* byval %A)
1710       // }
1711       return false;
1712     SDValue Ptr = Ld->getBasePtr();
1713     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1714     if (!FINode)
1715       return false;
1716     FI = FINode->getIndex();
1717   } else
1718     return false;
1719
1720   assert(FI != INT_MAX);
1721   if (!MFI->isFixedObjectIndex(FI))
1722     return false;
1723   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1724 }
1725
1726 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1727 /// for tail call optimization. Targets which want to do tail call
1728 /// optimization should implement this function.
1729 bool
1730 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1731                                                      CallingConv::ID CalleeCC,
1732                                                      bool isVarArg,
1733                                                      bool isCalleeStructRet,
1734                                                      bool isCallerStructRet,
1735                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1736                                     const SmallVectorImpl<SDValue> &OutVals,
1737                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1738                                                      SelectionDAG& DAG) const {
1739   const Function *CallerF = DAG.getMachineFunction().getFunction();
1740   CallingConv::ID CallerCC = CallerF->getCallingConv();
1741   bool CCMatch = CallerCC == CalleeCC;
1742
1743   // Look for obvious safe cases to perform tail call optimization that do not
1744   // require ABI changes. This is what gcc calls sibcall.
1745
1746   // Do not sibcall optimize vararg calls unless the call site is not passing
1747   // any arguments.
1748   if (isVarArg && !Outs.empty())
1749     return false;
1750
1751   // Also avoid sibcall optimization if either caller or callee uses struct
1752   // return semantics.
1753   if (isCalleeStructRet || isCallerStructRet)
1754     return false;
1755
1756   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1757   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1758   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1759   // support in the assembler and linker to be used. This would need to be
1760   // fixed to fully support tail calls in Thumb1.
1761   //
1762   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1763   // LR.  This means if we need to reload LR, it takes an extra instructions,
1764   // which outweighs the value of the tail call; but here we don't know yet
1765   // whether LR is going to be used.  Probably the right approach is to
1766   // generate the tail call here and turn it back into CALL/RET in
1767   // emitEpilogue if LR is used.
1768
1769   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1770   // but we need to make sure there are enough registers; the only valid
1771   // registers are the 4 used for parameters.  We don't currently do this
1772   // case.
1773   if (Subtarget->isThumb1Only())
1774     return false;
1775
1776   // If the calling conventions do not match, then we'd better make sure the
1777   // results are returned in the same way as what the caller expects.
1778   if (!CCMatch) {
1779     SmallVector<CCValAssign, 16> RVLocs1;
1780     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1781                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1782     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1783
1784     SmallVector<CCValAssign, 16> RVLocs2;
1785     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1786                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1787     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1788
1789     if (RVLocs1.size() != RVLocs2.size())
1790       return false;
1791     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1792       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1793         return false;
1794       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1795         return false;
1796       if (RVLocs1[i].isRegLoc()) {
1797         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1798           return false;
1799       } else {
1800         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1801           return false;
1802       }
1803     }
1804   }
1805
1806   // If the callee takes no arguments then go on to check the results of the
1807   // call.
1808   if (!Outs.empty()) {
1809     // Check if stack adjustment is needed. For now, do not do this if any
1810     // argument is passed on the stack.
1811     SmallVector<CCValAssign, 16> ArgLocs;
1812     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1813                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1814     CCInfo.AnalyzeCallOperands(Outs,
1815                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1816     if (CCInfo.getNextStackOffset()) {
1817       MachineFunction &MF = DAG.getMachineFunction();
1818
1819       // Check if the arguments are already laid out in the right way as
1820       // the caller's fixed stack objects.
1821       MachineFrameInfo *MFI = MF.getFrameInfo();
1822       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1823       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1824       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1825            i != e;
1826            ++i, ++realArgIdx) {
1827         CCValAssign &VA = ArgLocs[i];
1828         EVT RegVT = VA.getLocVT();
1829         SDValue Arg = OutVals[realArgIdx];
1830         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831         if (VA.getLocInfo() == CCValAssign::Indirect)
1832           return false;
1833         if (VA.needsCustom()) {
1834           // f64 and vector types are split into multiple registers or
1835           // register/stack-slot combinations.  The types will not match
1836           // the registers; give up on memory f64 refs until we figure
1837           // out what to do about this.
1838           if (!VA.isRegLoc())
1839             return false;
1840           if (!ArgLocs[++i].isRegLoc())
1841             return false;
1842           if (RegVT == MVT::v2f64) {
1843             if (!ArgLocs[++i].isRegLoc())
1844               return false;
1845             if (!ArgLocs[++i].isRegLoc())
1846               return false;
1847           }
1848         } else if (!VA.isRegLoc()) {
1849           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1850                                    MFI, MRI, TII))
1851             return false;
1852         }
1853       }
1854     }
1855   }
1856
1857   return true;
1858 }
1859
1860 SDValue
1861 ARMTargetLowering::LowerReturn(SDValue Chain,
1862                                CallingConv::ID CallConv, bool isVarArg,
1863                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1864                                const SmallVectorImpl<SDValue> &OutVals,
1865                                DebugLoc dl, SelectionDAG &DAG) const {
1866
1867   // CCValAssign - represent the assignment of the return value to a location.
1868   SmallVector<CCValAssign, 16> RVLocs;
1869
1870   // CCState - Info about the registers and stack slots.
1871   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1872                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1873
1874   // Analyze outgoing return values.
1875   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1876                                                isVarArg));
1877
1878   // If this is the first return lowered for this function, add
1879   // the regs to the liveout set for the function.
1880   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1881     for (unsigned i = 0; i != RVLocs.size(); ++i)
1882       if (RVLocs[i].isRegLoc())
1883         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1884   }
1885
1886   SDValue Flag;
1887
1888   // Copy the result values into the output registers.
1889   for (unsigned i = 0, realRVLocIdx = 0;
1890        i != RVLocs.size();
1891        ++i, ++realRVLocIdx) {
1892     CCValAssign &VA = RVLocs[i];
1893     assert(VA.isRegLoc() && "Can only return in registers!");
1894
1895     SDValue Arg = OutVals[realRVLocIdx];
1896
1897     switch (VA.getLocInfo()) {
1898     default: llvm_unreachable("Unknown loc info!");
1899     case CCValAssign::Full: break;
1900     case CCValAssign::BCvt:
1901       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1902       break;
1903     }
1904
1905     if (VA.needsCustom()) {
1906       if (VA.getLocVT() == MVT::v2f64) {
1907         // Extract the first half and return it in two registers.
1908         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1909                                    DAG.getConstant(0, MVT::i32));
1910         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1911                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1912
1913         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1914         Flag = Chain.getValue(1);
1915         VA = RVLocs[++i]; // skip ahead to next loc
1916         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1917                                  HalfGPRs.getValue(1), Flag);
1918         Flag = Chain.getValue(1);
1919         VA = RVLocs[++i]; // skip ahead to next loc
1920
1921         // Extract the 2nd half and fall through to handle it as an f64 value.
1922         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1923                           DAG.getConstant(1, MVT::i32));
1924       }
1925       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1926       // available.
1927       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1928                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1929       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1930       Flag = Chain.getValue(1);
1931       VA = RVLocs[++i]; // skip ahead to next loc
1932       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1933                                Flag);
1934     } else
1935       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1936
1937     // Guarantee that all emitted copies are
1938     // stuck together, avoiding something bad.
1939     Flag = Chain.getValue(1);
1940   }
1941
1942   SDValue result;
1943   if (Flag.getNode())
1944     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1945   else // Return Void
1946     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1947
1948   return result;
1949 }
1950
1951 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1952   if (N->getNumValues() != 1)
1953     return false;
1954   if (!N->hasNUsesOfValue(1, 0))
1955     return false;
1956
1957   SDValue TCChain = Chain;
1958   SDNode *Copy = *N->use_begin();
1959   if (Copy->getOpcode() == ISD::CopyToReg) {
1960     // If the copy has a glue operand, we conservatively assume it isn't safe to
1961     // perform a tail call.
1962     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1963       return false;
1964     TCChain = Copy->getOperand(0);
1965   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1966     SDNode *VMov = Copy;
1967     // f64 returned in a pair of GPRs.
1968     SmallPtrSet<SDNode*, 2> Copies;
1969     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1970          UI != UE; ++UI) {
1971       if (UI->getOpcode() != ISD::CopyToReg)
1972         return false;
1973       Copies.insert(*UI);
1974     }
1975     if (Copies.size() > 2)
1976       return false;
1977
1978     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1979          UI != UE; ++UI) {
1980       SDValue UseChain = UI->getOperand(0);
1981       if (Copies.count(UseChain.getNode()))
1982         // Second CopyToReg
1983         Copy = *UI;
1984       else
1985         // First CopyToReg
1986         TCChain = UseChain;
1987     }
1988   } else if (Copy->getOpcode() == ISD::BITCAST) {
1989     // f32 returned in a single GPR.
1990     if (!Copy->hasOneUse())
1991       return false;
1992     Copy = *Copy->use_begin();
1993     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1994       return false;
1995     Chain = Copy->getOperand(0);
1996   } else {
1997     return false;
1998   }
1999
2000   bool HasRet = false;
2001   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2002        UI != UE; ++UI) {
2003     if (UI->getOpcode() != ARMISD::RET_FLAG)
2004       return false;
2005     HasRet = true;
2006   }
2007
2008   if (!HasRet)
2009     return false;
2010
2011   Chain = TCChain;
2012   return true;
2013 }
2014
2015 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2016   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2017     return false;
2018
2019   if (!CI->isTailCall())
2020     return false;
2021
2022   return !Subtarget->isThumb1Only();
2023 }
2024
2025 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2026 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2027 // one of the above mentioned nodes. It has to be wrapped because otherwise
2028 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2029 // be used to form addressing mode. These wrapped nodes will be selected
2030 // into MOVi.
2031 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2032   EVT PtrVT = Op.getValueType();
2033   // FIXME there is no actual debug info here
2034   DebugLoc dl = Op.getDebugLoc();
2035   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2036   SDValue Res;
2037   if (CP->isMachineConstantPoolEntry())
2038     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2039                                     CP->getAlignment());
2040   else
2041     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2042                                     CP->getAlignment());
2043   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2044 }
2045
2046 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2047   return MachineJumpTableInfo::EK_Inline;
2048 }
2049
2050 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2051                                              SelectionDAG &DAG) const {
2052   MachineFunction &MF = DAG.getMachineFunction();
2053   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2054   unsigned ARMPCLabelIndex = 0;
2055   DebugLoc DL = Op.getDebugLoc();
2056   EVT PtrVT = getPointerTy();
2057   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2058   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2059   SDValue CPAddr;
2060   if (RelocM == Reloc::Static) {
2061     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2062   } else {
2063     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2064     ARMPCLabelIndex = AFI->createPICLabelUId();
2065     ARMConstantPoolValue *CPV =
2066       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2067                                       ARMCP::CPBlockAddress, PCAdj);
2068     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2069   }
2070   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2071   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2072                                MachinePointerInfo::getConstantPool(),
2073                                false, false, false, 0);
2074   if (RelocM == Reloc::Static)
2075     return Result;
2076   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2077   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2078 }
2079
2080 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2081 SDValue
2082 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2083                                                  SelectionDAG &DAG) const {
2084   DebugLoc dl = GA->getDebugLoc();
2085   EVT PtrVT = getPointerTy();
2086   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2087   MachineFunction &MF = DAG.getMachineFunction();
2088   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2089   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2090   ARMConstantPoolValue *CPV =
2091     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2092                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2093   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2094   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2095   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2096                          MachinePointerInfo::getConstantPool(),
2097                          false, false, false, 0);
2098   SDValue Chain = Argument.getValue(1);
2099
2100   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2101   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2102
2103   // call __tls_get_addr.
2104   ArgListTy Args;
2105   ArgListEntry Entry;
2106   Entry.Node = Argument;
2107   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2108   Args.push_back(Entry);
2109   // FIXME: is there useful debug info available here?
2110   TargetLowering::CallLoweringInfo CLI(Chain,
2111                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2112                 false, false, false, false,
2113                 0, CallingConv::C, /*isTailCall=*/false,
2114                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2115                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2116   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2117   return CallResult.first;
2118 }
2119
2120 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2121 // "local exec" model.
2122 SDValue
2123 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2124                                         SelectionDAG &DAG,
2125                                         TLSModel::Model model) const {
2126   const GlobalValue *GV = GA->getGlobal();
2127   DebugLoc dl = GA->getDebugLoc();
2128   SDValue Offset;
2129   SDValue Chain = DAG.getEntryNode();
2130   EVT PtrVT = getPointerTy();
2131   // Get the Thread Pointer
2132   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2133
2134   if (model == TLSModel::InitialExec) {
2135     MachineFunction &MF = DAG.getMachineFunction();
2136     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2137     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2138     // Initial exec model.
2139     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2140     ARMConstantPoolValue *CPV =
2141       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2142                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2143                                       true);
2144     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2145     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2146     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2147                          MachinePointerInfo::getConstantPool(),
2148                          false, false, false, 0);
2149     Chain = Offset.getValue(1);
2150
2151     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2152     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2153
2154     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2155                          MachinePointerInfo::getConstantPool(),
2156                          false, false, false, 0);
2157   } else {
2158     // local exec model
2159     assert(model == TLSModel::LocalExec);
2160     ARMConstantPoolValue *CPV =
2161       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2162     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2163     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2164     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2165                          MachinePointerInfo::getConstantPool(),
2166                          false, false, false, 0);
2167   }
2168
2169   // The address of the thread local variable is the add of the thread
2170   // pointer with the offset of the variable.
2171   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2172 }
2173
2174 SDValue
2175 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2176   // TODO: implement the "local dynamic" model
2177   assert(Subtarget->isTargetELF() &&
2178          "TLS not implemented for non-ELF targets");
2179   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2180
2181   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2182
2183   switch (model) {
2184     case TLSModel::GeneralDynamic:
2185     case TLSModel::LocalDynamic:
2186       return LowerToTLSGeneralDynamicModel(GA, DAG);
2187     case TLSModel::InitialExec:
2188     case TLSModel::LocalExec:
2189       return LowerToTLSExecModels(GA, DAG, model);
2190   }
2191   llvm_unreachable("bogus TLS model");
2192 }
2193
2194 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2195                                                  SelectionDAG &DAG) const {
2196   EVT PtrVT = getPointerTy();
2197   DebugLoc dl = Op.getDebugLoc();
2198   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2199   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2200   if (RelocM == Reloc::PIC_) {
2201     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2202     ARMConstantPoolValue *CPV =
2203       ARMConstantPoolConstant::Create(GV,
2204                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2205     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2206     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2207     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2208                                  CPAddr,
2209                                  MachinePointerInfo::getConstantPool(),
2210                                  false, false, false, 0);
2211     SDValue Chain = Result.getValue(1);
2212     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2213     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2214     if (!UseGOTOFF)
2215       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2216                            MachinePointerInfo::getGOT(),
2217                            false, false, false, 0);
2218     return Result;
2219   }
2220
2221   // If we have T2 ops, we can materialize the address directly via movt/movw
2222   // pair. This is always cheaper.
2223   if (Subtarget->useMovt()) {
2224     ++NumMovwMovt;
2225     // FIXME: Once remat is capable of dealing with instructions with register
2226     // operands, expand this into two nodes.
2227     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2228                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2229   } else {
2230     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2231     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2232     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2233                        MachinePointerInfo::getConstantPool(),
2234                        false, false, false, 0);
2235   }
2236 }
2237
2238 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2239                                                     SelectionDAG &DAG) const {
2240   EVT PtrVT = getPointerTy();
2241   DebugLoc dl = Op.getDebugLoc();
2242   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2243   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2244   MachineFunction &MF = DAG.getMachineFunction();
2245   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2246
2247   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2248   // update ARMFastISel::ARMMaterializeGV.
2249   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2250     ++NumMovwMovt;
2251     // FIXME: Once remat is capable of dealing with instructions with register
2252     // operands, expand this into two nodes.
2253     if (RelocM == Reloc::Static)
2254       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2255                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2256
2257     unsigned Wrapper = (RelocM == Reloc::PIC_)
2258       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2259     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2260                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2261     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2262       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2263                            MachinePointerInfo::getGOT(),
2264                            false, false, false, 0);
2265     return Result;
2266   }
2267
2268   unsigned ARMPCLabelIndex = 0;
2269   SDValue CPAddr;
2270   if (RelocM == Reloc::Static) {
2271     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2272   } else {
2273     ARMPCLabelIndex = AFI->createPICLabelUId();
2274     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2275     ARMConstantPoolValue *CPV =
2276       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2277                                       PCAdj);
2278     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2279   }
2280   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2281
2282   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2283                                MachinePointerInfo::getConstantPool(),
2284                                false, false, false, 0);
2285   SDValue Chain = Result.getValue(1);
2286
2287   if (RelocM == Reloc::PIC_) {
2288     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2289     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2290   }
2291
2292   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2293     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2294                          false, false, false, 0);
2295
2296   return Result;
2297 }
2298
2299 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2300                                                     SelectionDAG &DAG) const {
2301   assert(Subtarget->isTargetELF() &&
2302          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2303   MachineFunction &MF = DAG.getMachineFunction();
2304   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2306   EVT PtrVT = getPointerTy();
2307   DebugLoc dl = Op.getDebugLoc();
2308   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2309   ARMConstantPoolValue *CPV =
2310     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2311                                   ARMPCLabelIndex, PCAdj);
2312   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2313   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2314   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2315                                MachinePointerInfo::getConstantPool(),
2316                                false, false, false, 0);
2317   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2318   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2319 }
2320
2321 SDValue
2322 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2323   DebugLoc dl = Op.getDebugLoc();
2324   SDValue Val = DAG.getConstant(0, MVT::i32);
2325   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2326                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2327                      Op.getOperand(1), Val);
2328 }
2329
2330 SDValue
2331 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2332   DebugLoc dl = Op.getDebugLoc();
2333   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2334                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2335 }
2336
2337 SDValue
2338 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2339                                           const ARMSubtarget *Subtarget) const {
2340   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2341   DebugLoc dl = Op.getDebugLoc();
2342   switch (IntNo) {
2343   default: return SDValue();    // Don't custom lower most intrinsics.
2344   case Intrinsic::arm_thread_pointer: {
2345     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2346     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2347   }
2348   case Intrinsic::eh_sjlj_lsda: {
2349     MachineFunction &MF = DAG.getMachineFunction();
2350     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2351     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2352     EVT PtrVT = getPointerTy();
2353     DebugLoc dl = Op.getDebugLoc();
2354     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2355     SDValue CPAddr;
2356     unsigned PCAdj = (RelocM != Reloc::PIC_)
2357       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2358     ARMConstantPoolValue *CPV =
2359       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2360                                       ARMCP::CPLSDA, PCAdj);
2361     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2362     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2363     SDValue Result =
2364       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2365                   MachinePointerInfo::getConstantPool(),
2366                   false, false, false, 0);
2367
2368     if (RelocM == Reloc::PIC_) {
2369       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2370       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2371     }
2372     return Result;
2373   }
2374   case Intrinsic::arm_neon_vmulls:
2375   case Intrinsic::arm_neon_vmullu: {
2376     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2377       ? ARMISD::VMULLs : ARMISD::VMULLu;
2378     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2379                        Op.getOperand(1), Op.getOperand(2));
2380   }
2381   }
2382 }
2383
2384 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2385                                const ARMSubtarget *Subtarget) {
2386   DebugLoc dl = Op.getDebugLoc();
2387   if (!Subtarget->hasDataBarrier()) {
2388     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2389     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2390     // here.
2391     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2392            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2393     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2394                        DAG.getConstant(0, MVT::i32));
2395   }
2396
2397   SDValue Op5 = Op.getOperand(5);
2398   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2399   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2400   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2401   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2402
2403   ARM_MB::MemBOpt DMBOpt;
2404   if (isDeviceBarrier)
2405     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2406   else
2407     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2408   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2409                      DAG.getConstant(DMBOpt, MVT::i32));
2410 }
2411
2412
2413 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2414                                  const ARMSubtarget *Subtarget) {
2415   // FIXME: handle "fence singlethread" more efficiently.
2416   DebugLoc dl = Op.getDebugLoc();
2417   if (!Subtarget->hasDataBarrier()) {
2418     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2419     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2420     // here.
2421     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2422            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2423     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2424                        DAG.getConstant(0, MVT::i32));
2425   }
2426
2427   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2428                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2429 }
2430
2431 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2432                              const ARMSubtarget *Subtarget) {
2433   // ARM pre v5TE and Thumb1 does not have preload instructions.
2434   if (!(Subtarget->isThumb2() ||
2435         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2436     // Just preserve the chain.
2437     return Op.getOperand(0);
2438
2439   DebugLoc dl = Op.getDebugLoc();
2440   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2441   if (!isRead &&
2442       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2443     // ARMv7 with MP extension has PLDW.
2444     return Op.getOperand(0);
2445
2446   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2447   if (Subtarget->isThumb()) {
2448     // Invert the bits.
2449     isRead = ~isRead & 1;
2450     isData = ~isData & 1;
2451   }
2452
2453   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2454                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2455                      DAG.getConstant(isData, MVT::i32));
2456 }
2457
2458 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2459   MachineFunction &MF = DAG.getMachineFunction();
2460   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2461
2462   // vastart just stores the address of the VarArgsFrameIndex slot into the
2463   // memory location argument.
2464   DebugLoc dl = Op.getDebugLoc();
2465   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2466   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2467   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2468   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2469                       MachinePointerInfo(SV), false, false, 0);
2470 }
2471
2472 SDValue
2473 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2474                                         SDValue &Root, SelectionDAG &DAG,
2475                                         DebugLoc dl) const {
2476   MachineFunction &MF = DAG.getMachineFunction();
2477   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2478
2479   const TargetRegisterClass *RC;
2480   if (AFI->isThumb1OnlyFunction())
2481     RC = &ARM::tGPRRegClass;
2482   else
2483     RC = &ARM::GPRRegClass;
2484
2485   // Transform the arguments stored in physical registers into virtual ones.
2486   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2487   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2488
2489   SDValue ArgValue2;
2490   if (NextVA.isMemLoc()) {
2491     MachineFrameInfo *MFI = MF.getFrameInfo();
2492     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2493
2494     // Create load node to retrieve arguments from the stack.
2495     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2496     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2497                             MachinePointerInfo::getFixedStack(FI),
2498                             false, false, false, 0);
2499   } else {
2500     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2501     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2502   }
2503
2504   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2505 }
2506
2507 void
2508 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2509                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2510   const {
2511   unsigned NumGPRs;
2512   if (CCInfo.isFirstByValRegValid())
2513     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2514   else {
2515     unsigned int firstUnalloced;
2516     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2517                                                 sizeof(GPRArgRegs) /
2518                                                 sizeof(GPRArgRegs[0]));
2519     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2520   }
2521
2522   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2523   VARegSize = NumGPRs * 4;
2524   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2525 }
2526
2527 // The remaining GPRs hold either the beginning of variable-argument
2528 // data, or the beginning of an aggregate passed by value (usuall
2529 // byval).  Either way, we allocate stack slots adjacent to the data
2530 // provided by our caller, and store the unallocated registers there.
2531 // If this is a variadic function, the va_list pointer will begin with
2532 // these values; otherwise, this reassembles a (byval) structure that
2533 // was split between registers and memory.
2534 void
2535 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2536                                         DebugLoc dl, SDValue &Chain,
2537                                         unsigned ArgOffset) const {
2538   MachineFunction &MF = DAG.getMachineFunction();
2539   MachineFrameInfo *MFI = MF.getFrameInfo();
2540   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2541   unsigned firstRegToSaveIndex;
2542   if (CCInfo.isFirstByValRegValid())
2543     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2544   else {
2545     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2546       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2547   }
2548
2549   unsigned VARegSize, VARegSaveSize;
2550   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2551   if (VARegSaveSize) {
2552     // If this function is vararg, store any remaining integer argument regs
2553     // to their spots on the stack so that they may be loaded by deferencing
2554     // the result of va_next.
2555     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2556     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2557                                                      ArgOffset + VARegSaveSize
2558                                                      - VARegSize,
2559                                                      false));
2560     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2561                                     getPointerTy());
2562
2563     SmallVector<SDValue, 4> MemOps;
2564     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2565       const TargetRegisterClass *RC;
2566       if (AFI->isThumb1OnlyFunction())
2567         RC = &ARM::tGPRRegClass;
2568       else
2569         RC = &ARM::GPRRegClass;
2570
2571       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2572       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2573       SDValue Store =
2574         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2575                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2576                      false, false, 0);
2577       MemOps.push_back(Store);
2578       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2579                         DAG.getConstant(4, getPointerTy()));
2580     }
2581     if (!MemOps.empty())
2582       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2583                           &MemOps[0], MemOps.size());
2584   } else
2585     // This will point to the next argument passed via stack.
2586     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2587 }
2588
2589 SDValue
2590 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2591                                         CallingConv::ID CallConv, bool isVarArg,
2592                                         const SmallVectorImpl<ISD::InputArg>
2593                                           &Ins,
2594                                         DebugLoc dl, SelectionDAG &DAG,
2595                                         SmallVectorImpl<SDValue> &InVals)
2596                                           const {
2597   MachineFunction &MF = DAG.getMachineFunction();
2598   MachineFrameInfo *MFI = MF.getFrameInfo();
2599
2600   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601
2602   // Assign locations to all of the incoming arguments.
2603   SmallVector<CCValAssign, 16> ArgLocs;
2604   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2605                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2606   CCInfo.AnalyzeFormalArguments(Ins,
2607                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2608                                                   isVarArg));
2609
2610   SmallVector<SDValue, 16> ArgValues;
2611   int lastInsIndex = -1;
2612
2613   SDValue ArgValue;
2614   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2615     CCValAssign &VA = ArgLocs[i];
2616
2617     // Arguments stored in registers.
2618     if (VA.isRegLoc()) {
2619       EVT RegVT = VA.getLocVT();
2620
2621       if (VA.needsCustom()) {
2622         // f64 and vector types are split up into multiple registers or
2623         // combinations of registers and stack slots.
2624         if (VA.getLocVT() == MVT::v2f64) {
2625           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2626                                                    Chain, DAG, dl);
2627           VA = ArgLocs[++i]; // skip ahead to next loc
2628           SDValue ArgValue2;
2629           if (VA.isMemLoc()) {
2630             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2631             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2632             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2633                                     MachinePointerInfo::getFixedStack(FI),
2634                                     false, false, false, 0);
2635           } else {
2636             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2637                                              Chain, DAG, dl);
2638           }
2639           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2640           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2641                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2642           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2643                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2644         } else
2645           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2646
2647       } else {
2648         const TargetRegisterClass *RC;
2649
2650         if (RegVT == MVT::f32)
2651           RC = &ARM::SPRRegClass;
2652         else if (RegVT == MVT::f64)
2653           RC = &ARM::DPRRegClass;
2654         else if (RegVT == MVT::v2f64)
2655           RC = &ARM::QPRRegClass;
2656         else if (RegVT == MVT::i32)
2657           RC = AFI->isThumb1OnlyFunction() ?
2658             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2659             (const TargetRegisterClass*)&ARM::GPRRegClass;
2660         else
2661           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2662
2663         // Transform the arguments in physical registers into virtual ones.
2664         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2665         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2666       }
2667
2668       // If this is an 8 or 16-bit value, it is really passed promoted
2669       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2670       // truncate to the right size.
2671       switch (VA.getLocInfo()) {
2672       default: llvm_unreachable("Unknown loc info!");
2673       case CCValAssign::Full: break;
2674       case CCValAssign::BCvt:
2675         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2676         break;
2677       case CCValAssign::SExt:
2678         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2679                                DAG.getValueType(VA.getValVT()));
2680         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2681         break;
2682       case CCValAssign::ZExt:
2683         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2684                                DAG.getValueType(VA.getValVT()));
2685         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2686         break;
2687       }
2688
2689       InVals.push_back(ArgValue);
2690
2691     } else { // VA.isRegLoc()
2692
2693       // sanity check
2694       assert(VA.isMemLoc());
2695       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2696
2697       int index = ArgLocs[i].getValNo();
2698
2699       // Some Ins[] entries become multiple ArgLoc[] entries.
2700       // Process them only once.
2701       if (index != lastInsIndex)
2702         {
2703           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2704           // FIXME: For now, all byval parameter objects are marked mutable.
2705           // This can be changed with more analysis.
2706           // In case of tail call optimization mark all arguments mutable.
2707           // Since they could be overwritten by lowering of arguments in case of
2708           // a tail call.
2709           if (Flags.isByVal()) {
2710             unsigned VARegSize, VARegSaveSize;
2711             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2712             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2713             unsigned Bytes = Flags.getByValSize() - VARegSize;
2714             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2715             int FI = MFI->CreateFixedObject(Bytes,
2716                                             VA.getLocMemOffset(), false);
2717             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2718           } else {
2719             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2720                                             VA.getLocMemOffset(), true);
2721
2722             // Create load nodes to retrieve arguments from the stack.
2723             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2724             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2725                                          MachinePointerInfo::getFixedStack(FI),
2726                                          false, false, false, 0));
2727           }
2728           lastInsIndex = index;
2729         }
2730     }
2731   }
2732
2733   // varargs
2734   if (isVarArg)
2735     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2736
2737   return Chain;
2738 }
2739
2740 /// isFloatingPointZero - Return true if this is +0.0.
2741 static bool isFloatingPointZero(SDValue Op) {
2742   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2743     return CFP->getValueAPF().isPosZero();
2744   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2745     // Maybe this has already been legalized into the constant pool?
2746     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2747       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2748       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2749         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2750           return CFP->getValueAPF().isPosZero();
2751     }
2752   }
2753   return false;
2754 }
2755
2756 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2757 /// the given operands.
2758 SDValue
2759 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2760                              SDValue &ARMcc, SelectionDAG &DAG,
2761                              DebugLoc dl) const {
2762   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2763     unsigned C = RHSC->getZExtValue();
2764     if (!isLegalICmpImmediate(C)) {
2765       // Constant does not fit, try adjusting it by one?
2766       switch (CC) {
2767       default: break;
2768       case ISD::SETLT:
2769       case ISD::SETGE:
2770         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2771           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2772           RHS = DAG.getConstant(C-1, MVT::i32);
2773         }
2774         break;
2775       case ISD::SETULT:
2776       case ISD::SETUGE:
2777         if (C != 0 && isLegalICmpImmediate(C-1)) {
2778           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2779           RHS = DAG.getConstant(C-1, MVT::i32);
2780         }
2781         break;
2782       case ISD::SETLE:
2783       case ISD::SETGT:
2784         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2785           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2786           RHS = DAG.getConstant(C+1, MVT::i32);
2787         }
2788         break;
2789       case ISD::SETULE:
2790       case ISD::SETUGT:
2791         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2792           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2793           RHS = DAG.getConstant(C+1, MVT::i32);
2794         }
2795         break;
2796       }
2797     }
2798   }
2799
2800   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2801   ARMISD::NodeType CompareType;
2802   switch (CondCode) {
2803   default:
2804     CompareType = ARMISD::CMP;
2805     break;
2806   case ARMCC::EQ:
2807   case ARMCC::NE:
2808     // Uses only Z Flag
2809     CompareType = ARMISD::CMPZ;
2810     break;
2811   }
2812   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2813   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2814 }
2815
2816 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2817 SDValue
2818 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2819                              DebugLoc dl) const {
2820   SDValue Cmp;
2821   if (!isFloatingPointZero(RHS))
2822     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2823   else
2824     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2825   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2826 }
2827
2828 /// duplicateCmp - Glue values can have only one use, so this function
2829 /// duplicates a comparison node.
2830 SDValue
2831 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2832   unsigned Opc = Cmp.getOpcode();
2833   DebugLoc DL = Cmp.getDebugLoc();
2834   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2835     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2836
2837   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2838   Cmp = Cmp.getOperand(0);
2839   Opc = Cmp.getOpcode();
2840   if (Opc == ARMISD::CMPFP)
2841     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2842   else {
2843     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2844     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2845   }
2846   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2847 }
2848
2849 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2850   SDValue Cond = Op.getOperand(0);
2851   SDValue SelectTrue = Op.getOperand(1);
2852   SDValue SelectFalse = Op.getOperand(2);
2853   DebugLoc dl = Op.getDebugLoc();
2854
2855   // Convert:
2856   //
2857   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2858   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2859   //
2860   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2861     const ConstantSDNode *CMOVTrue =
2862       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2863     const ConstantSDNode *CMOVFalse =
2864       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2865
2866     if (CMOVTrue && CMOVFalse) {
2867       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2868       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2869
2870       SDValue True;
2871       SDValue False;
2872       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2873         True = SelectTrue;
2874         False = SelectFalse;
2875       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2876         True = SelectFalse;
2877         False = SelectTrue;
2878       }
2879
2880       if (True.getNode() && False.getNode()) {
2881         EVT VT = Op.getValueType();
2882         SDValue ARMcc = Cond.getOperand(2);
2883         SDValue CCR = Cond.getOperand(3);
2884         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2885         assert(True.getValueType() == VT);
2886         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2887       }
2888     }
2889   }
2890
2891   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2892   // undefined bits before doing a full-word comparison with zero.
2893   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2894                      DAG.getConstant(1, Cond.getValueType()));
2895
2896   return DAG.getSelectCC(dl, Cond,
2897                          DAG.getConstant(0, Cond.getValueType()),
2898                          SelectTrue, SelectFalse, ISD::SETNE);
2899 }
2900
2901 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2902   EVT VT = Op.getValueType();
2903   SDValue LHS = Op.getOperand(0);
2904   SDValue RHS = Op.getOperand(1);
2905   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2906   SDValue TrueVal = Op.getOperand(2);
2907   SDValue FalseVal = Op.getOperand(3);
2908   DebugLoc dl = Op.getDebugLoc();
2909
2910   if (LHS.getValueType() == MVT::i32) {
2911     SDValue ARMcc;
2912     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2913     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2914     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2915   }
2916
2917   ARMCC::CondCodes CondCode, CondCode2;
2918   FPCCToARMCC(CC, CondCode, CondCode2);
2919
2920   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2921   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2922   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2923   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2924                                ARMcc, CCR, Cmp);
2925   if (CondCode2 != ARMCC::AL) {
2926     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2927     // FIXME: Needs another CMP because flag can have but one use.
2928     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2929     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2930                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2931   }
2932   return Result;
2933 }
2934
2935 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2936 /// to morph to an integer compare sequence.
2937 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2938                            const ARMSubtarget *Subtarget) {
2939   SDNode *N = Op.getNode();
2940   if (!N->hasOneUse())
2941     // Otherwise it requires moving the value from fp to integer registers.
2942     return false;
2943   if (!N->getNumValues())
2944     return false;
2945   EVT VT = Op.getValueType();
2946   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2947     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2948     // vmrs are very slow, e.g. cortex-a8.
2949     return false;
2950
2951   if (isFloatingPointZero(Op)) {
2952     SeenZero = true;
2953     return true;
2954   }
2955   return ISD::isNormalLoad(N);
2956 }
2957
2958 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2959   if (isFloatingPointZero(Op))
2960     return DAG.getConstant(0, MVT::i32);
2961
2962   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2963     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2964                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2965                        Ld->isVolatile(), Ld->isNonTemporal(),
2966                        Ld->isInvariant(), Ld->getAlignment());
2967
2968   llvm_unreachable("Unknown VFP cmp argument!");
2969 }
2970
2971 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2972                            SDValue &RetVal1, SDValue &RetVal2) {
2973   if (isFloatingPointZero(Op)) {
2974     RetVal1 = DAG.getConstant(0, MVT::i32);
2975     RetVal2 = DAG.getConstant(0, MVT::i32);
2976     return;
2977   }
2978
2979   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2980     SDValue Ptr = Ld->getBasePtr();
2981     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2982                           Ld->getChain(), Ptr,
2983                           Ld->getPointerInfo(),
2984                           Ld->isVolatile(), Ld->isNonTemporal(),
2985                           Ld->isInvariant(), Ld->getAlignment());
2986
2987     EVT PtrType = Ptr.getValueType();
2988     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2989     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2990                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2991     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2992                           Ld->getChain(), NewPtr,
2993                           Ld->getPointerInfo().getWithOffset(4),
2994                           Ld->isVolatile(), Ld->isNonTemporal(),
2995                           Ld->isInvariant(), NewAlign);
2996     return;
2997   }
2998
2999   llvm_unreachable("Unknown VFP cmp argument!");
3000 }
3001
3002 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3003 /// f32 and even f64 comparisons to integer ones.
3004 SDValue
3005 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3006   SDValue Chain = Op.getOperand(0);
3007   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3008   SDValue LHS = Op.getOperand(2);
3009   SDValue RHS = Op.getOperand(3);
3010   SDValue Dest = Op.getOperand(4);
3011   DebugLoc dl = Op.getDebugLoc();
3012
3013   bool LHSSeenZero = false;
3014   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3015   bool RHSSeenZero = false;
3016   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3017   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3018     // If unsafe fp math optimization is enabled and there are no other uses of
3019     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3020     // to an integer comparison.
3021     if (CC == ISD::SETOEQ)
3022       CC = ISD::SETEQ;
3023     else if (CC == ISD::SETUNE)
3024       CC = ISD::SETNE;
3025
3026     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3027     SDValue ARMcc;
3028     if (LHS.getValueType() == MVT::f32) {
3029       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3030                         bitcastf32Toi32(LHS, DAG), Mask);
3031       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3032                         bitcastf32Toi32(RHS, DAG), Mask);
3033       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3034       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3035       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3036                          Chain, Dest, ARMcc, CCR, Cmp);
3037     }
3038
3039     SDValue LHS1, LHS2;
3040     SDValue RHS1, RHS2;
3041     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3042     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3043     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3044     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3045     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3046     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3047     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3048     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3049     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3050   }
3051
3052   return SDValue();
3053 }
3054
3055 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3056   SDValue Chain = Op.getOperand(0);
3057   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3058   SDValue LHS = Op.getOperand(2);
3059   SDValue RHS = Op.getOperand(3);
3060   SDValue Dest = Op.getOperand(4);
3061   DebugLoc dl = Op.getDebugLoc();
3062
3063   if (LHS.getValueType() == MVT::i32) {
3064     SDValue ARMcc;
3065     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3066     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3067     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3068                        Chain, Dest, ARMcc, CCR, Cmp);
3069   }
3070
3071   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3072
3073   if (getTargetMachine().Options.UnsafeFPMath &&
3074       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3075        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3076     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3077     if (Result.getNode())
3078       return Result;
3079   }
3080
3081   ARMCC::CondCodes CondCode, CondCode2;
3082   FPCCToARMCC(CC, CondCode, CondCode2);
3083
3084   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3085   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3086   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3087   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3088   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3089   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3090   if (CondCode2 != ARMCC::AL) {
3091     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3092     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3093     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3094   }
3095   return Res;
3096 }
3097
3098 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3099   SDValue Chain = Op.getOperand(0);
3100   SDValue Table = Op.getOperand(1);
3101   SDValue Index = Op.getOperand(2);
3102   DebugLoc dl = Op.getDebugLoc();
3103
3104   EVT PTy = getPointerTy();
3105   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3106   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3107   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3108   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3109   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3110   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3111   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3112   if (Subtarget->isThumb2()) {
3113     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3114     // which does another jump to the destination. This also makes it easier
3115     // to translate it to TBB / TBH later.
3116     // FIXME: This might not work if the function is extremely large.
3117     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3118                        Addr, Op.getOperand(2), JTI, UId);
3119   }
3120   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3121     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3122                        MachinePointerInfo::getJumpTable(),
3123                        false, false, false, 0);
3124     Chain = Addr.getValue(1);
3125     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3126     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3127   } else {
3128     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3129                        MachinePointerInfo::getJumpTable(),
3130                        false, false, false, 0);
3131     Chain = Addr.getValue(1);
3132     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3133   }
3134 }
3135
3136 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3137   EVT VT = Op.getValueType();
3138   DebugLoc dl = Op.getDebugLoc();
3139
3140   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3141     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3142       return Op;
3143     return DAG.UnrollVectorOp(Op.getNode());
3144   }
3145
3146   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3147          "Invalid type for custom lowering!");
3148   if (VT != MVT::v4i16)
3149     return DAG.UnrollVectorOp(Op.getNode());
3150
3151   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3152   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3153 }
3154
3155 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3156   EVT VT = Op.getValueType();
3157   if (VT.isVector())
3158     return LowerVectorFP_TO_INT(Op, DAG);
3159
3160   DebugLoc dl = Op.getDebugLoc();
3161   unsigned Opc;
3162
3163   switch (Op.getOpcode()) {
3164   default: llvm_unreachable("Invalid opcode!");
3165   case ISD::FP_TO_SINT:
3166     Opc = ARMISD::FTOSI;
3167     break;
3168   case ISD::FP_TO_UINT:
3169     Opc = ARMISD::FTOUI;
3170     break;
3171   }
3172   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3173   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3174 }
3175
3176 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3177   EVT VT = Op.getValueType();
3178   DebugLoc dl = Op.getDebugLoc();
3179
3180   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3181     if (VT.getVectorElementType() == MVT::f32)
3182       return Op;
3183     return DAG.UnrollVectorOp(Op.getNode());
3184   }
3185
3186   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3187          "Invalid type for custom lowering!");
3188   if (VT != MVT::v4f32)
3189     return DAG.UnrollVectorOp(Op.getNode());
3190
3191   unsigned CastOpc;
3192   unsigned Opc;
3193   switch (Op.getOpcode()) {
3194   default: llvm_unreachable("Invalid opcode!");
3195   case ISD::SINT_TO_FP:
3196     CastOpc = ISD::SIGN_EXTEND;
3197     Opc = ISD::SINT_TO_FP;
3198     break;
3199   case ISD::UINT_TO_FP:
3200     CastOpc = ISD::ZERO_EXTEND;
3201     Opc = ISD::UINT_TO_FP;
3202     break;
3203   }
3204
3205   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3206   return DAG.getNode(Opc, dl, VT, Op);
3207 }
3208
3209 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3210   EVT VT = Op.getValueType();
3211   if (VT.isVector())
3212     return LowerVectorINT_TO_FP(Op, DAG);
3213
3214   DebugLoc dl = Op.getDebugLoc();
3215   unsigned Opc;
3216
3217   switch (Op.getOpcode()) {
3218   default: llvm_unreachable("Invalid opcode!");
3219   case ISD::SINT_TO_FP:
3220     Opc = ARMISD::SITOF;
3221     break;
3222   case ISD::UINT_TO_FP:
3223     Opc = ARMISD::UITOF;
3224     break;
3225   }
3226
3227   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3228   return DAG.getNode(Opc, dl, VT, Op);
3229 }
3230
3231 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3232   // Implement fcopysign with a fabs and a conditional fneg.
3233   SDValue Tmp0 = Op.getOperand(0);
3234   SDValue Tmp1 = Op.getOperand(1);
3235   DebugLoc dl = Op.getDebugLoc();
3236   EVT VT = Op.getValueType();
3237   EVT SrcVT = Tmp1.getValueType();
3238   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3239     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3240   bool UseNEON = !InGPR && Subtarget->hasNEON();
3241
3242   if (UseNEON) {
3243     // Use VBSL to copy the sign bit.
3244     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3245     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3246                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3247     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3248     if (VT == MVT::f64)
3249       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3250                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3251                          DAG.getConstant(32, MVT::i32));
3252     else /*if (VT == MVT::f32)*/
3253       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3254     if (SrcVT == MVT::f32) {
3255       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3256       if (VT == MVT::f64)
3257         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3258                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3259                            DAG.getConstant(32, MVT::i32));
3260     } else if (VT == MVT::f32)
3261       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3262                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3263                          DAG.getConstant(32, MVT::i32));
3264     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3265     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3266
3267     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3268                                             MVT::i32);
3269     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3270     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3271                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3272
3273     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3274                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3275                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3276     if (VT == MVT::f32) {
3277       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3278       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3279                         DAG.getConstant(0, MVT::i32));
3280     } else {
3281       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3282     }
3283
3284     return Res;
3285   }
3286
3287   // Bitcast operand 1 to i32.
3288   if (SrcVT == MVT::f64)
3289     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3290                        &Tmp1, 1).getValue(1);
3291   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3292
3293   // Or in the signbit with integer operations.
3294   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3295   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3296   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3297   if (VT == MVT::f32) {
3298     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3299                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3300     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3301                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3302   }
3303
3304   // f64: Or the high part with signbit and then combine two parts.
3305   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3306                      &Tmp0, 1);
3307   SDValue Lo = Tmp0.getValue(0);
3308   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3309   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3310   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3311 }
3312
3313 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3314   MachineFunction &MF = DAG.getMachineFunction();
3315   MachineFrameInfo *MFI = MF.getFrameInfo();
3316   MFI->setReturnAddressIsTaken(true);
3317
3318   EVT VT = Op.getValueType();
3319   DebugLoc dl = Op.getDebugLoc();
3320   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3321   if (Depth) {
3322     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3323     SDValue Offset = DAG.getConstant(4, MVT::i32);
3324     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3325                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3326                        MachinePointerInfo(), false, false, false, 0);
3327   }
3328
3329   // Return LR, which contains the return address. Mark it an implicit live-in.
3330   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3331   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3332 }
3333
3334 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3335   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3336   MFI->setFrameAddressIsTaken(true);
3337
3338   EVT VT = Op.getValueType();
3339   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3340   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3341   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3342     ? ARM::R7 : ARM::R11;
3343   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3344   while (Depth--)
3345     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3346                             MachinePointerInfo(),
3347                             false, false, false, 0);
3348   return FrameAddr;
3349 }
3350
3351 /// ExpandBITCAST - If the target supports VFP, this function is called to
3352 /// expand a bit convert where either the source or destination type is i64 to
3353 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3354 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3355 /// vectors), since the legalizer won't know what to do with that.
3356 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3358   DebugLoc dl = N->getDebugLoc();
3359   SDValue Op = N->getOperand(0);
3360
3361   // This function is only supposed to be called for i64 types, either as the
3362   // source or destination of the bit convert.
3363   EVT SrcVT = Op.getValueType();
3364   EVT DstVT = N->getValueType(0);
3365   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3366          "ExpandBITCAST called for non-i64 type");
3367
3368   // Turn i64->f64 into VMOVDRR.
3369   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3370     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3371                              DAG.getConstant(0, MVT::i32));
3372     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3373                              DAG.getConstant(1, MVT::i32));
3374     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3375                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3376   }
3377
3378   // Turn f64->i64 into VMOVRRD.
3379   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3380     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3381                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3382     // Merge the pieces into a single i64 value.
3383     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3384   }
3385
3386   return SDValue();
3387 }
3388
3389 /// getZeroVector - Returns a vector of specified type with all zero elements.
3390 /// Zero vectors are used to represent vector negation and in those cases
3391 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3392 /// not support i64 elements, so sometimes the zero vectors will need to be
3393 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3394 /// zero vector.
3395 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3396   assert(VT.isVector() && "Expected a vector type");
3397   // The canonical modified immediate encoding of a zero vector is....0!
3398   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3399   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3400   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3401   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3402 }
3403
3404 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3405 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3406 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3407                                                 SelectionDAG &DAG) const {
3408   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3409   EVT VT = Op.getValueType();
3410   unsigned VTBits = VT.getSizeInBits();
3411   DebugLoc dl = Op.getDebugLoc();
3412   SDValue ShOpLo = Op.getOperand(0);
3413   SDValue ShOpHi = Op.getOperand(1);
3414   SDValue ShAmt  = Op.getOperand(2);
3415   SDValue ARMcc;
3416   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3417
3418   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3419
3420   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3421                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3422   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3423   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3424                                    DAG.getConstant(VTBits, MVT::i32));
3425   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3426   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3427   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3428
3429   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3430   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3431                           ARMcc, DAG, dl);
3432   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3433   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3434                            CCR, Cmp);
3435
3436   SDValue Ops[2] = { Lo, Hi };
3437   return DAG.getMergeValues(Ops, 2, dl);
3438 }
3439
3440 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3441 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3442 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3443                                                SelectionDAG &DAG) const {
3444   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3445   EVT VT = Op.getValueType();
3446   unsigned VTBits = VT.getSizeInBits();
3447   DebugLoc dl = Op.getDebugLoc();
3448   SDValue ShOpLo = Op.getOperand(0);
3449   SDValue ShOpHi = Op.getOperand(1);
3450   SDValue ShAmt  = Op.getOperand(2);
3451   SDValue ARMcc;
3452
3453   assert(Op.getOpcode() == ISD::SHL_PARTS);
3454   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3455                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3456   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3457   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3458                                    DAG.getConstant(VTBits, MVT::i32));
3459   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3460   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3461
3462   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3463   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3464   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3465                           ARMcc, DAG, dl);
3466   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3467   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3468                            CCR, Cmp);
3469
3470   SDValue Ops[2] = { Lo, Hi };
3471   return DAG.getMergeValues(Ops, 2, dl);
3472 }
3473
3474 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3475                                             SelectionDAG &DAG) const {
3476   // The rounding mode is in bits 23:22 of the FPSCR.
3477   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3478   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3479   // so that the shift + and get folded into a bitfield extract.
3480   DebugLoc dl = Op.getDebugLoc();
3481   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3482                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3483                                               MVT::i32));
3484   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3485                                   DAG.getConstant(1U << 22, MVT::i32));
3486   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3487                               DAG.getConstant(22, MVT::i32));
3488   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3489                      DAG.getConstant(3, MVT::i32));
3490 }
3491
3492 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3493                          const ARMSubtarget *ST) {
3494   EVT VT = N->getValueType(0);
3495   DebugLoc dl = N->getDebugLoc();
3496
3497   if (!ST->hasV6T2Ops())
3498     return SDValue();
3499
3500   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3501   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3502 }
3503
3504 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3505                           const ARMSubtarget *ST) {
3506   EVT VT = N->getValueType(0);
3507   DebugLoc dl = N->getDebugLoc();
3508
3509   if (!VT.isVector())
3510     return SDValue();
3511
3512   // Lower vector shifts on NEON to use VSHL.
3513   assert(ST->hasNEON() && "unexpected vector shift");
3514
3515   // Left shifts translate directly to the vshiftu intrinsic.
3516   if (N->getOpcode() == ISD::SHL)
3517     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3518                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3519                        N->getOperand(0), N->getOperand(1));
3520
3521   assert((N->getOpcode() == ISD::SRA ||
3522           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3523
3524   // NEON uses the same intrinsics for both left and right shifts.  For
3525   // right shifts, the shift amounts are negative, so negate the vector of
3526   // shift amounts.
3527   EVT ShiftVT = N->getOperand(1).getValueType();
3528   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3529                                      getZeroVector(ShiftVT, DAG, dl),
3530                                      N->getOperand(1));
3531   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3532                              Intrinsic::arm_neon_vshifts :
3533                              Intrinsic::arm_neon_vshiftu);
3534   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3535                      DAG.getConstant(vshiftInt, MVT::i32),
3536                      N->getOperand(0), NegatedCount);
3537 }
3538
3539 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3540                                 const ARMSubtarget *ST) {
3541   EVT VT = N->getValueType(0);
3542   DebugLoc dl = N->getDebugLoc();
3543
3544   // We can get here for a node like i32 = ISD::SHL i32, i64
3545   if (VT != MVT::i64)
3546     return SDValue();
3547
3548   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3549          "Unknown shift to lower!");
3550
3551   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3552   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3553       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3554     return SDValue();
3555
3556   // If we are in thumb mode, we don't have RRX.
3557   if (ST->isThumb1Only()) return SDValue();
3558
3559   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3560   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3561                            DAG.getConstant(0, MVT::i32));
3562   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3563                            DAG.getConstant(1, MVT::i32));
3564
3565   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3566   // captures the result into a carry flag.
3567   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3568   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3569
3570   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3571   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3572
3573   // Merge the pieces into a single i64 value.
3574  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3575 }
3576
3577 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3578   SDValue TmpOp0, TmpOp1;
3579   bool Invert = false;
3580   bool Swap = false;
3581   unsigned Opc = 0;
3582
3583   SDValue Op0 = Op.getOperand(0);
3584   SDValue Op1 = Op.getOperand(1);
3585   SDValue CC = Op.getOperand(2);
3586   EVT VT = Op.getValueType();
3587   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3588   DebugLoc dl = Op.getDebugLoc();
3589
3590   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3591     switch (SetCCOpcode) {
3592     default: llvm_unreachable("Illegal FP comparison");
3593     case ISD::SETUNE:
3594     case ISD::SETNE:  Invert = true; // Fallthrough
3595     case ISD::SETOEQ:
3596     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3597     case ISD::SETOLT:
3598     case ISD::SETLT: Swap = true; // Fallthrough
3599     case ISD::SETOGT:
3600     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3601     case ISD::SETOLE:
3602     case ISD::SETLE:  Swap = true; // Fallthrough
3603     case ISD::SETOGE:
3604     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3605     case ISD::SETUGE: Swap = true; // Fallthrough
3606     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3607     case ISD::SETUGT: Swap = true; // Fallthrough
3608     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3609     case ISD::SETUEQ: Invert = true; // Fallthrough
3610     case ISD::SETONE:
3611       // Expand this to (OLT | OGT).
3612       TmpOp0 = Op0;
3613       TmpOp1 = Op1;
3614       Opc = ISD::OR;
3615       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3616       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3617       break;
3618     case ISD::SETUO: Invert = true; // Fallthrough
3619     case ISD::SETO:
3620       // Expand this to (OLT | OGE).
3621       TmpOp0 = Op0;
3622       TmpOp1 = Op1;
3623       Opc = ISD::OR;
3624       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3625       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3626       break;
3627     }
3628   } else {
3629     // Integer comparisons.
3630     switch (SetCCOpcode) {
3631     default: llvm_unreachable("Illegal integer comparison");
3632     case ISD::SETNE:  Invert = true;
3633     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3634     case ISD::SETLT:  Swap = true;
3635     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3636     case ISD::SETLE:  Swap = true;
3637     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3638     case ISD::SETULT: Swap = true;
3639     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3640     case ISD::SETULE: Swap = true;
3641     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3642     }
3643
3644     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3645     if (Opc == ARMISD::VCEQ) {
3646
3647       SDValue AndOp;
3648       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3649         AndOp = Op0;
3650       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3651         AndOp = Op1;
3652
3653       // Ignore bitconvert.
3654       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3655         AndOp = AndOp.getOperand(0);
3656
3657       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3658         Opc = ARMISD::VTST;
3659         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3660         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3661         Invert = !Invert;
3662       }
3663     }
3664   }
3665
3666   if (Swap)
3667     std::swap(Op0, Op1);
3668
3669   // If one of the operands is a constant vector zero, attempt to fold the
3670   // comparison to a specialized compare-against-zero form.
3671   SDValue SingleOp;
3672   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3673     SingleOp = Op0;
3674   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3675     if (Opc == ARMISD::VCGE)
3676       Opc = ARMISD::VCLEZ;
3677     else if (Opc == ARMISD::VCGT)
3678       Opc = ARMISD::VCLTZ;
3679     SingleOp = Op1;
3680   }
3681
3682   SDValue Result;
3683   if (SingleOp.getNode()) {
3684     switch (Opc) {
3685     case ARMISD::VCEQ:
3686       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3687     case ARMISD::VCGE:
3688       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3689     case ARMISD::VCLEZ:
3690       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3691     case ARMISD::VCGT:
3692       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3693     case ARMISD::VCLTZ:
3694       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3695     default:
3696       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3697     }
3698   } else {
3699      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3700   }
3701
3702   if (Invert)
3703     Result = DAG.getNOT(dl, Result, VT);
3704
3705   return Result;
3706 }
3707
3708 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3709 /// valid vector constant for a NEON instruction with a "modified immediate"
3710 /// operand (e.g., VMOV).  If so, return the encoded value.
3711 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3712                                  unsigned SplatBitSize, SelectionDAG &DAG,
3713                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3714   unsigned OpCmode, Imm;
3715
3716   // SplatBitSize is set to the smallest size that splats the vector, so a
3717   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3718   // immediate instructions others than VMOV do not support the 8-bit encoding
3719   // of a zero vector, and the default encoding of zero is supposed to be the
3720   // 32-bit version.
3721   if (SplatBits == 0)
3722     SplatBitSize = 32;
3723
3724   switch (SplatBitSize) {
3725   case 8:
3726     if (type != VMOVModImm)
3727       return SDValue();
3728     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3729     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3730     OpCmode = 0xe;
3731     Imm = SplatBits;
3732     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3733     break;
3734
3735   case 16:
3736     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3737     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3738     if ((SplatBits & ~0xff) == 0) {
3739       // Value = 0x00nn: Op=x, Cmode=100x.
3740       OpCmode = 0x8;
3741       Imm = SplatBits;
3742       break;
3743     }
3744     if ((SplatBits & ~0xff00) == 0) {
3745       // Value = 0xnn00: Op=x, Cmode=101x.
3746       OpCmode = 0xa;
3747       Imm = SplatBits >> 8;
3748       break;
3749     }
3750     return SDValue();
3751
3752   case 32:
3753     // NEON's 32-bit VMOV supports splat values where:
3754     // * only one byte is nonzero, or
3755     // * the least significant byte is 0xff and the second byte is nonzero, or
3756     // * the least significant 2 bytes are 0xff and the third is nonzero.
3757     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3758     if ((SplatBits & ~0xff) == 0) {
3759       // Value = 0x000000nn: Op=x, Cmode=000x.
3760       OpCmode = 0;
3761       Imm = SplatBits;
3762       break;
3763     }
3764     if ((SplatBits & ~0xff00) == 0) {
3765       // Value = 0x0000nn00: Op=x, Cmode=001x.
3766       OpCmode = 0x2;
3767       Imm = SplatBits >> 8;
3768       break;
3769     }
3770     if ((SplatBits & ~0xff0000) == 0) {
3771       // Value = 0x00nn0000: Op=x, Cmode=010x.
3772       OpCmode = 0x4;
3773       Imm = SplatBits >> 16;
3774       break;
3775     }
3776     if ((SplatBits & ~0xff000000) == 0) {
3777       // Value = 0xnn000000: Op=x, Cmode=011x.
3778       OpCmode = 0x6;
3779       Imm = SplatBits >> 24;
3780       break;
3781     }
3782
3783     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3784     if (type == OtherModImm) return SDValue();
3785
3786     if ((SplatBits & ~0xffff) == 0 &&
3787         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3788       // Value = 0x0000nnff: Op=x, Cmode=1100.
3789       OpCmode = 0xc;
3790       Imm = SplatBits >> 8;
3791       SplatBits |= 0xff;
3792       break;
3793     }
3794
3795     if ((SplatBits & ~0xffffff) == 0 &&
3796         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3797       // Value = 0x00nnffff: Op=x, Cmode=1101.
3798       OpCmode = 0xd;
3799       Imm = SplatBits >> 16;
3800       SplatBits |= 0xffff;
3801       break;
3802     }
3803
3804     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3805     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3806     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3807     // and fall through here to test for a valid 64-bit splat.  But, then the
3808     // caller would also need to check and handle the change in size.
3809     return SDValue();
3810
3811   case 64: {
3812     if (type != VMOVModImm)
3813       return SDValue();
3814     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3815     uint64_t BitMask = 0xff;
3816     uint64_t Val = 0;
3817     unsigned ImmMask = 1;
3818     Imm = 0;
3819     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3820       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3821         Val |= BitMask;
3822         Imm |= ImmMask;
3823       } else if ((SplatBits & BitMask) != 0) {
3824         return SDValue();
3825       }
3826       BitMask <<= 8;
3827       ImmMask <<= 1;
3828     }
3829     // Op=1, Cmode=1110.
3830     OpCmode = 0x1e;
3831     SplatBits = Val;
3832     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3833     break;
3834   }
3835
3836   default:
3837     llvm_unreachable("unexpected size for isNEONModifiedImm");
3838   }
3839
3840   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3841   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3842 }
3843
3844 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3845                                            const ARMSubtarget *ST) const {
3846   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3847     return SDValue();
3848
3849   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3850   assert(Op.getValueType() == MVT::f32 &&
3851          "ConstantFP custom lowering should only occur for f32.");
3852
3853   // Try splatting with a VMOV.f32...
3854   APFloat FPVal = CFP->getValueAPF();
3855   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3856   if (ImmVal != -1) {
3857     DebugLoc DL = Op.getDebugLoc();
3858     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3859     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3860                                       NewVal);
3861     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3862                        DAG.getConstant(0, MVT::i32));
3863   }
3864
3865   // If that fails, try a VMOV.i32
3866   EVT VMovVT;
3867   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3868   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3869                                      VMOVModImm);
3870   if (NewVal != SDValue()) {
3871     DebugLoc DL = Op.getDebugLoc();
3872     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3873                                       NewVal);
3874     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3875                                        VecConstant);
3876     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3877                        DAG.getConstant(0, MVT::i32));
3878   }
3879
3880   // Finally, try a VMVN.i32
3881   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3882                              VMVNModImm);
3883   if (NewVal != SDValue()) {
3884     DebugLoc DL = Op.getDebugLoc();
3885     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3886     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3887                                        VecConstant);
3888     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3889                        DAG.getConstant(0, MVT::i32));
3890   }
3891
3892   return SDValue();
3893 }
3894
3895
3896 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3897                        bool &ReverseVEXT, unsigned &Imm) {
3898   unsigned NumElts = VT.getVectorNumElements();
3899   ReverseVEXT = false;
3900
3901   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3902   if (M[0] < 0)
3903     return false;
3904
3905   Imm = M[0];
3906
3907   // If this is a VEXT shuffle, the immediate value is the index of the first
3908   // element.  The other shuffle indices must be the successive elements after
3909   // the first one.
3910   unsigned ExpectedElt = Imm;
3911   for (unsigned i = 1; i < NumElts; ++i) {
3912     // Increment the expected index.  If it wraps around, it may still be
3913     // a VEXT but the source vectors must be swapped.
3914     ExpectedElt += 1;
3915     if (ExpectedElt == NumElts * 2) {
3916       ExpectedElt = 0;
3917       ReverseVEXT = true;
3918     }
3919
3920     if (M[i] < 0) continue; // ignore UNDEF indices
3921     if (ExpectedElt != static_cast<unsigned>(M[i]))
3922       return false;
3923   }
3924
3925   // Adjust the index value if the source operands will be swapped.
3926   if (ReverseVEXT)
3927     Imm -= NumElts;
3928
3929   return true;
3930 }
3931
3932 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3933 /// instruction with the specified blocksize.  (The order of the elements
3934 /// within each block of the vector is reversed.)
3935 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3936   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3937          "Only possible block sizes for VREV are: 16, 32, 64");
3938
3939   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3940   if (EltSz == 64)
3941     return false;
3942
3943   unsigned NumElts = VT.getVectorNumElements();
3944   unsigned BlockElts = M[0] + 1;
3945   // If the first shuffle index is UNDEF, be optimistic.
3946   if (M[0] < 0)
3947     BlockElts = BlockSize / EltSz;
3948
3949   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3950     return false;
3951
3952   for (unsigned i = 0; i < NumElts; ++i) {
3953     if (M[i] < 0) continue; // ignore UNDEF indices
3954     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3955       return false;
3956   }
3957
3958   return true;
3959 }
3960
3961 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3962   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3963   // range, then 0 is placed into the resulting vector. So pretty much any mask
3964   // of 8 elements can work here.
3965   return VT == MVT::v8i8 && M.size() == 8;
3966 }
3967
3968 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3969   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3970   if (EltSz == 64)
3971     return false;
3972
3973   unsigned NumElts = VT.getVectorNumElements();
3974   WhichResult = (M[0] == 0 ? 0 : 1);
3975   for (unsigned i = 0; i < NumElts; i += 2) {
3976     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3977         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3978       return false;
3979   }
3980   return true;
3981 }
3982
3983 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3984 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3985 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3986 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3987   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3988   if (EltSz == 64)
3989     return false;
3990
3991   unsigned NumElts = VT.getVectorNumElements();
3992   WhichResult = (M[0] == 0 ? 0 : 1);
3993   for (unsigned i = 0; i < NumElts; i += 2) {
3994     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3995         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3996       return false;
3997   }
3998   return true;
3999 }
4000
4001 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4002   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4003   if (EltSz == 64)
4004     return false;
4005
4006   unsigned NumElts = VT.getVectorNumElements();
4007   WhichResult = (M[0] == 0 ? 0 : 1);
4008   for (unsigned i = 0; i != NumElts; ++i) {
4009     if (M[i] < 0) continue; // ignore UNDEF indices
4010     if ((unsigned) M[i] != 2 * i + WhichResult)
4011       return false;
4012   }
4013
4014   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4015   if (VT.is64BitVector() && EltSz == 32)
4016     return false;
4017
4018   return true;
4019 }
4020
4021 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4022 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4023 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4024 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4025   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4026   if (EltSz == 64)
4027     return false;
4028
4029   unsigned Half = VT.getVectorNumElements() / 2;
4030   WhichResult = (M[0] == 0 ? 0 : 1);
4031   for (unsigned j = 0; j != 2; ++j) {
4032     unsigned Idx = WhichResult;
4033     for (unsigned i = 0; i != Half; ++i) {
4034       int MIdx = M[i + j * Half];
4035       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4036         return false;
4037       Idx += 2;
4038     }
4039   }
4040
4041   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4042   if (VT.is64BitVector() && EltSz == 32)
4043     return false;
4044
4045   return true;
4046 }
4047
4048 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4049   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4050   if (EltSz == 64)
4051     return false;
4052
4053   unsigned NumElts = VT.getVectorNumElements();
4054   WhichResult = (M[0] == 0 ? 0 : 1);
4055   unsigned Idx = WhichResult * NumElts / 2;
4056   for (unsigned i = 0; i != NumElts; i += 2) {
4057     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4058         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4059       return false;
4060     Idx += 1;
4061   }
4062
4063   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4064   if (VT.is64BitVector() && EltSz == 32)
4065     return false;
4066
4067   return true;
4068 }
4069
4070 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4071 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4072 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4073 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4074   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4075   if (EltSz == 64)
4076     return false;
4077
4078   unsigned NumElts = VT.getVectorNumElements();
4079   WhichResult = (M[0] == 0 ? 0 : 1);
4080   unsigned Idx = WhichResult * NumElts / 2;
4081   for (unsigned i = 0; i != NumElts; i += 2) {
4082     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4083         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4084       return false;
4085     Idx += 1;
4086   }
4087
4088   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4089   if (VT.is64BitVector() && EltSz == 32)
4090     return false;
4091
4092   return true;
4093 }
4094
4095 // If N is an integer constant that can be moved into a register in one
4096 // instruction, return an SDValue of such a constant (will become a MOV
4097 // instruction).  Otherwise return null.
4098 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4099                                      const ARMSubtarget *ST, DebugLoc dl) {
4100   uint64_t Val;
4101   if (!isa<ConstantSDNode>(N))
4102     return SDValue();
4103   Val = cast<ConstantSDNode>(N)->getZExtValue();
4104
4105   if (ST->isThumb1Only()) {
4106     if (Val <= 255 || ~Val <= 255)
4107       return DAG.getConstant(Val, MVT::i32);
4108   } else {
4109     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4110       return DAG.getConstant(Val, MVT::i32);
4111   }
4112   return SDValue();
4113 }
4114
4115 // If this is a case we can't handle, return null and let the default
4116 // expansion code take care of it.
4117 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4118                                              const ARMSubtarget *ST) const {
4119   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4120   DebugLoc dl = Op.getDebugLoc();
4121   EVT VT = Op.getValueType();
4122
4123   APInt SplatBits, SplatUndef;
4124   unsigned SplatBitSize;
4125   bool HasAnyUndefs;
4126   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4127     if (SplatBitSize <= 64) {
4128       // Check if an immediate VMOV works.
4129       EVT VmovVT;
4130       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4131                                       SplatUndef.getZExtValue(), SplatBitSize,
4132                                       DAG, VmovVT, VT.is128BitVector(),
4133                                       VMOVModImm);
4134       if (Val.getNode()) {
4135         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4136         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4137       }
4138
4139       // Try an immediate VMVN.
4140       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4141       Val = isNEONModifiedImm(NegatedImm,
4142                                       SplatUndef.getZExtValue(), SplatBitSize,
4143                                       DAG, VmovVT, VT.is128BitVector(),
4144                                       VMVNModImm);
4145       if (Val.getNode()) {
4146         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4147         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4148       }
4149
4150       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4151       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4152         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4153         if (ImmVal != -1) {
4154           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4155           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4156         }
4157       }
4158     }
4159   }
4160
4161   // Scan through the operands to see if only one value is used.
4162   //
4163   // As an optimisation, even if more than one value is used it may be more
4164   // profitable to splat with one value then change some lanes.
4165   //
4166   // Heuristically we decide to do this if the vector has a "dominant" value,
4167   // defined as splatted to more than half of the lanes.
4168   unsigned NumElts = VT.getVectorNumElements();
4169   bool isOnlyLowElement = true;
4170   bool usesOnlyOneValue = true;
4171   bool hasDominantValue = false;
4172   bool isConstant = true;
4173
4174   // Map of the number of times a particular SDValue appears in the
4175   // element list.
4176   DenseMap<SDValue, unsigned> ValueCounts;
4177   SDValue Value;
4178   for (unsigned i = 0; i < NumElts; ++i) {
4179     SDValue V = Op.getOperand(i);
4180     if (V.getOpcode() == ISD::UNDEF)
4181       continue;
4182     if (i > 0)
4183       isOnlyLowElement = false;
4184     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4185       isConstant = false;
4186
4187     ValueCounts.insert(std::make_pair(V, 0));
4188     unsigned &Count = ValueCounts[V];
4189     
4190     // Is this value dominant? (takes up more than half of the lanes)
4191     if (++Count > (NumElts / 2)) {
4192       hasDominantValue = true;
4193       Value = V;
4194     }
4195   }
4196   if (ValueCounts.size() != 1)
4197     usesOnlyOneValue = false;
4198   if (!Value.getNode() && ValueCounts.size() > 0)
4199     Value = ValueCounts.begin()->first;
4200
4201   if (ValueCounts.size() == 0)
4202     return DAG.getUNDEF(VT);
4203
4204   if (isOnlyLowElement)
4205     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4206
4207   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4208
4209   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4210   // i32 and try again.
4211   if (hasDominantValue && EltSize <= 32) {
4212     if (!isConstant) {
4213       SDValue N;
4214
4215       // If we are VDUPing a value that comes directly from a vector, that will
4216       // cause an unnecessary move to and from a GPR, where instead we could
4217       // just use VDUPLANE.
4218       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT)
4219         N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4220                         Value->getOperand(0), Value->getOperand(1));
4221       else
4222         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4223
4224       if (!usesOnlyOneValue) {
4225         // The dominant value was splatted as 'N', but we now have to insert
4226         // all differing elements.
4227         for (unsigned I = 0; I < NumElts; ++I) {
4228           if (Op.getOperand(I) == Value)
4229             continue;
4230           SmallVector<SDValue, 3> Ops;
4231           Ops.push_back(N);
4232           Ops.push_back(Op.getOperand(I));
4233           Ops.push_back(DAG.getConstant(I, MVT::i32));
4234           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4235         }
4236       }
4237       return N;
4238     }
4239     if (VT.getVectorElementType().isFloatingPoint()) {
4240       SmallVector<SDValue, 8> Ops;
4241       for (unsigned i = 0; i < NumElts; ++i)
4242         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4243                                   Op.getOperand(i)));
4244       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4245       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4246       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4247       if (Val.getNode())
4248         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4249     }
4250     if (usesOnlyOneValue) {
4251       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4252       if (isConstant && Val.getNode())
4253         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4254     }
4255   }
4256
4257   // If all elements are constants and the case above didn't get hit, fall back
4258   // to the default expansion, which will generate a load from the constant
4259   // pool.
4260   if (isConstant)
4261     return SDValue();
4262
4263   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4264   if (NumElts >= 4) {
4265     SDValue shuffle = ReconstructShuffle(Op, DAG);
4266     if (shuffle != SDValue())
4267       return shuffle;
4268   }
4269
4270   // Vectors with 32- or 64-bit elements can be built by directly assigning
4271   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4272   // will be legalized.
4273   if (EltSize >= 32) {
4274     // Do the expansion with floating-point types, since that is what the VFP
4275     // registers are defined to use, and since i64 is not legal.
4276     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4277     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4278     SmallVector<SDValue, 8> Ops;
4279     for (unsigned i = 0; i < NumElts; ++i)
4280       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4281     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4282     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4283   }
4284
4285   return SDValue();
4286 }
4287
4288 // Gather data to see if the operation can be modelled as a
4289 // shuffle in combination with VEXTs.
4290 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4291                                               SelectionDAG &DAG) const {
4292   DebugLoc dl = Op.getDebugLoc();
4293   EVT VT = Op.getValueType();
4294   unsigned NumElts = VT.getVectorNumElements();
4295
4296   SmallVector<SDValue, 2> SourceVecs;
4297   SmallVector<unsigned, 2> MinElts;
4298   SmallVector<unsigned, 2> MaxElts;
4299
4300   for (unsigned i = 0; i < NumElts; ++i) {
4301     SDValue V = Op.getOperand(i);
4302     if (V.getOpcode() == ISD::UNDEF)
4303       continue;
4304     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4305       // A shuffle can only come from building a vector from various
4306       // elements of other vectors.
4307       return SDValue();
4308     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4309                VT.getVectorElementType()) {
4310       // This code doesn't know how to handle shuffles where the vector
4311       // element types do not match (this happens because type legalization
4312       // promotes the return type of EXTRACT_VECTOR_ELT).
4313       // FIXME: It might be appropriate to extend this code to handle
4314       // mismatched types.
4315       return SDValue();
4316     }
4317
4318     // Record this extraction against the appropriate vector if possible...
4319     SDValue SourceVec = V.getOperand(0);
4320     // If the element number isn't a constant, we can't effectively
4321     // analyze what's going on.
4322     if (!isa<ConstantSDNode>(V.getOperand(1)))
4323       return SDValue();
4324     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4325     bool FoundSource = false;
4326     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4327       if (SourceVecs[j] == SourceVec) {
4328         if (MinElts[j] > EltNo)
4329           MinElts[j] = EltNo;
4330         if (MaxElts[j] < EltNo)
4331           MaxElts[j] = EltNo;
4332         FoundSource = true;
4333         break;
4334       }
4335     }
4336
4337     // Or record a new source if not...
4338     if (!FoundSource) {
4339       SourceVecs.push_back(SourceVec);
4340       MinElts.push_back(EltNo);
4341       MaxElts.push_back(EltNo);
4342     }
4343   }
4344
4345   // Currently only do something sane when at most two source vectors
4346   // involved.
4347   if (SourceVecs.size() > 2)
4348     return SDValue();
4349
4350   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4351   int VEXTOffsets[2] = {0, 0};
4352
4353   // This loop extracts the usage patterns of the source vectors
4354   // and prepares appropriate SDValues for a shuffle if possible.
4355   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4356     if (SourceVecs[i].getValueType() == VT) {
4357       // No VEXT necessary
4358       ShuffleSrcs[i] = SourceVecs[i];
4359       VEXTOffsets[i] = 0;
4360       continue;
4361     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4362       // It probably isn't worth padding out a smaller vector just to
4363       // break it down again in a shuffle.
4364       return SDValue();
4365     }
4366
4367     // Since only 64-bit and 128-bit vectors are legal on ARM and
4368     // we've eliminated the other cases...
4369     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4370            "unexpected vector sizes in ReconstructShuffle");
4371
4372     if (MaxElts[i] - MinElts[i] >= NumElts) {
4373       // Span too large for a VEXT to cope
4374       return SDValue();
4375     }
4376
4377     if (MinElts[i] >= NumElts) {
4378       // The extraction can just take the second half
4379       VEXTOffsets[i] = NumElts;
4380       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4381                                    SourceVecs[i],
4382                                    DAG.getIntPtrConstant(NumElts));
4383     } else if (MaxElts[i] < NumElts) {
4384       // The extraction can just take the first half
4385       VEXTOffsets[i] = 0;
4386       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4387                                    SourceVecs[i],
4388                                    DAG.getIntPtrConstant(0));
4389     } else {
4390       // An actual VEXT is needed
4391       VEXTOffsets[i] = MinElts[i];
4392       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4393                                      SourceVecs[i],
4394                                      DAG.getIntPtrConstant(0));
4395       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4396                                      SourceVecs[i],
4397                                      DAG.getIntPtrConstant(NumElts));
4398       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4399                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4400     }
4401   }
4402
4403   SmallVector<int, 8> Mask;
4404
4405   for (unsigned i = 0; i < NumElts; ++i) {
4406     SDValue Entry = Op.getOperand(i);
4407     if (Entry.getOpcode() == ISD::UNDEF) {
4408       Mask.push_back(-1);
4409       continue;
4410     }
4411
4412     SDValue ExtractVec = Entry.getOperand(0);
4413     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4414                                           .getOperand(1))->getSExtValue();
4415     if (ExtractVec == SourceVecs[0]) {
4416       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4417     } else {
4418       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4419     }
4420   }
4421
4422   // Final check before we try to produce nonsense...
4423   if (isShuffleMaskLegal(Mask, VT))
4424     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4425                                 &Mask[0]);
4426
4427   return SDValue();
4428 }
4429
4430 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4431 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4432 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4433 /// are assumed to be legal.
4434 bool
4435 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4436                                       EVT VT) const {
4437   if (VT.getVectorNumElements() == 4 &&
4438       (VT.is128BitVector() || VT.is64BitVector())) {
4439     unsigned PFIndexes[4];
4440     for (unsigned i = 0; i != 4; ++i) {
4441       if (M[i] < 0)
4442         PFIndexes[i] = 8;
4443       else
4444         PFIndexes[i] = M[i];
4445     }
4446
4447     // Compute the index in the perfect shuffle table.
4448     unsigned PFTableIndex =
4449       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4450     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4451     unsigned Cost = (PFEntry >> 30);
4452
4453     if (Cost <= 4)
4454       return true;
4455   }
4456
4457   bool ReverseVEXT;
4458   unsigned Imm, WhichResult;
4459
4460   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4461   return (EltSize >= 32 ||
4462           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4463           isVREVMask(M, VT, 64) ||
4464           isVREVMask(M, VT, 32) ||
4465           isVREVMask(M, VT, 16) ||
4466           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4467           isVTBLMask(M, VT) ||
4468           isVTRNMask(M, VT, WhichResult) ||
4469           isVUZPMask(M, VT, WhichResult) ||
4470           isVZIPMask(M, VT, WhichResult) ||
4471           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4472           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4473           isVZIP_v_undef_Mask(M, VT, WhichResult));
4474 }
4475
4476 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4477 /// the specified operations to build the shuffle.
4478 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4479                                       SDValue RHS, SelectionDAG &DAG,
4480                                       DebugLoc dl) {
4481   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4482   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4483   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4484
4485   enum {
4486     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4487     OP_VREV,
4488     OP_VDUP0,
4489     OP_VDUP1,
4490     OP_VDUP2,
4491     OP_VDUP3,
4492     OP_VEXT1,
4493     OP_VEXT2,
4494     OP_VEXT3,
4495     OP_VUZPL, // VUZP, left result
4496     OP_VUZPR, // VUZP, right result
4497     OP_VZIPL, // VZIP, left result
4498     OP_VZIPR, // VZIP, right result
4499     OP_VTRNL, // VTRN, left result
4500     OP_VTRNR  // VTRN, right result
4501   };
4502
4503   if (OpNum == OP_COPY) {
4504     if (LHSID == (1*9+2)*9+3) return LHS;
4505     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4506     return RHS;
4507   }
4508
4509   SDValue OpLHS, OpRHS;
4510   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4511   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4512   EVT VT = OpLHS.getValueType();
4513
4514   switch (OpNum) {
4515   default: llvm_unreachable("Unknown shuffle opcode!");
4516   case OP_VREV:
4517     // VREV divides the vector in half and swaps within the half.
4518     if (VT.getVectorElementType() == MVT::i32 ||
4519         VT.getVectorElementType() == MVT::f32)
4520       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4521     // vrev <4 x i16> -> VREV32
4522     if (VT.getVectorElementType() == MVT::i16)
4523       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4524     // vrev <4 x i8> -> VREV16
4525     assert(VT.getVectorElementType() == MVT::i8);
4526     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4527   case OP_VDUP0:
4528   case OP_VDUP1:
4529   case OP_VDUP2:
4530   case OP_VDUP3:
4531     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4532                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4533   case OP_VEXT1:
4534   case OP_VEXT2:
4535   case OP_VEXT3:
4536     return DAG.getNode(ARMISD::VEXT, dl, VT,
4537                        OpLHS, OpRHS,
4538                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4539   case OP_VUZPL:
4540   case OP_VUZPR:
4541     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4542                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4543   case OP_VZIPL:
4544   case OP_VZIPR:
4545     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4546                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4547   case OP_VTRNL:
4548   case OP_VTRNR:
4549     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4550                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4551   }
4552 }
4553
4554 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4555                                        ArrayRef<int> ShuffleMask,
4556                                        SelectionDAG &DAG) {
4557   // Check to see if we can use the VTBL instruction.
4558   SDValue V1 = Op.getOperand(0);
4559   SDValue V2 = Op.getOperand(1);
4560   DebugLoc DL = Op.getDebugLoc();
4561
4562   SmallVector<SDValue, 8> VTBLMask;
4563   for (ArrayRef<int>::iterator
4564          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4565     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4566
4567   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4568     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4569                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4570                                    &VTBLMask[0], 8));
4571
4572   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4573                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4574                                  &VTBLMask[0], 8));
4575 }
4576
4577 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4578   SDValue V1 = Op.getOperand(0);
4579   SDValue V2 = Op.getOperand(1);
4580   DebugLoc dl = Op.getDebugLoc();
4581   EVT VT = Op.getValueType();
4582   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4583
4584   // Convert shuffles that are directly supported on NEON to target-specific
4585   // DAG nodes, instead of keeping them as shuffles and matching them again
4586   // during code selection.  This is more efficient and avoids the possibility
4587   // of inconsistencies between legalization and selection.
4588   // FIXME: floating-point vectors should be canonicalized to integer vectors
4589   // of the same time so that they get CSEd properly.
4590   ArrayRef<int> ShuffleMask = SVN->getMask();
4591
4592   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4593   if (EltSize <= 32) {
4594     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4595       int Lane = SVN->getSplatIndex();
4596       // If this is undef splat, generate it via "just" vdup, if possible.
4597       if (Lane == -1) Lane = 0;
4598
4599       // Test if V1 is a SCALAR_TO_VECTOR.
4600       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4601         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4602       }
4603       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4604       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4605       // reaches it).
4606       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4607           !isa<ConstantSDNode>(V1.getOperand(0))) {
4608         bool IsScalarToVector = true;
4609         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4610           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4611             IsScalarToVector = false;
4612             break;
4613           }
4614         if (IsScalarToVector)
4615           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4616       }
4617       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4618                          DAG.getConstant(Lane, MVT::i32));
4619     }
4620
4621     bool ReverseVEXT;
4622     unsigned Imm;
4623     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4624       if (ReverseVEXT)
4625         std::swap(V1, V2);
4626       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4627                          DAG.getConstant(Imm, MVT::i32));
4628     }
4629
4630     if (isVREVMask(ShuffleMask, VT, 64))
4631       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4632     if (isVREVMask(ShuffleMask, VT, 32))
4633       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4634     if (isVREVMask(ShuffleMask, VT, 16))
4635       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4636
4637     // Check for Neon shuffles that modify both input vectors in place.
4638     // If both results are used, i.e., if there are two shuffles with the same
4639     // source operands and with masks corresponding to both results of one of
4640     // these operations, DAG memoization will ensure that a single node is
4641     // used for both shuffles.
4642     unsigned WhichResult;
4643     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4644       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4645                          V1, V2).getValue(WhichResult);
4646     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4647       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4648                          V1, V2).getValue(WhichResult);
4649     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4650       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4651                          V1, V2).getValue(WhichResult);
4652
4653     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4654       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4655                          V1, V1).getValue(WhichResult);
4656     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4657       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4658                          V1, V1).getValue(WhichResult);
4659     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4660       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4661                          V1, V1).getValue(WhichResult);
4662   }
4663
4664   // If the shuffle is not directly supported and it has 4 elements, use
4665   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4666   unsigned NumElts = VT.getVectorNumElements();
4667   if (NumElts == 4) {
4668     unsigned PFIndexes[4];
4669     for (unsigned i = 0; i != 4; ++i) {
4670       if (ShuffleMask[i] < 0)
4671         PFIndexes[i] = 8;
4672       else
4673         PFIndexes[i] = ShuffleMask[i];
4674     }
4675
4676     // Compute the index in the perfect shuffle table.
4677     unsigned PFTableIndex =
4678       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4679     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4680     unsigned Cost = (PFEntry >> 30);
4681
4682     if (Cost <= 4)
4683       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4684   }
4685
4686   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4687   if (EltSize >= 32) {
4688     // Do the expansion with floating-point types, since that is what the VFP
4689     // registers are defined to use, and since i64 is not legal.
4690     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4691     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4692     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4693     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4694     SmallVector<SDValue, 8> Ops;
4695     for (unsigned i = 0; i < NumElts; ++i) {
4696       if (ShuffleMask[i] < 0)
4697         Ops.push_back(DAG.getUNDEF(EltVT));
4698       else
4699         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4700                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4701                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4702                                                   MVT::i32)));
4703     }
4704     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4705     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4706   }
4707
4708   if (VT == MVT::v8i8) {
4709     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4710     if (NewOp.getNode())
4711       return NewOp;
4712   }
4713
4714   return SDValue();
4715 }
4716
4717 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4718   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4719   SDValue Lane = Op.getOperand(2);
4720   if (!isa<ConstantSDNode>(Lane))
4721     return SDValue();
4722
4723   return Op;
4724 }
4725
4726 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4727   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4728   SDValue Lane = Op.getOperand(1);
4729   if (!isa<ConstantSDNode>(Lane))
4730     return SDValue();
4731
4732   SDValue Vec = Op.getOperand(0);
4733   if (Op.getValueType() == MVT::i32 &&
4734       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4735     DebugLoc dl = Op.getDebugLoc();
4736     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4737   }
4738
4739   return Op;
4740 }
4741
4742 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4743   // The only time a CONCAT_VECTORS operation can have legal types is when
4744   // two 64-bit vectors are concatenated to a 128-bit vector.
4745   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4746          "unexpected CONCAT_VECTORS");
4747   DebugLoc dl = Op.getDebugLoc();
4748   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4749   SDValue Op0 = Op.getOperand(0);
4750   SDValue Op1 = Op.getOperand(1);
4751   if (Op0.getOpcode() != ISD::UNDEF)
4752     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4753                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4754                       DAG.getIntPtrConstant(0));
4755   if (Op1.getOpcode() != ISD::UNDEF)
4756     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4757                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4758                       DAG.getIntPtrConstant(1));
4759   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4760 }
4761
4762 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4763 /// element has been zero/sign-extended, depending on the isSigned parameter,
4764 /// from an integer type half its size.
4765 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4766                                    bool isSigned) {
4767   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4768   EVT VT = N->getValueType(0);
4769   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4770     SDNode *BVN = N->getOperand(0).getNode();
4771     if (BVN->getValueType(0) != MVT::v4i32 ||
4772         BVN->getOpcode() != ISD::BUILD_VECTOR)
4773       return false;
4774     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4775     unsigned HiElt = 1 - LoElt;
4776     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4777     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4778     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4779     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4780     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4781       return false;
4782     if (isSigned) {
4783       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4784           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4785         return true;
4786     } else {
4787       if (Hi0->isNullValue() && Hi1->isNullValue())
4788         return true;
4789     }
4790     return false;
4791   }
4792
4793   if (N->getOpcode() != ISD::BUILD_VECTOR)
4794     return false;
4795
4796   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4797     SDNode *Elt = N->getOperand(i).getNode();
4798     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4799       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4800       unsigned HalfSize = EltSize / 2;
4801       if (isSigned) {
4802         if (!isIntN(HalfSize, C->getSExtValue()))
4803           return false;
4804       } else {
4805         if (!isUIntN(HalfSize, C->getZExtValue()))
4806           return false;
4807       }
4808       continue;
4809     }
4810     return false;
4811   }
4812
4813   return true;
4814 }
4815
4816 /// isSignExtended - Check if a node is a vector value that is sign-extended
4817 /// or a constant BUILD_VECTOR with sign-extended elements.
4818 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4819   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4820     return true;
4821   if (isExtendedBUILD_VECTOR(N, DAG, true))
4822     return true;
4823   return false;
4824 }
4825
4826 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4827 /// or a constant BUILD_VECTOR with zero-extended elements.
4828 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4829   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4830     return true;
4831   if (isExtendedBUILD_VECTOR(N, DAG, false))
4832     return true;
4833   return false;
4834 }
4835
4836 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4837 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4838 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4839   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4840     return N->getOperand(0);
4841   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4842     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4843                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4844                        LD->isNonTemporal(), LD->isInvariant(),
4845                        LD->getAlignment());
4846   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4847   // have been legalized as a BITCAST from v4i32.
4848   if (N->getOpcode() == ISD::BITCAST) {
4849     SDNode *BVN = N->getOperand(0).getNode();
4850     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4851            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4852     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4853     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4854                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4855   }
4856   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4857   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4858   EVT VT = N->getValueType(0);
4859   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4860   unsigned NumElts = VT.getVectorNumElements();
4861   MVT TruncVT = MVT::getIntegerVT(EltSize);
4862   SmallVector<SDValue, 8> Ops;
4863   for (unsigned i = 0; i != NumElts; ++i) {
4864     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4865     const APInt &CInt = C->getAPIntValue();
4866     // Element types smaller than 32 bits are not legal, so use i32 elements.
4867     // The values are implicitly truncated so sext vs. zext doesn't matter.
4868     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4869   }
4870   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4871                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4872 }
4873
4874 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4875   unsigned Opcode = N->getOpcode();
4876   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4877     SDNode *N0 = N->getOperand(0).getNode();
4878     SDNode *N1 = N->getOperand(1).getNode();
4879     return N0->hasOneUse() && N1->hasOneUse() &&
4880       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4881   }
4882   return false;
4883 }
4884
4885 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4886   unsigned Opcode = N->getOpcode();
4887   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4888     SDNode *N0 = N->getOperand(0).getNode();
4889     SDNode *N1 = N->getOperand(1).getNode();
4890     return N0->hasOneUse() && N1->hasOneUse() &&
4891       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4892   }
4893   return false;
4894 }
4895
4896 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4897   // Multiplications are only custom-lowered for 128-bit vectors so that
4898   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4899   EVT VT = Op.getValueType();
4900   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4901   SDNode *N0 = Op.getOperand(0).getNode();
4902   SDNode *N1 = Op.getOperand(1).getNode();
4903   unsigned NewOpc = 0;
4904   bool isMLA = false;
4905   bool isN0SExt = isSignExtended(N0, DAG);
4906   bool isN1SExt = isSignExtended(N1, DAG);
4907   if (isN0SExt && isN1SExt)
4908     NewOpc = ARMISD::VMULLs;
4909   else {
4910     bool isN0ZExt = isZeroExtended(N0, DAG);
4911     bool isN1ZExt = isZeroExtended(N1, DAG);
4912     if (isN0ZExt && isN1ZExt)
4913       NewOpc = ARMISD::VMULLu;
4914     else if (isN1SExt || isN1ZExt) {
4915       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4916       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4917       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4918         NewOpc = ARMISD::VMULLs;
4919         isMLA = true;
4920       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4921         NewOpc = ARMISD::VMULLu;
4922         isMLA = true;
4923       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4924         std::swap(N0, N1);
4925         NewOpc = ARMISD::VMULLu;
4926         isMLA = true;
4927       }
4928     }
4929
4930     if (!NewOpc) {
4931       if (VT == MVT::v2i64)
4932         // Fall through to expand this.  It is not legal.
4933         return SDValue();
4934       else
4935         // Other vector multiplications are legal.
4936         return Op;
4937     }
4938   }
4939
4940   // Legalize to a VMULL instruction.
4941   DebugLoc DL = Op.getDebugLoc();
4942   SDValue Op0;
4943   SDValue Op1 = SkipExtension(N1, DAG);
4944   if (!isMLA) {
4945     Op0 = SkipExtension(N0, DAG);
4946     assert(Op0.getValueType().is64BitVector() &&
4947            Op1.getValueType().is64BitVector() &&
4948            "unexpected types for extended operands to VMULL");
4949     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4950   }
4951
4952   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4953   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4954   //   vmull q0, d4, d6
4955   //   vmlal q0, d5, d6
4956   // is faster than
4957   //   vaddl q0, d4, d5
4958   //   vmovl q1, d6
4959   //   vmul  q0, q0, q1
4960   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4961   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4962   EVT Op1VT = Op1.getValueType();
4963   return DAG.getNode(N0->getOpcode(), DL, VT,
4964                      DAG.getNode(NewOpc, DL, VT,
4965                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4966                      DAG.getNode(NewOpc, DL, VT,
4967                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4968 }
4969
4970 static SDValue
4971 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4972   // Convert to float
4973   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4974   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4975   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4976   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4977   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4978   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4979   // Get reciprocal estimate.
4980   // float4 recip = vrecpeq_f32(yf);
4981   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4982                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4983   // Because char has a smaller range than uchar, we can actually get away
4984   // without any newton steps.  This requires that we use a weird bias
4985   // of 0xb000, however (again, this has been exhaustively tested).
4986   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4987   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4988   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4989   Y = DAG.getConstant(0xb000, MVT::i32);
4990   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4991   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4992   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4993   // Convert back to short.
4994   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4995   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4996   return X;
4997 }
4998
4999 static SDValue
5000 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5001   SDValue N2;
5002   // Convert to float.
5003   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5004   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5005   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5006   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5007   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5008   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5009
5010   // Use reciprocal estimate and one refinement step.
5011   // float4 recip = vrecpeq_f32(yf);
5012   // recip *= vrecpsq_f32(yf, recip);
5013   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5014                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5015   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5016                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5017                    N1, N2);
5018   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5019   // Because short has a smaller range than ushort, we can actually get away
5020   // with only a single newton step.  This requires that we use a weird bias
5021   // of 89, however (again, this has been exhaustively tested).
5022   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5023   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5024   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5025   N1 = DAG.getConstant(0x89, MVT::i32);
5026   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5027   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5028   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5029   // Convert back to integer and return.
5030   // return vmovn_s32(vcvt_s32_f32(result));
5031   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5032   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5033   return N0;
5034 }
5035
5036 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5037   EVT VT = Op.getValueType();
5038   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5039          "unexpected type for custom-lowering ISD::SDIV");
5040
5041   DebugLoc dl = Op.getDebugLoc();
5042   SDValue N0 = Op.getOperand(0);
5043   SDValue N1 = Op.getOperand(1);
5044   SDValue N2, N3;
5045
5046   if (VT == MVT::v8i8) {
5047     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5048     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5049
5050     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5051                      DAG.getIntPtrConstant(4));
5052     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5053                      DAG.getIntPtrConstant(4));
5054     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5055                      DAG.getIntPtrConstant(0));
5056     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5057                      DAG.getIntPtrConstant(0));
5058
5059     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5060     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5061
5062     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5063     N0 = LowerCONCAT_VECTORS(N0, DAG);
5064
5065     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5066     return N0;
5067   }
5068   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5069 }
5070
5071 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5072   EVT VT = Op.getValueType();
5073   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5074          "unexpected type for custom-lowering ISD::UDIV");
5075
5076   DebugLoc dl = Op.getDebugLoc();
5077   SDValue N0 = Op.getOperand(0);
5078   SDValue N1 = Op.getOperand(1);
5079   SDValue N2, N3;
5080
5081   if (VT == MVT::v8i8) {
5082     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5083     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5084
5085     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5086                      DAG.getIntPtrConstant(4));
5087     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5088                      DAG.getIntPtrConstant(4));
5089     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5090                      DAG.getIntPtrConstant(0));
5091     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5092                      DAG.getIntPtrConstant(0));
5093
5094     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5095     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5096
5097     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5098     N0 = LowerCONCAT_VECTORS(N0, DAG);
5099
5100     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5101                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5102                      N0);
5103     return N0;
5104   }
5105
5106   // v4i16 sdiv ... Convert to float.
5107   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5108   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5109   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5110   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5111   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5112   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5113
5114   // Use reciprocal estimate and two refinement steps.
5115   // float4 recip = vrecpeq_f32(yf);
5116   // recip *= vrecpsq_f32(yf, recip);
5117   // recip *= vrecpsq_f32(yf, recip);
5118   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5119                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5120   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5121                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5122                    BN1, N2);
5123   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5124   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5125                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5126                    BN1, N2);
5127   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5128   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5129   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5130   // and that it will never cause us to return an answer too large).
5131   // float4 result = as_float4(as_int4(xf*recip) + 2);
5132   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5133   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5134   N1 = DAG.getConstant(2, MVT::i32);
5135   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5136   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5137   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5138   // Convert back to integer and return.
5139   // return vmovn_u32(vcvt_s32_f32(result));
5140   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5141   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5142   return N0;
5143 }
5144
5145 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5146   EVT VT = Op.getNode()->getValueType(0);
5147   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5148
5149   unsigned Opc;
5150   bool ExtraOp = false;
5151   switch (Op.getOpcode()) {
5152   default: llvm_unreachable("Invalid code");
5153   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5154   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5155   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5156   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5157   }
5158
5159   if (!ExtraOp)
5160     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5161                        Op.getOperand(1));
5162   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5163                      Op.getOperand(1), Op.getOperand(2));
5164 }
5165
5166 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5167   // Monotonic load/store is legal for all targets
5168   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5169     return Op;
5170
5171   // Aquire/Release load/store is not legal for targets without a
5172   // dmb or equivalent available.
5173   return SDValue();
5174 }
5175
5176
5177 static void
5178 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5179                     SelectionDAG &DAG, unsigned NewOp) {
5180   DebugLoc dl = Node->getDebugLoc();
5181   assert (Node->getValueType(0) == MVT::i64 &&
5182           "Only know how to expand i64 atomics");
5183
5184   SmallVector<SDValue, 6> Ops;
5185   Ops.push_back(Node->getOperand(0)); // Chain
5186   Ops.push_back(Node->getOperand(1)); // Ptr
5187   // Low part of Val1
5188   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5189                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5190   // High part of Val1
5191   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5192                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5193   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5194     // High part of Val1
5195     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5196                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5197     // High part of Val2
5198     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5199                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5200   }
5201   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5202   SDValue Result =
5203     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5204                             cast<MemSDNode>(Node)->getMemOperand());
5205   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5206   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5207   Results.push_back(Result.getValue(2));
5208 }
5209
5210 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5211   switch (Op.getOpcode()) {
5212   default: llvm_unreachable("Don't know how to custom lower this!");
5213   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5214   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5215   case ISD::GlobalAddress:
5216     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5217       LowerGlobalAddressELF(Op, DAG);
5218   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5219   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5220   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5221   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5222   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5223   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5224   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5225   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5226   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5227   case ISD::SINT_TO_FP:
5228   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5229   case ISD::FP_TO_SINT:
5230   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5231   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5232   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5233   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5234   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5235   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5236   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5237   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5238                                                                Subtarget);
5239   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5240   case ISD::SHL:
5241   case ISD::SRL:
5242   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5243   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5244   case ISD::SRL_PARTS:
5245   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5246   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5247   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5248   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5249   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5250   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5251   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5252   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5253   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5254   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5255   case ISD::MUL:           return LowerMUL(Op, DAG);
5256   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5257   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5258   case ISD::ADDC:
5259   case ISD::ADDE:
5260   case ISD::SUBC:
5261   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5262   case ISD::ATOMIC_LOAD:
5263   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5264   }
5265 }
5266
5267 /// ReplaceNodeResults - Replace the results of node with an illegal result
5268 /// type with new values built out of custom code.
5269 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5270                                            SmallVectorImpl<SDValue>&Results,
5271                                            SelectionDAG &DAG) const {
5272   SDValue Res;
5273   switch (N->getOpcode()) {
5274   default:
5275     llvm_unreachable("Don't know how to custom expand this!");
5276   case ISD::BITCAST:
5277     Res = ExpandBITCAST(N, DAG);
5278     break;
5279   case ISD::SRL:
5280   case ISD::SRA:
5281     Res = Expand64BitShift(N, DAG, Subtarget);
5282     break;
5283   case ISD::ATOMIC_LOAD_ADD:
5284     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5285     return;
5286   case ISD::ATOMIC_LOAD_AND:
5287     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5288     return;
5289   case ISD::ATOMIC_LOAD_NAND:
5290     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5291     return;
5292   case ISD::ATOMIC_LOAD_OR:
5293     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5294     return;
5295   case ISD::ATOMIC_LOAD_SUB:
5296     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5297     return;
5298   case ISD::ATOMIC_LOAD_XOR:
5299     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5300     return;
5301   case ISD::ATOMIC_SWAP:
5302     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5303     return;
5304   case ISD::ATOMIC_CMP_SWAP:
5305     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5306     return;
5307   }
5308   if (Res.getNode())
5309     Results.push_back(Res);
5310 }
5311
5312 //===----------------------------------------------------------------------===//
5313 //                           ARM Scheduler Hooks
5314 //===----------------------------------------------------------------------===//
5315
5316 MachineBasicBlock *
5317 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5318                                      MachineBasicBlock *BB,
5319                                      unsigned Size) const {
5320   unsigned dest    = MI->getOperand(0).getReg();
5321   unsigned ptr     = MI->getOperand(1).getReg();
5322   unsigned oldval  = MI->getOperand(2).getReg();
5323   unsigned newval  = MI->getOperand(3).getReg();
5324   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5325   DebugLoc dl = MI->getDebugLoc();
5326   bool isThumb2 = Subtarget->isThumb2();
5327
5328   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5329   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5330     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5331     (const TargetRegisterClass*)&ARM::GPRRegClass);
5332
5333   if (isThumb2) {
5334     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5335     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5336     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5337   }
5338
5339   unsigned ldrOpc, strOpc;
5340   switch (Size) {
5341   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5342   case 1:
5343     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5344     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5345     break;
5346   case 2:
5347     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5348     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5349     break;
5350   case 4:
5351     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5352     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5353     break;
5354   }
5355
5356   MachineFunction *MF = BB->getParent();
5357   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5358   MachineFunction::iterator It = BB;
5359   ++It; // insert the new blocks after the current block
5360
5361   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5362   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5363   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5364   MF->insert(It, loop1MBB);
5365   MF->insert(It, loop2MBB);
5366   MF->insert(It, exitMBB);
5367
5368   // Transfer the remainder of BB and its successor edges to exitMBB.
5369   exitMBB->splice(exitMBB->begin(), BB,
5370                   llvm::next(MachineBasicBlock::iterator(MI)),
5371                   BB->end());
5372   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5373
5374   //  thisMBB:
5375   //   ...
5376   //   fallthrough --> loop1MBB
5377   BB->addSuccessor(loop1MBB);
5378
5379   // loop1MBB:
5380   //   ldrex dest, [ptr]
5381   //   cmp dest, oldval
5382   //   bne exitMBB
5383   BB = loop1MBB;
5384   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5385   if (ldrOpc == ARM::t2LDREX)
5386     MIB.addImm(0);
5387   AddDefaultPred(MIB);
5388   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5389                  .addReg(dest).addReg(oldval));
5390   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5391     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5392   BB->addSuccessor(loop2MBB);
5393   BB->addSuccessor(exitMBB);
5394
5395   // loop2MBB:
5396   //   strex scratch, newval, [ptr]
5397   //   cmp scratch, #0
5398   //   bne loop1MBB
5399   BB = loop2MBB;
5400   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5401   if (strOpc == ARM::t2STREX)
5402     MIB.addImm(0);
5403   AddDefaultPred(MIB);
5404   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5405                  .addReg(scratch).addImm(0));
5406   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5407     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5408   BB->addSuccessor(loop1MBB);
5409   BB->addSuccessor(exitMBB);
5410
5411   //  exitMBB:
5412   //   ...
5413   BB = exitMBB;
5414
5415   MI->eraseFromParent();   // The instruction is gone now.
5416
5417   return BB;
5418 }
5419
5420 MachineBasicBlock *
5421 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5422                                     unsigned Size, unsigned BinOpcode) const {
5423   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5424   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5425
5426   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5427   MachineFunction *MF = BB->getParent();
5428   MachineFunction::iterator It = BB;
5429   ++It;
5430
5431   unsigned dest = MI->getOperand(0).getReg();
5432   unsigned ptr = MI->getOperand(1).getReg();
5433   unsigned incr = MI->getOperand(2).getReg();
5434   DebugLoc dl = MI->getDebugLoc();
5435   bool isThumb2 = Subtarget->isThumb2();
5436
5437   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5438   if (isThumb2) {
5439     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5440     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5441   }
5442
5443   unsigned ldrOpc, strOpc;
5444   switch (Size) {
5445   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5446   case 1:
5447     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5448     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5449     break;
5450   case 2:
5451     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5452     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5453     break;
5454   case 4:
5455     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5456     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5457     break;
5458   }
5459
5460   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5461   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5462   MF->insert(It, loopMBB);
5463   MF->insert(It, exitMBB);
5464
5465   // Transfer the remainder of BB and its successor edges to exitMBB.
5466   exitMBB->splice(exitMBB->begin(), BB,
5467                   llvm::next(MachineBasicBlock::iterator(MI)),
5468                   BB->end());
5469   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5470
5471   const TargetRegisterClass *TRC = isThumb2 ?
5472     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5473     (const TargetRegisterClass*)&ARM::GPRRegClass;
5474   unsigned scratch = MRI.createVirtualRegister(TRC);
5475   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5476
5477   //  thisMBB:
5478   //   ...
5479   //   fallthrough --> loopMBB
5480   BB->addSuccessor(loopMBB);
5481
5482   //  loopMBB:
5483   //   ldrex dest, ptr
5484   //   <binop> scratch2, dest, incr
5485   //   strex scratch, scratch2, ptr
5486   //   cmp scratch, #0
5487   //   bne- loopMBB
5488   //   fallthrough --> exitMBB
5489   BB = loopMBB;
5490   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5491   if (ldrOpc == ARM::t2LDREX)
5492     MIB.addImm(0);
5493   AddDefaultPred(MIB);
5494   if (BinOpcode) {
5495     // operand order needs to go the other way for NAND
5496     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5497       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5498                      addReg(incr).addReg(dest)).addReg(0);
5499     else
5500       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5501                      addReg(dest).addReg(incr)).addReg(0);
5502   }
5503
5504   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5505   if (strOpc == ARM::t2STREX)
5506     MIB.addImm(0);
5507   AddDefaultPred(MIB);
5508   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5509                  .addReg(scratch).addImm(0));
5510   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5511     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5512
5513   BB->addSuccessor(loopMBB);
5514   BB->addSuccessor(exitMBB);
5515
5516   //  exitMBB:
5517   //   ...
5518   BB = exitMBB;
5519
5520   MI->eraseFromParent();   // The instruction is gone now.
5521
5522   return BB;
5523 }
5524
5525 MachineBasicBlock *
5526 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5527                                           MachineBasicBlock *BB,
5528                                           unsigned Size,
5529                                           bool signExtend,
5530                                           ARMCC::CondCodes Cond) const {
5531   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5532
5533   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5534   MachineFunction *MF = BB->getParent();
5535   MachineFunction::iterator It = BB;
5536   ++It;
5537
5538   unsigned dest = MI->getOperand(0).getReg();
5539   unsigned ptr = MI->getOperand(1).getReg();
5540   unsigned incr = MI->getOperand(2).getReg();
5541   unsigned oldval = dest;
5542   DebugLoc dl = MI->getDebugLoc();
5543   bool isThumb2 = Subtarget->isThumb2();
5544
5545   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5546   if (isThumb2) {
5547     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5548     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5549   }
5550
5551   unsigned ldrOpc, strOpc, extendOpc;
5552   switch (Size) {
5553   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5554   case 1:
5555     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5556     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5557     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5558     break;
5559   case 2:
5560     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5561     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5562     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5563     break;
5564   case 4:
5565     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5566     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5567     extendOpc = 0;
5568     break;
5569   }
5570
5571   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5572   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5573   MF->insert(It, loopMBB);
5574   MF->insert(It, exitMBB);
5575
5576   // Transfer the remainder of BB and its successor edges to exitMBB.
5577   exitMBB->splice(exitMBB->begin(), BB,
5578                   llvm::next(MachineBasicBlock::iterator(MI)),
5579                   BB->end());
5580   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5581
5582   const TargetRegisterClass *TRC = isThumb2 ?
5583     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5584     (const TargetRegisterClass*)&ARM::GPRRegClass;
5585   unsigned scratch = MRI.createVirtualRegister(TRC);
5586   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5587
5588   //  thisMBB:
5589   //   ...
5590   //   fallthrough --> loopMBB
5591   BB->addSuccessor(loopMBB);
5592
5593   //  loopMBB:
5594   //   ldrex dest, ptr
5595   //   (sign extend dest, if required)
5596   //   cmp dest, incr
5597   //   cmov.cond scratch2, incr, dest
5598   //   strex scratch, scratch2, ptr
5599   //   cmp scratch, #0
5600   //   bne- loopMBB
5601   //   fallthrough --> exitMBB
5602   BB = loopMBB;
5603   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5604   if (ldrOpc == ARM::t2LDREX)
5605     MIB.addImm(0);
5606   AddDefaultPred(MIB);
5607
5608   // Sign extend the value, if necessary.
5609   if (signExtend && extendOpc) {
5610     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5611     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5612                      .addReg(dest)
5613                      .addImm(0));
5614   }
5615
5616   // Build compare and cmov instructions.
5617   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5618                  .addReg(oldval).addReg(incr));
5619   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5620          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5621
5622   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5623   if (strOpc == ARM::t2STREX)
5624     MIB.addImm(0);
5625   AddDefaultPred(MIB);
5626   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5627                  .addReg(scratch).addImm(0));
5628   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5629     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5630
5631   BB->addSuccessor(loopMBB);
5632   BB->addSuccessor(exitMBB);
5633
5634   //  exitMBB:
5635   //   ...
5636   BB = exitMBB;
5637
5638   MI->eraseFromParent();   // The instruction is gone now.
5639
5640   return BB;
5641 }
5642
5643 MachineBasicBlock *
5644 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5645                                       unsigned Op1, unsigned Op2,
5646                                       bool NeedsCarry, bool IsCmpxchg) const {
5647   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5648   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5649
5650   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5651   MachineFunction *MF = BB->getParent();
5652   MachineFunction::iterator It = BB;
5653   ++It;
5654
5655   unsigned destlo = MI->getOperand(0).getReg();
5656   unsigned desthi = MI->getOperand(1).getReg();
5657   unsigned ptr = MI->getOperand(2).getReg();
5658   unsigned vallo = MI->getOperand(3).getReg();
5659   unsigned valhi = MI->getOperand(4).getReg();
5660   DebugLoc dl = MI->getDebugLoc();
5661   bool isThumb2 = Subtarget->isThumb2();
5662
5663   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5664   if (isThumb2) {
5665     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5666     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5667     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5668   }
5669
5670   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5671   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5672
5673   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5674   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5675   if (IsCmpxchg) {
5676     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5677     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5678   }
5679   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5680   MF->insert(It, loopMBB);
5681   if (IsCmpxchg) {
5682     MF->insert(It, contBB);
5683     MF->insert(It, cont2BB);
5684   }
5685   MF->insert(It, exitMBB);
5686
5687   // Transfer the remainder of BB and its successor edges to exitMBB.
5688   exitMBB->splice(exitMBB->begin(), BB,
5689                   llvm::next(MachineBasicBlock::iterator(MI)),
5690                   BB->end());
5691   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5692
5693   const TargetRegisterClass *TRC = isThumb2 ?
5694     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5695     (const TargetRegisterClass*)&ARM::GPRRegClass;
5696   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5697
5698   //  thisMBB:
5699   //   ...
5700   //   fallthrough --> loopMBB
5701   BB->addSuccessor(loopMBB);
5702
5703   //  loopMBB:
5704   //   ldrexd r2, r3, ptr
5705   //   <binopa> r0, r2, incr
5706   //   <binopb> r1, r3, incr
5707   //   strexd storesuccess, r0, r1, ptr
5708   //   cmp storesuccess, #0
5709   //   bne- loopMBB
5710   //   fallthrough --> exitMBB
5711   //
5712   // Note that the registers are explicitly specified because there is not any
5713   // way to force the register allocator to allocate a register pair.
5714   //
5715   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5716   // need to properly enforce the restriction that the two output registers
5717   // for ldrexd must be different.
5718   BB = loopMBB;
5719   // Load
5720   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5721                  .addReg(ARM::R2, RegState::Define)
5722                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5723   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5724   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5725   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5726
5727   if (IsCmpxchg) {
5728     // Add early exit
5729     for (unsigned i = 0; i < 2; i++) {
5730       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5731                                                          ARM::CMPrr))
5732                      .addReg(i == 0 ? destlo : desthi)
5733                      .addReg(i == 0 ? vallo : valhi));
5734       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5735         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5736       BB->addSuccessor(exitMBB);
5737       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5738       BB = (i == 0 ? contBB : cont2BB);
5739     }
5740
5741     // Copy to physregs for strexd
5742     unsigned setlo = MI->getOperand(5).getReg();
5743     unsigned sethi = MI->getOperand(6).getReg();
5744     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5745     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5746   } else if (Op1) {
5747     // Perform binary operation
5748     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5749                    .addReg(destlo).addReg(vallo))
5750         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5751     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5752                    .addReg(desthi).addReg(valhi)).addReg(0);
5753   } else {
5754     // Copy to physregs for strexd
5755     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5756     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5757   }
5758
5759   // Store
5760   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5761                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5762   // Cmp+jump
5763   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5764                  .addReg(storesuccess).addImm(0));
5765   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5766     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5767
5768   BB->addSuccessor(loopMBB);
5769   BB->addSuccessor(exitMBB);
5770
5771   //  exitMBB:
5772   //   ...
5773   BB = exitMBB;
5774
5775   MI->eraseFromParent();   // The instruction is gone now.
5776
5777   return BB;
5778 }
5779
5780 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5781 /// registers the function context.
5782 void ARMTargetLowering::
5783 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5784                        MachineBasicBlock *DispatchBB, int FI) const {
5785   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5786   DebugLoc dl = MI->getDebugLoc();
5787   MachineFunction *MF = MBB->getParent();
5788   MachineRegisterInfo *MRI = &MF->getRegInfo();
5789   MachineConstantPool *MCP = MF->getConstantPool();
5790   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5791   const Function *F = MF->getFunction();
5792
5793   bool isThumb = Subtarget->isThumb();
5794   bool isThumb2 = Subtarget->isThumb2();
5795
5796   unsigned PCLabelId = AFI->createPICLabelUId();
5797   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5798   ARMConstantPoolValue *CPV =
5799     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5800   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5801
5802   const TargetRegisterClass *TRC = isThumb ?
5803     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5804     (const TargetRegisterClass*)&ARM::GPRRegClass;
5805
5806   // Grab constant pool and fixed stack memory operands.
5807   MachineMemOperand *CPMMO =
5808     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5809                              MachineMemOperand::MOLoad, 4, 4);
5810
5811   MachineMemOperand *FIMMOSt =
5812     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5813                              MachineMemOperand::MOStore, 4, 4);
5814
5815   // Load the address of the dispatch MBB into the jump buffer.
5816   if (isThumb2) {
5817     // Incoming value: jbuf
5818     //   ldr.n  r5, LCPI1_1
5819     //   orr    r5, r5, #1
5820     //   add    r5, pc
5821     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5822     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5823     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5824                    .addConstantPoolIndex(CPI)
5825                    .addMemOperand(CPMMO));
5826     // Set the low bit because of thumb mode.
5827     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5828     AddDefaultCC(
5829       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5830                      .addReg(NewVReg1, RegState::Kill)
5831                      .addImm(0x01)));
5832     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5833     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5834       .addReg(NewVReg2, RegState::Kill)
5835       .addImm(PCLabelId);
5836     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5837                    .addReg(NewVReg3, RegState::Kill)
5838                    .addFrameIndex(FI)
5839                    .addImm(36)  // &jbuf[1] :: pc
5840                    .addMemOperand(FIMMOSt));
5841   } else if (isThumb) {
5842     // Incoming value: jbuf
5843     //   ldr.n  r1, LCPI1_4
5844     //   add    r1, pc
5845     //   mov    r2, #1
5846     //   orrs   r1, r2
5847     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5848     //   str    r1, [r2]
5849     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5850     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5851                    .addConstantPoolIndex(CPI)
5852                    .addMemOperand(CPMMO));
5853     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5854     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5855       .addReg(NewVReg1, RegState::Kill)
5856       .addImm(PCLabelId);
5857     // Set the low bit because of thumb mode.
5858     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5859     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5860                    .addReg(ARM::CPSR, RegState::Define)
5861                    .addImm(1));
5862     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5863     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5864                    .addReg(ARM::CPSR, RegState::Define)
5865                    .addReg(NewVReg2, RegState::Kill)
5866                    .addReg(NewVReg3, RegState::Kill));
5867     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5868     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5869                    .addFrameIndex(FI)
5870                    .addImm(36)); // &jbuf[1] :: pc
5871     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5872                    .addReg(NewVReg4, RegState::Kill)
5873                    .addReg(NewVReg5, RegState::Kill)
5874                    .addImm(0)
5875                    .addMemOperand(FIMMOSt));
5876   } else {
5877     // Incoming value: jbuf
5878     //   ldr  r1, LCPI1_1
5879     //   add  r1, pc, r1
5880     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5881     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5882     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5883                    .addConstantPoolIndex(CPI)
5884                    .addImm(0)
5885                    .addMemOperand(CPMMO));
5886     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5887     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5888                    .addReg(NewVReg1, RegState::Kill)
5889                    .addImm(PCLabelId));
5890     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5891                    .addReg(NewVReg2, RegState::Kill)
5892                    .addFrameIndex(FI)
5893                    .addImm(36)  // &jbuf[1] :: pc
5894                    .addMemOperand(FIMMOSt));
5895   }
5896 }
5897
5898 MachineBasicBlock *ARMTargetLowering::
5899 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5900   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5901   DebugLoc dl = MI->getDebugLoc();
5902   MachineFunction *MF = MBB->getParent();
5903   MachineRegisterInfo *MRI = &MF->getRegInfo();
5904   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5905   MachineFrameInfo *MFI = MF->getFrameInfo();
5906   int FI = MFI->getFunctionContextIndex();
5907
5908   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5909     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5910     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5911
5912   // Get a mapping of the call site numbers to all of the landing pads they're
5913   // associated with.
5914   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5915   unsigned MaxCSNum = 0;
5916   MachineModuleInfo &MMI = MF->getMMI();
5917   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5918        ++BB) {
5919     if (!BB->isLandingPad()) continue;
5920
5921     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5922     // pad.
5923     for (MachineBasicBlock::iterator
5924            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5925       if (!II->isEHLabel()) continue;
5926
5927       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5928       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5929
5930       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5931       for (SmallVectorImpl<unsigned>::iterator
5932              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5933            CSI != CSE; ++CSI) {
5934         CallSiteNumToLPad[*CSI].push_back(BB);
5935         MaxCSNum = std::max(MaxCSNum, *CSI);
5936       }
5937       break;
5938     }
5939   }
5940
5941   // Get an ordered list of the machine basic blocks for the jump table.
5942   std::vector<MachineBasicBlock*> LPadList;
5943   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5944   LPadList.reserve(CallSiteNumToLPad.size());
5945   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5946     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5947     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5948            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5949       LPadList.push_back(*II);
5950       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5951     }
5952   }
5953
5954   assert(!LPadList.empty() &&
5955          "No landing pad destinations for the dispatch jump table!");
5956
5957   // Create the jump table and associated information.
5958   MachineJumpTableInfo *JTI =
5959     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5960   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5961   unsigned UId = AFI->createJumpTableUId();
5962
5963   // Create the MBBs for the dispatch code.
5964
5965   // Shove the dispatch's address into the return slot in the function context.
5966   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5967   DispatchBB->setIsLandingPad();
5968
5969   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5970   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5971   DispatchBB->addSuccessor(TrapBB);
5972
5973   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5974   DispatchBB->addSuccessor(DispContBB);
5975
5976   // Insert and MBBs.
5977   MF->insert(MF->end(), DispatchBB);
5978   MF->insert(MF->end(), DispContBB);
5979   MF->insert(MF->end(), TrapBB);
5980
5981   // Insert code into the entry block that creates and registers the function
5982   // context.
5983   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5984
5985   MachineMemOperand *FIMMOLd =
5986     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5987                              MachineMemOperand::MOLoad |
5988                              MachineMemOperand::MOVolatile, 4, 4);
5989
5990   if (AFI->isThumb1OnlyFunction())
5991     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5992   else if (!Subtarget->hasVFP2())
5993     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5994   else
5995     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5996
5997   unsigned NumLPads = LPadList.size();
5998   if (Subtarget->isThumb2()) {
5999     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6000     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6001                    .addFrameIndex(FI)
6002                    .addImm(4)
6003                    .addMemOperand(FIMMOLd));
6004
6005     if (NumLPads < 256) {
6006       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6007                      .addReg(NewVReg1)
6008                      .addImm(LPadList.size()));
6009     } else {
6010       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6011       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6012                      .addImm(NumLPads & 0xFFFF));
6013
6014       unsigned VReg2 = VReg1;
6015       if ((NumLPads & 0xFFFF0000) != 0) {
6016         VReg2 = MRI->createVirtualRegister(TRC);
6017         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6018                        .addReg(VReg1)
6019                        .addImm(NumLPads >> 16));
6020       }
6021
6022       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6023                      .addReg(NewVReg1)
6024                      .addReg(VReg2));
6025     }
6026
6027     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6028       .addMBB(TrapBB)
6029       .addImm(ARMCC::HI)
6030       .addReg(ARM::CPSR);
6031
6032     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6033     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6034                    .addJumpTableIndex(MJTI)
6035                    .addImm(UId));
6036
6037     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6038     AddDefaultCC(
6039       AddDefaultPred(
6040         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6041         .addReg(NewVReg3, RegState::Kill)
6042         .addReg(NewVReg1)
6043         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6044
6045     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6046       .addReg(NewVReg4, RegState::Kill)
6047       .addReg(NewVReg1)
6048       .addJumpTableIndex(MJTI)
6049       .addImm(UId);
6050   } else if (Subtarget->isThumb()) {
6051     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6052     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6053                    .addFrameIndex(FI)
6054                    .addImm(1)
6055                    .addMemOperand(FIMMOLd));
6056
6057     if (NumLPads < 256) {
6058       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6059                      .addReg(NewVReg1)
6060                      .addImm(NumLPads));
6061     } else {
6062       MachineConstantPool *ConstantPool = MF->getConstantPool();
6063       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6064       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6065
6066       // MachineConstantPool wants an explicit alignment.
6067       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6068       if (Align == 0)
6069         Align = getTargetData()->getTypeAllocSize(C->getType());
6070       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6071
6072       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6073       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6074                      .addReg(VReg1, RegState::Define)
6075                      .addConstantPoolIndex(Idx));
6076       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6077                      .addReg(NewVReg1)
6078                      .addReg(VReg1));
6079     }
6080
6081     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6082       .addMBB(TrapBB)
6083       .addImm(ARMCC::HI)
6084       .addReg(ARM::CPSR);
6085
6086     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6087     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6088                    .addReg(ARM::CPSR, RegState::Define)
6089                    .addReg(NewVReg1)
6090                    .addImm(2));
6091
6092     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6093     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6094                    .addJumpTableIndex(MJTI)
6095                    .addImm(UId));
6096
6097     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6098     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6099                    .addReg(ARM::CPSR, RegState::Define)
6100                    .addReg(NewVReg2, RegState::Kill)
6101                    .addReg(NewVReg3));
6102
6103     MachineMemOperand *JTMMOLd =
6104       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6105                                MachineMemOperand::MOLoad, 4, 4);
6106
6107     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6108     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6109                    .addReg(NewVReg4, RegState::Kill)
6110                    .addImm(0)
6111                    .addMemOperand(JTMMOLd));
6112
6113     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6114     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6115                    .addReg(ARM::CPSR, RegState::Define)
6116                    .addReg(NewVReg5, RegState::Kill)
6117                    .addReg(NewVReg3));
6118
6119     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6120       .addReg(NewVReg6, RegState::Kill)
6121       .addJumpTableIndex(MJTI)
6122       .addImm(UId);
6123   } else {
6124     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6125     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6126                    .addFrameIndex(FI)
6127                    .addImm(4)
6128                    .addMemOperand(FIMMOLd));
6129
6130     if (NumLPads < 256) {
6131       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6132                      .addReg(NewVReg1)
6133                      .addImm(NumLPads));
6134     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6135       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6136       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6137                      .addImm(NumLPads & 0xFFFF));
6138
6139       unsigned VReg2 = VReg1;
6140       if ((NumLPads & 0xFFFF0000) != 0) {
6141         VReg2 = MRI->createVirtualRegister(TRC);
6142         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6143                        .addReg(VReg1)
6144                        .addImm(NumLPads >> 16));
6145       }
6146
6147       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6148                      .addReg(NewVReg1)
6149                      .addReg(VReg2));
6150     } else {
6151       MachineConstantPool *ConstantPool = MF->getConstantPool();
6152       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6153       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6154
6155       // MachineConstantPool wants an explicit alignment.
6156       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6157       if (Align == 0)
6158         Align = getTargetData()->getTypeAllocSize(C->getType());
6159       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6160
6161       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6162       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6163                      .addReg(VReg1, RegState::Define)
6164                      .addConstantPoolIndex(Idx)
6165                      .addImm(0));
6166       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6167                      .addReg(NewVReg1)
6168                      .addReg(VReg1, RegState::Kill));
6169     }
6170
6171     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6172       .addMBB(TrapBB)
6173       .addImm(ARMCC::HI)
6174       .addReg(ARM::CPSR);
6175
6176     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6177     AddDefaultCC(
6178       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6179                      .addReg(NewVReg1)
6180                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6181     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6182     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6183                    .addJumpTableIndex(MJTI)
6184                    .addImm(UId));
6185
6186     MachineMemOperand *JTMMOLd =
6187       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6188                                MachineMemOperand::MOLoad, 4, 4);
6189     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6190     AddDefaultPred(
6191       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6192       .addReg(NewVReg3, RegState::Kill)
6193       .addReg(NewVReg4)
6194       .addImm(0)
6195       .addMemOperand(JTMMOLd));
6196
6197     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6198       .addReg(NewVReg5, RegState::Kill)
6199       .addReg(NewVReg4)
6200       .addJumpTableIndex(MJTI)
6201       .addImm(UId);
6202   }
6203
6204   // Add the jump table entries as successors to the MBB.
6205   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6206   for (std::vector<MachineBasicBlock*>::iterator
6207          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6208     MachineBasicBlock *CurMBB = *I;
6209     if (SeenMBBs.insert(CurMBB))
6210       DispContBB->addSuccessor(CurMBB);
6211   }
6212
6213   // N.B. the order the invoke BBs are processed in doesn't matter here.
6214   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6215   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6216   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6217   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6218   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6219          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6220     MachineBasicBlock *BB = *I;
6221
6222     // Remove the landing pad successor from the invoke block and replace it
6223     // with the new dispatch block.
6224     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6225                                                   BB->succ_end());
6226     while (!Successors.empty()) {
6227       MachineBasicBlock *SMBB = Successors.pop_back_val();
6228       if (SMBB->isLandingPad()) {
6229         BB->removeSuccessor(SMBB);
6230         MBBLPads.push_back(SMBB);
6231       }
6232     }
6233
6234     BB->addSuccessor(DispatchBB);
6235
6236     // Find the invoke call and mark all of the callee-saved registers as
6237     // 'implicit defined' so that they're spilled. This prevents code from
6238     // moving instructions to before the EH block, where they will never be
6239     // executed.
6240     for (MachineBasicBlock::reverse_iterator
6241            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6242       if (!II->isCall()) continue;
6243
6244       DenseMap<unsigned, bool> DefRegs;
6245       for (MachineInstr::mop_iterator
6246              OI = II->operands_begin(), OE = II->operands_end();
6247            OI != OE; ++OI) {
6248         if (!OI->isReg()) continue;
6249         DefRegs[OI->getReg()] = true;
6250       }
6251
6252       MachineInstrBuilder MIB(&*II);
6253
6254       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6255         unsigned Reg = SavedRegs[i];
6256         if (Subtarget->isThumb2() &&
6257             !ARM::tGPRRegClass.contains(Reg) &&
6258             !ARM::hGPRRegClass.contains(Reg))
6259           continue;
6260         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6261           continue;
6262         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6263           continue;
6264         if (!DefRegs[Reg])
6265           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6266       }
6267
6268       break;
6269     }
6270   }
6271
6272   // Mark all former landing pads as non-landing pads. The dispatch is the only
6273   // landing pad now.
6274   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6275          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6276     (*I)->setIsLandingPad(false);
6277
6278   // The instruction is gone now.
6279   MI->eraseFromParent();
6280
6281   return MBB;
6282 }
6283
6284 static
6285 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6286   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6287        E = MBB->succ_end(); I != E; ++I)
6288     if (*I != Succ)
6289       return *I;
6290   llvm_unreachable("Expecting a BB with two successors!");
6291 }
6292
6293 MachineBasicBlock *ARMTargetLowering::
6294 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6295   // This pseudo instruction has 3 operands: dst, src, size
6296   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6297   // Otherwise, we will generate unrolled scalar copies.
6298   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6299   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6300   MachineFunction::iterator It = BB;
6301   ++It;
6302
6303   unsigned dest = MI->getOperand(0).getReg();
6304   unsigned src = MI->getOperand(1).getReg();
6305   unsigned SizeVal = MI->getOperand(2).getImm();
6306   unsigned Align = MI->getOperand(3).getImm();
6307   DebugLoc dl = MI->getDebugLoc();
6308
6309   bool isThumb2 = Subtarget->isThumb2();
6310   MachineFunction *MF = BB->getParent();
6311   MachineRegisterInfo &MRI = MF->getRegInfo();
6312   unsigned ldrOpc, strOpc, UnitSize = 0;
6313
6314   const TargetRegisterClass *TRC = isThumb2 ?
6315     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6316     (const TargetRegisterClass*)&ARM::GPRRegClass;
6317   const TargetRegisterClass *TRC_Vec = 0;
6318
6319   if (Align & 1) {
6320     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6321     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6322     UnitSize = 1;
6323   } else if (Align & 2) {
6324     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6325     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6326     UnitSize = 2;
6327   } else {
6328     // Check whether we can use NEON instructions.
6329     if (!MF->getFunction()->getFnAttributes().hasNoImplicitFloatAttr() &&
6330         Subtarget->hasNEON()) {
6331       if ((Align % 16 == 0) && SizeVal >= 16) {
6332         ldrOpc = ARM::VLD1q32wb_fixed;
6333         strOpc = ARM::VST1q32wb_fixed;
6334         UnitSize = 16;
6335         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6336       }
6337       else if ((Align % 8 == 0) && SizeVal >= 8) {
6338         ldrOpc = ARM::VLD1d32wb_fixed;
6339         strOpc = ARM::VST1d32wb_fixed;
6340         UnitSize = 8;
6341         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6342       }
6343     }
6344     // Can't use NEON instructions.
6345     if (UnitSize == 0) {
6346       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6347       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6348       UnitSize = 4;
6349     }
6350   }
6351
6352   unsigned BytesLeft = SizeVal % UnitSize;
6353   unsigned LoopSize = SizeVal - BytesLeft;
6354
6355   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6356     // Use LDR and STR to copy.
6357     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6358     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6359     unsigned srcIn = src;
6360     unsigned destIn = dest;
6361     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6362       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6363       unsigned srcOut = MRI.createVirtualRegister(TRC);
6364       unsigned destOut = MRI.createVirtualRegister(TRC);
6365       if (UnitSize >= 8) {
6366         AddDefaultPred(BuildMI(*BB, MI, dl,
6367           TII->get(ldrOpc), scratch)
6368           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6369
6370         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6371           .addReg(destIn).addImm(0).addReg(scratch));
6372       } else if (isThumb2) {
6373         AddDefaultPred(BuildMI(*BB, MI, dl,
6374           TII->get(ldrOpc), scratch)
6375           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6376
6377         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6378           .addReg(scratch).addReg(destIn)
6379           .addImm(UnitSize));
6380       } else {
6381         AddDefaultPred(BuildMI(*BB, MI, dl,
6382           TII->get(ldrOpc), scratch)
6383           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6384           .addImm(UnitSize));
6385
6386         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6387           .addReg(scratch).addReg(destIn)
6388           .addReg(0).addImm(UnitSize));
6389       }
6390       srcIn = srcOut;
6391       destIn = destOut;
6392     }
6393
6394     // Handle the leftover bytes with LDRB and STRB.
6395     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6396     // [destOut] = STRB_POST(scratch, destIn, 1)
6397     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6398     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6399     for (unsigned i = 0; i < BytesLeft; i++) {
6400       unsigned scratch = MRI.createVirtualRegister(TRC);
6401       unsigned srcOut = MRI.createVirtualRegister(TRC);
6402       unsigned destOut = MRI.createVirtualRegister(TRC);
6403       if (isThumb2) {
6404         AddDefaultPred(BuildMI(*BB, MI, dl,
6405           TII->get(ldrOpc),scratch)
6406           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6407
6408         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6409           .addReg(scratch).addReg(destIn)
6410           .addReg(0).addImm(1));
6411       } else {
6412         AddDefaultPred(BuildMI(*BB, MI, dl,
6413           TII->get(ldrOpc),scratch)
6414           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6415
6416         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6417           .addReg(scratch).addReg(destIn)
6418           .addReg(0).addImm(1));
6419       }
6420       srcIn = srcOut;
6421       destIn = destOut;
6422     }
6423     MI->eraseFromParent();   // The instruction is gone now.
6424     return BB;
6425   }
6426
6427   // Expand the pseudo op to a loop.
6428   // thisMBB:
6429   //   ...
6430   //   movw varEnd, # --> with thumb2
6431   //   movt varEnd, #
6432   //   ldrcp varEnd, idx --> without thumb2
6433   //   fallthrough --> loopMBB
6434   // loopMBB:
6435   //   PHI varPhi, varEnd, varLoop
6436   //   PHI srcPhi, src, srcLoop
6437   //   PHI destPhi, dst, destLoop
6438   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6439   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6440   //   subs varLoop, varPhi, #UnitSize
6441   //   bne loopMBB
6442   //   fallthrough --> exitMBB
6443   // exitMBB:
6444   //   epilogue to handle left-over bytes
6445   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6446   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6447   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6448   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6449   MF->insert(It, loopMBB);
6450   MF->insert(It, exitMBB);
6451
6452   // Transfer the remainder of BB and its successor edges to exitMBB.
6453   exitMBB->splice(exitMBB->begin(), BB,
6454                   llvm::next(MachineBasicBlock::iterator(MI)),
6455                   BB->end());
6456   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6457
6458   // Load an immediate to varEnd.
6459   unsigned varEnd = MRI.createVirtualRegister(TRC);
6460   if (isThumb2) {
6461     unsigned VReg1 = varEnd;
6462     if ((LoopSize & 0xFFFF0000) != 0)
6463       VReg1 = MRI.createVirtualRegister(TRC);
6464     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6465                    .addImm(LoopSize & 0xFFFF));
6466
6467     if ((LoopSize & 0xFFFF0000) != 0)
6468       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6469                      .addReg(VReg1)
6470                      .addImm(LoopSize >> 16));
6471   } else {
6472     MachineConstantPool *ConstantPool = MF->getConstantPool();
6473     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6474     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6475
6476     // MachineConstantPool wants an explicit alignment.
6477     unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6478     if (Align == 0)
6479       Align = getTargetData()->getTypeAllocSize(C->getType());
6480     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6481
6482     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6483                    .addReg(varEnd, RegState::Define)
6484                    .addConstantPoolIndex(Idx)
6485                    .addImm(0));
6486   }
6487   BB->addSuccessor(loopMBB);
6488
6489   // Generate the loop body:
6490   //   varPhi = PHI(varLoop, varEnd)
6491   //   srcPhi = PHI(srcLoop, src)
6492   //   destPhi = PHI(destLoop, dst)
6493   MachineBasicBlock *entryBB = BB;
6494   BB = loopMBB;
6495   unsigned varLoop = MRI.createVirtualRegister(TRC);
6496   unsigned varPhi = MRI.createVirtualRegister(TRC);
6497   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6498   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6499   unsigned destLoop = MRI.createVirtualRegister(TRC);
6500   unsigned destPhi = MRI.createVirtualRegister(TRC);
6501
6502   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6503     .addReg(varLoop).addMBB(loopMBB)
6504     .addReg(varEnd).addMBB(entryBB);
6505   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6506     .addReg(srcLoop).addMBB(loopMBB)
6507     .addReg(src).addMBB(entryBB);
6508   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6509     .addReg(destLoop).addMBB(loopMBB)
6510     .addReg(dest).addMBB(entryBB);
6511
6512   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6513   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6514   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6515   if (UnitSize >= 8) {
6516     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6517       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6518
6519     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6520       .addReg(destPhi).addImm(0).addReg(scratch));
6521   } else if (isThumb2) {
6522     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6523       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6524
6525     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6526       .addReg(scratch).addReg(destPhi)
6527       .addImm(UnitSize));
6528   } else {
6529     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6530       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6531       .addImm(UnitSize));
6532
6533     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6534       .addReg(scratch).addReg(destPhi)
6535       .addReg(0).addImm(UnitSize));
6536   }
6537
6538   // Decrement loop variable by UnitSize.
6539   MachineInstrBuilder MIB = BuildMI(BB, dl,
6540     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6541   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6542   MIB->getOperand(5).setReg(ARM::CPSR);
6543   MIB->getOperand(5).setIsDef(true);
6544
6545   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6546     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6547
6548   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6549   BB->addSuccessor(loopMBB);
6550   BB->addSuccessor(exitMBB);
6551
6552   // Add epilogue to handle BytesLeft.
6553   BB = exitMBB;
6554   MachineInstr *StartOfExit = exitMBB->begin();
6555   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6556   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6557
6558   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6559   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6560   unsigned srcIn = srcLoop;
6561   unsigned destIn = destLoop;
6562   for (unsigned i = 0; i < BytesLeft; i++) {
6563     unsigned scratch = MRI.createVirtualRegister(TRC);
6564     unsigned srcOut = MRI.createVirtualRegister(TRC);
6565     unsigned destOut = MRI.createVirtualRegister(TRC);
6566     if (isThumb2) {
6567       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6568         TII->get(ldrOpc),scratch)
6569         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6570
6571       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6572         .addReg(scratch).addReg(destIn)
6573         .addImm(1));
6574     } else {
6575       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6576         TII->get(ldrOpc),scratch)
6577         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6578
6579       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6580         .addReg(scratch).addReg(destIn)
6581         .addReg(0).addImm(1));
6582     }
6583     srcIn = srcOut;
6584     destIn = destOut;
6585   }
6586
6587   MI->eraseFromParent();   // The instruction is gone now.
6588   return BB;
6589 }
6590
6591 MachineBasicBlock *
6592 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6593                                                MachineBasicBlock *BB) const {
6594   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6595   DebugLoc dl = MI->getDebugLoc();
6596   bool isThumb2 = Subtarget->isThumb2();
6597   switch (MI->getOpcode()) {
6598   default: {
6599     MI->dump();
6600     llvm_unreachable("Unexpected instr type to insert");
6601   }
6602   // The Thumb2 pre-indexed stores have the same MI operands, they just
6603   // define them differently in the .td files from the isel patterns, so
6604   // they need pseudos.
6605   case ARM::t2STR_preidx:
6606     MI->setDesc(TII->get(ARM::t2STR_PRE));
6607     return BB;
6608   case ARM::t2STRB_preidx:
6609     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6610     return BB;
6611   case ARM::t2STRH_preidx:
6612     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6613     return BB;
6614
6615   case ARM::STRi_preidx:
6616   case ARM::STRBi_preidx: {
6617     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6618       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6619     // Decode the offset.
6620     unsigned Offset = MI->getOperand(4).getImm();
6621     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6622     Offset = ARM_AM::getAM2Offset(Offset);
6623     if (isSub)
6624       Offset = -Offset;
6625
6626     MachineMemOperand *MMO = *MI->memoperands_begin();
6627     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6628       .addOperand(MI->getOperand(0))  // Rn_wb
6629       .addOperand(MI->getOperand(1))  // Rt
6630       .addOperand(MI->getOperand(2))  // Rn
6631       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6632       .addOperand(MI->getOperand(5))  // pred
6633       .addOperand(MI->getOperand(6))
6634       .addMemOperand(MMO);
6635     MI->eraseFromParent();
6636     return BB;
6637   }
6638   case ARM::STRr_preidx:
6639   case ARM::STRBr_preidx:
6640   case ARM::STRH_preidx: {
6641     unsigned NewOpc;
6642     switch (MI->getOpcode()) {
6643     default: llvm_unreachable("unexpected opcode!");
6644     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6645     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6646     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6647     }
6648     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6649     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6650       MIB.addOperand(MI->getOperand(i));
6651     MI->eraseFromParent();
6652     return BB;
6653   }
6654   case ARM::ATOMIC_LOAD_ADD_I8:
6655      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6656   case ARM::ATOMIC_LOAD_ADD_I16:
6657      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6658   case ARM::ATOMIC_LOAD_ADD_I32:
6659      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6660
6661   case ARM::ATOMIC_LOAD_AND_I8:
6662      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6663   case ARM::ATOMIC_LOAD_AND_I16:
6664      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6665   case ARM::ATOMIC_LOAD_AND_I32:
6666      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6667
6668   case ARM::ATOMIC_LOAD_OR_I8:
6669      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6670   case ARM::ATOMIC_LOAD_OR_I16:
6671      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6672   case ARM::ATOMIC_LOAD_OR_I32:
6673      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6674
6675   case ARM::ATOMIC_LOAD_XOR_I8:
6676      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6677   case ARM::ATOMIC_LOAD_XOR_I16:
6678      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6679   case ARM::ATOMIC_LOAD_XOR_I32:
6680      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6681
6682   case ARM::ATOMIC_LOAD_NAND_I8:
6683      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6684   case ARM::ATOMIC_LOAD_NAND_I16:
6685      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6686   case ARM::ATOMIC_LOAD_NAND_I32:
6687      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6688
6689   case ARM::ATOMIC_LOAD_SUB_I8:
6690      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6691   case ARM::ATOMIC_LOAD_SUB_I16:
6692      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6693   case ARM::ATOMIC_LOAD_SUB_I32:
6694      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6695
6696   case ARM::ATOMIC_LOAD_MIN_I8:
6697      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6698   case ARM::ATOMIC_LOAD_MIN_I16:
6699      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6700   case ARM::ATOMIC_LOAD_MIN_I32:
6701      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6702
6703   case ARM::ATOMIC_LOAD_MAX_I8:
6704      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6705   case ARM::ATOMIC_LOAD_MAX_I16:
6706      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6707   case ARM::ATOMIC_LOAD_MAX_I32:
6708      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6709
6710   case ARM::ATOMIC_LOAD_UMIN_I8:
6711      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6712   case ARM::ATOMIC_LOAD_UMIN_I16:
6713      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6714   case ARM::ATOMIC_LOAD_UMIN_I32:
6715      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6716
6717   case ARM::ATOMIC_LOAD_UMAX_I8:
6718      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6719   case ARM::ATOMIC_LOAD_UMAX_I16:
6720      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6721   case ARM::ATOMIC_LOAD_UMAX_I32:
6722      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6723
6724   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6725   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6726   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6727
6728   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6729   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6730   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6731
6732
6733   case ARM::ATOMADD6432:
6734     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6735                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6736                               /*NeedsCarry*/ true);
6737   case ARM::ATOMSUB6432:
6738     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6739                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6740                               /*NeedsCarry*/ true);
6741   case ARM::ATOMOR6432:
6742     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6743                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6744   case ARM::ATOMXOR6432:
6745     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6746                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6747   case ARM::ATOMAND6432:
6748     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6749                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6750   case ARM::ATOMSWAP6432:
6751     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6752   case ARM::ATOMCMPXCHG6432:
6753     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6754                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6755                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6756
6757   case ARM::tMOVCCr_pseudo: {
6758     // To "insert" a SELECT_CC instruction, we actually have to insert the
6759     // diamond control-flow pattern.  The incoming instruction knows the
6760     // destination vreg to set, the condition code register to branch on, the
6761     // true/false values to select between, and a branch opcode to use.
6762     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6763     MachineFunction::iterator It = BB;
6764     ++It;
6765
6766     //  thisMBB:
6767     //  ...
6768     //   TrueVal = ...
6769     //   cmpTY ccX, r1, r2
6770     //   bCC copy1MBB
6771     //   fallthrough --> copy0MBB
6772     MachineBasicBlock *thisMBB  = BB;
6773     MachineFunction *F = BB->getParent();
6774     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6775     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6776     F->insert(It, copy0MBB);
6777     F->insert(It, sinkMBB);
6778
6779     // Transfer the remainder of BB and its successor edges to sinkMBB.
6780     sinkMBB->splice(sinkMBB->begin(), BB,
6781                     llvm::next(MachineBasicBlock::iterator(MI)),
6782                     BB->end());
6783     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6784
6785     BB->addSuccessor(copy0MBB);
6786     BB->addSuccessor(sinkMBB);
6787
6788     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6789       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6790
6791     //  copy0MBB:
6792     //   %FalseValue = ...
6793     //   # fallthrough to sinkMBB
6794     BB = copy0MBB;
6795
6796     // Update machine-CFG edges
6797     BB->addSuccessor(sinkMBB);
6798
6799     //  sinkMBB:
6800     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6801     //  ...
6802     BB = sinkMBB;
6803     BuildMI(*BB, BB->begin(), dl,
6804             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6805       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6806       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6807
6808     MI->eraseFromParent();   // The pseudo instruction is gone now.
6809     return BB;
6810   }
6811
6812   case ARM::BCCi64:
6813   case ARM::BCCZi64: {
6814     // If there is an unconditional branch to the other successor, remove it.
6815     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6816
6817     // Compare both parts that make up the double comparison separately for
6818     // equality.
6819     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6820
6821     unsigned LHS1 = MI->getOperand(1).getReg();
6822     unsigned LHS2 = MI->getOperand(2).getReg();
6823     if (RHSisZero) {
6824       AddDefaultPred(BuildMI(BB, dl,
6825                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6826                      .addReg(LHS1).addImm(0));
6827       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6828         .addReg(LHS2).addImm(0)
6829         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6830     } else {
6831       unsigned RHS1 = MI->getOperand(3).getReg();
6832       unsigned RHS2 = MI->getOperand(4).getReg();
6833       AddDefaultPred(BuildMI(BB, dl,
6834                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6835                      .addReg(LHS1).addReg(RHS1));
6836       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6837         .addReg(LHS2).addReg(RHS2)
6838         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6839     }
6840
6841     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6842     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6843     if (MI->getOperand(0).getImm() == ARMCC::NE)
6844       std::swap(destMBB, exitMBB);
6845
6846     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6847       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6848     if (isThumb2)
6849       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6850     else
6851       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6852
6853     MI->eraseFromParent();   // The pseudo instruction is gone now.
6854     return BB;
6855   }
6856
6857   case ARM::Int_eh_sjlj_setjmp:
6858   case ARM::Int_eh_sjlj_setjmp_nofp:
6859   case ARM::tInt_eh_sjlj_setjmp:
6860   case ARM::t2Int_eh_sjlj_setjmp:
6861   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6862     EmitSjLjDispatchBlock(MI, BB);
6863     return BB;
6864
6865   case ARM::ABS:
6866   case ARM::t2ABS: {
6867     // To insert an ABS instruction, we have to insert the
6868     // diamond control-flow pattern.  The incoming instruction knows the
6869     // source vreg to test against 0, the destination vreg to set,
6870     // the condition code register to branch on, the
6871     // true/false values to select between, and a branch opcode to use.
6872     // It transforms
6873     //     V1 = ABS V0
6874     // into
6875     //     V2 = MOVS V0
6876     //     BCC                      (branch to SinkBB if V0 >= 0)
6877     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6878     //     SinkBB: V1 = PHI(V2, V3)
6879     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6880     MachineFunction::iterator BBI = BB;
6881     ++BBI;
6882     MachineFunction *Fn = BB->getParent();
6883     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6884     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6885     Fn->insert(BBI, RSBBB);
6886     Fn->insert(BBI, SinkBB);
6887
6888     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6889     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6890     bool isThumb2 = Subtarget->isThumb2();
6891     MachineRegisterInfo &MRI = Fn->getRegInfo();
6892     // In Thumb mode S must not be specified if source register is the SP or
6893     // PC and if destination register is the SP, so restrict register class
6894     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6895       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6896       (const TargetRegisterClass*)&ARM::GPRRegClass);
6897
6898     // Transfer the remainder of BB and its successor edges to sinkMBB.
6899     SinkBB->splice(SinkBB->begin(), BB,
6900       llvm::next(MachineBasicBlock::iterator(MI)),
6901       BB->end());
6902     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6903
6904     BB->addSuccessor(RSBBB);
6905     BB->addSuccessor(SinkBB);
6906
6907     // fall through to SinkMBB
6908     RSBBB->addSuccessor(SinkBB);
6909
6910     // insert a cmp at the end of BB
6911     AddDefaultPred(BuildMI(BB, dl,
6912                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6913                    .addReg(ABSSrcReg).addImm(0));
6914
6915     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6916     BuildMI(BB, dl,
6917       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6918       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6919
6920     // insert rsbri in RSBBB
6921     // Note: BCC and rsbri will be converted into predicated rsbmi
6922     // by if-conversion pass
6923     BuildMI(*RSBBB, RSBBB->begin(), dl,
6924       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6925       .addReg(ABSSrcReg, RegState::Kill)
6926       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6927
6928     // insert PHI in SinkBB,
6929     // reuse ABSDstReg to not change uses of ABS instruction
6930     BuildMI(*SinkBB, SinkBB->begin(), dl,
6931       TII->get(ARM::PHI), ABSDstReg)
6932       .addReg(NewRsbDstReg).addMBB(RSBBB)
6933       .addReg(ABSSrcReg).addMBB(BB);
6934
6935     // remove ABS instruction
6936     MI->eraseFromParent();
6937
6938     // return last added BB
6939     return SinkBB;
6940   }
6941   case ARM::COPY_STRUCT_BYVAL_I32:
6942     ++NumLoopByVals;
6943     return EmitStructByval(MI, BB);
6944   }
6945 }
6946
6947 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6948                                                       SDNode *Node) const {
6949   if (!MI->hasPostISelHook()) {
6950     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6951            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6952     return;
6953   }
6954
6955   const MCInstrDesc *MCID = &MI->getDesc();
6956   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6957   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6958   // operand is still set to noreg. If needed, set the optional operand's
6959   // register to CPSR, and remove the redundant implicit def.
6960   //
6961   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6962
6963   // Rename pseudo opcodes.
6964   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6965   if (NewOpc) {
6966     const ARMBaseInstrInfo *TII =
6967       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6968     MCID = &TII->get(NewOpc);
6969
6970     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6971            "converted opcode should be the same except for cc_out");
6972
6973     MI->setDesc(*MCID);
6974
6975     // Add the optional cc_out operand
6976     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6977   }
6978   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6979
6980   // Any ARM instruction that sets the 's' bit should specify an optional
6981   // "cc_out" operand in the last operand position.
6982   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6983     assert(!NewOpc && "Optional cc_out operand required");
6984     return;
6985   }
6986   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6987   // since we already have an optional CPSR def.
6988   bool definesCPSR = false;
6989   bool deadCPSR = false;
6990   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6991        i != e; ++i) {
6992     const MachineOperand &MO = MI->getOperand(i);
6993     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6994       definesCPSR = true;
6995       if (MO.isDead())
6996         deadCPSR = true;
6997       MI->RemoveOperand(i);
6998       break;
6999     }
7000   }
7001   if (!definesCPSR) {
7002     assert(!NewOpc && "Optional cc_out operand required");
7003     return;
7004   }
7005   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7006   if (deadCPSR) {
7007     assert(!MI->getOperand(ccOutIdx).getReg() &&
7008            "expect uninitialized optional cc_out operand");
7009     return;
7010   }
7011
7012   // If this instruction was defined with an optional CPSR def and its dag node
7013   // had a live implicit CPSR def, then activate the optional CPSR def.
7014   MachineOperand &MO = MI->getOperand(ccOutIdx);
7015   MO.setReg(ARM::CPSR);
7016   MO.setIsDef(true);
7017 }
7018
7019 //===----------------------------------------------------------------------===//
7020 //                           ARM Optimization Hooks
7021 //===----------------------------------------------------------------------===//
7022
7023 // Helper function that checks if N is a null or all ones constant.
7024 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7025   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7026   if (!C)
7027     return false;
7028   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7029 }
7030
7031 // Return true if N is conditionally 0 or all ones.
7032 // Detects these expressions where cc is an i1 value:
7033 //
7034 //   (select cc 0, y)   [AllOnes=0]
7035 //   (select cc y, 0)   [AllOnes=0]
7036 //   (zext cc)          [AllOnes=0]
7037 //   (sext cc)          [AllOnes=0/1]
7038 //   (select cc -1, y)  [AllOnes=1]
7039 //   (select cc y, -1)  [AllOnes=1]
7040 //
7041 // Invert is set when N is the null/all ones constant when CC is false.
7042 // OtherOp is set to the alternative value of N.
7043 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7044                                        SDValue &CC, bool &Invert,
7045                                        SDValue &OtherOp,
7046                                        SelectionDAG &DAG) {
7047   switch (N->getOpcode()) {
7048   default: return false;
7049   case ISD::SELECT: {
7050     CC = N->getOperand(0);
7051     SDValue N1 = N->getOperand(1);
7052     SDValue N2 = N->getOperand(2);
7053     if (isZeroOrAllOnes(N1, AllOnes)) {
7054       Invert = false;
7055       OtherOp = N2;
7056       return true;
7057     }
7058     if (isZeroOrAllOnes(N2, AllOnes)) {
7059       Invert = true;
7060       OtherOp = N1;
7061       return true;
7062     }
7063     return false;
7064   }
7065   case ISD::ZERO_EXTEND:
7066     // (zext cc) can never be the all ones value.
7067     if (AllOnes)
7068       return false;
7069     // Fall through.
7070   case ISD::SIGN_EXTEND: {
7071     EVT VT = N->getValueType(0);
7072     CC = N->getOperand(0);
7073     if (CC.getValueType() != MVT::i1)
7074       return false;
7075     Invert = !AllOnes;
7076     if (AllOnes)
7077       // When looking for an AllOnes constant, N is an sext, and the 'other'
7078       // value is 0.
7079       OtherOp = DAG.getConstant(0, VT);
7080     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7081       // When looking for a 0 constant, N can be zext or sext.
7082       OtherOp = DAG.getConstant(1, VT);
7083     else
7084       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7085     return true;
7086   }
7087   }
7088 }
7089
7090 // Combine a constant select operand into its use:
7091 //
7092 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7093 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7094 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7095 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7096 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7097 //
7098 // The transform is rejected if the select doesn't have a constant operand that
7099 // is null, or all ones when AllOnes is set.
7100 //
7101 // Also recognize sext/zext from i1:
7102 //
7103 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7104 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7105 //
7106 // These transformations eventually create predicated instructions.
7107 //
7108 // @param N       The node to transform.
7109 // @param Slct    The N operand that is a select.
7110 // @param OtherOp The other N operand (x above).
7111 // @param DCI     Context.
7112 // @param AllOnes Require the select constant to be all ones instead of null.
7113 // @returns The new node, or SDValue() on failure.
7114 static
7115 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7116                             TargetLowering::DAGCombinerInfo &DCI,
7117                             bool AllOnes = false) {
7118   SelectionDAG &DAG = DCI.DAG;
7119   EVT VT = N->getValueType(0);
7120   SDValue NonConstantVal;
7121   SDValue CCOp;
7122   bool SwapSelectOps;
7123   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7124                                   NonConstantVal, DAG))
7125     return SDValue();
7126
7127   // Slct is now know to be the desired identity constant when CC is true.
7128   SDValue TrueVal = OtherOp;
7129   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7130                                  OtherOp, NonConstantVal);
7131   // Unless SwapSelectOps says CC should be false.
7132   if (SwapSelectOps)
7133     std::swap(TrueVal, FalseVal);
7134
7135   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7136                      CCOp, TrueVal, FalseVal);
7137 }
7138
7139 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7140 static
7141 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7142                                        TargetLowering::DAGCombinerInfo &DCI) {
7143   SDValue N0 = N->getOperand(0);
7144   SDValue N1 = N->getOperand(1);
7145   if (N0.getNode()->hasOneUse()) {
7146     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7147     if (Result.getNode())
7148       return Result;
7149   }
7150   if (N1.getNode()->hasOneUse()) {
7151     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7152     if (Result.getNode())
7153       return Result;
7154   }
7155   return SDValue();
7156 }
7157
7158 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7159 // (only after legalization).
7160 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7161                                  TargetLowering::DAGCombinerInfo &DCI,
7162                                  const ARMSubtarget *Subtarget) {
7163
7164   // Only perform optimization if after legalize, and if NEON is available. We
7165   // also expected both operands to be BUILD_VECTORs.
7166   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7167       || N0.getOpcode() != ISD::BUILD_VECTOR
7168       || N1.getOpcode() != ISD::BUILD_VECTOR)
7169     return SDValue();
7170
7171   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7172   EVT VT = N->getValueType(0);
7173   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7174     return SDValue();
7175
7176   // Check that the vector operands are of the right form.
7177   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7178   // operands, where N is the size of the formed vector.
7179   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7180   // index such that we have a pair wise add pattern.
7181
7182   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7183   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7184     return SDValue();
7185   SDValue Vec = N0->getOperand(0)->getOperand(0);
7186   SDNode *V = Vec.getNode();
7187   unsigned nextIndex = 0;
7188
7189   // For each operands to the ADD which are BUILD_VECTORs,
7190   // check to see if each of their operands are an EXTRACT_VECTOR with
7191   // the same vector and appropriate index.
7192   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7193     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7194         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7195
7196       SDValue ExtVec0 = N0->getOperand(i);
7197       SDValue ExtVec1 = N1->getOperand(i);
7198
7199       // First operand is the vector, verify its the same.
7200       if (V != ExtVec0->getOperand(0).getNode() ||
7201           V != ExtVec1->getOperand(0).getNode())
7202         return SDValue();
7203
7204       // Second is the constant, verify its correct.
7205       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7206       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7207
7208       // For the constant, we want to see all the even or all the odd.
7209       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7210           || C1->getZExtValue() != nextIndex+1)
7211         return SDValue();
7212
7213       // Increment index.
7214       nextIndex+=2;
7215     } else
7216       return SDValue();
7217   }
7218
7219   // Create VPADDL node.
7220   SelectionDAG &DAG = DCI.DAG;
7221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7222
7223   // Build operand list.
7224   SmallVector<SDValue, 8> Ops;
7225   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7226                                 TLI.getPointerTy()));
7227
7228   // Input is the vector.
7229   Ops.push_back(Vec);
7230
7231   // Get widened type and narrowed type.
7232   MVT widenType;
7233   unsigned numElem = VT.getVectorNumElements();
7234   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7235     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7236     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7237     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7238     default:
7239       llvm_unreachable("Invalid vector element type for padd optimization.");
7240   }
7241
7242   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7243                             widenType, &Ops[0], Ops.size());
7244   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7245 }
7246
7247 static SDValue findMUL_LOHI(SDValue V) {
7248   if (V->getOpcode() == ISD::UMUL_LOHI ||
7249       V->getOpcode() == ISD::SMUL_LOHI)
7250     return V;
7251   return SDValue();
7252 }
7253
7254 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7255                                      TargetLowering::DAGCombinerInfo &DCI,
7256                                      const ARMSubtarget *Subtarget) {
7257
7258   if (Subtarget->isThumb1Only()) return SDValue();
7259
7260   // Only perform the checks after legalize when the pattern is available.
7261   if (DCI.isBeforeLegalize()) return SDValue();
7262
7263   // Look for multiply add opportunities.
7264   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7265   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7266   // a glue link from the first add to the second add.
7267   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7268   // a S/UMLAL instruction.
7269   //          loAdd   UMUL_LOHI
7270   //            \    / :lo    \ :hi
7271   //             \  /          \          [no multiline comment]
7272   //              ADDC         |  hiAdd
7273   //                 \ :glue  /  /
7274   //                  \      /  /
7275   //                    ADDE
7276   //
7277   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7278   SDValue AddcOp0 = AddcNode->getOperand(0);
7279   SDValue AddcOp1 = AddcNode->getOperand(1);
7280
7281   // Check if the two operands are from the same mul_lohi node.
7282   if (AddcOp0.getNode() == AddcOp1.getNode())
7283     return SDValue();
7284
7285   assert(AddcNode->getNumValues() == 2 &&
7286          AddcNode->getValueType(0) == MVT::i32 &&
7287          AddcNode->getValueType(1) == MVT::Glue &&
7288          "Expect ADDC with two result values: i32, glue");
7289
7290   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7291   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7292       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7293       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7294       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7295     return SDValue();
7296
7297   // Look for the glued ADDE.
7298   SDNode* AddeNode = AddcNode->getGluedUser();
7299   if (AddeNode == NULL)
7300     return SDValue();
7301
7302   // Make sure it is really an ADDE.
7303   if (AddeNode->getOpcode() != ISD::ADDE)
7304     return SDValue();
7305
7306   assert(AddeNode->getNumOperands() == 3 &&
7307          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7308          "ADDE node has the wrong inputs");
7309
7310   // Check for the triangle shape.
7311   SDValue AddeOp0 = AddeNode->getOperand(0);
7312   SDValue AddeOp1 = AddeNode->getOperand(1);
7313
7314   // Make sure that the ADDE operands are not coming from the same node.
7315   if (AddeOp0.getNode() == AddeOp1.getNode())
7316     return SDValue();
7317
7318   // Find the MUL_LOHI node walking up ADDE's operands.
7319   bool IsLeftOperandMUL = false;
7320   SDValue MULOp = findMUL_LOHI(AddeOp0);
7321   if (MULOp == SDValue())
7322    MULOp = findMUL_LOHI(AddeOp1);
7323   else
7324     IsLeftOperandMUL = true;
7325   if (MULOp == SDValue())
7326      return SDValue();
7327
7328   // Figure out the right opcode.
7329   unsigned Opc = MULOp->getOpcode();
7330   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7331
7332   // Figure out the high and low input values to the MLAL node.
7333   SDValue* HiMul = &MULOp;
7334   SDValue* HiAdd = NULL;
7335   SDValue* LoMul = NULL;
7336   SDValue* LowAdd = NULL;
7337
7338   if (IsLeftOperandMUL)
7339     HiAdd = &AddeOp1;
7340   else
7341     HiAdd = &AddeOp0;
7342
7343
7344   if (AddcOp0->getOpcode() == Opc) {
7345     LoMul = &AddcOp0;
7346     LowAdd = &AddcOp1;
7347   }
7348   if (AddcOp1->getOpcode() == Opc) {
7349     LoMul = &AddcOp1;
7350     LowAdd = &AddcOp0;
7351   }
7352
7353   if (LoMul == NULL)
7354     return SDValue();
7355
7356   if (LoMul->getNode() != HiMul->getNode())
7357     return SDValue();
7358
7359   // Create the merged node.
7360   SelectionDAG &DAG = DCI.DAG;
7361
7362   // Build operand list.
7363   SmallVector<SDValue, 8> Ops;
7364   Ops.push_back(LoMul->getOperand(0));
7365   Ops.push_back(LoMul->getOperand(1));
7366   Ops.push_back(*LowAdd);
7367   Ops.push_back(*HiAdd);
7368
7369   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7370                                  DAG.getVTList(MVT::i32, MVT::i32),
7371                                  &Ops[0], Ops.size());
7372
7373   // Replace the ADDs' nodes uses by the MLA node's values.
7374   SDValue HiMLALResult(MLALNode.getNode(), 1);
7375   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7376
7377   SDValue LoMLALResult(MLALNode.getNode(), 0);
7378   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7379
7380   // Return original node to notify the driver to stop replacing.
7381   SDValue resNode(AddcNode, 0);
7382   return resNode;
7383 }
7384
7385 /// PerformADDCCombine - Target-specific dag combine transform from
7386 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7387 static SDValue PerformADDCCombine(SDNode *N,
7388                                  TargetLowering::DAGCombinerInfo &DCI,
7389                                  const ARMSubtarget *Subtarget) {
7390
7391   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7392
7393 }
7394
7395 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7396 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7397 /// called with the default operands, and if that fails, with commuted
7398 /// operands.
7399 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7400                                           TargetLowering::DAGCombinerInfo &DCI,
7401                                           const ARMSubtarget *Subtarget){
7402
7403   // Attempt to create vpaddl for this add.
7404   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7405   if (Result.getNode())
7406     return Result;
7407
7408   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7409   if (N0.getNode()->hasOneUse()) {
7410     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7411     if (Result.getNode()) return Result;
7412   }
7413   return SDValue();
7414 }
7415
7416 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7417 ///
7418 static SDValue PerformADDCombine(SDNode *N,
7419                                  TargetLowering::DAGCombinerInfo &DCI,
7420                                  const ARMSubtarget *Subtarget) {
7421   SDValue N0 = N->getOperand(0);
7422   SDValue N1 = N->getOperand(1);
7423
7424   // First try with the default operand order.
7425   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7426   if (Result.getNode())
7427     return Result;
7428
7429   // If that didn't work, try again with the operands commuted.
7430   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7431 }
7432
7433 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7434 ///
7435 static SDValue PerformSUBCombine(SDNode *N,
7436                                  TargetLowering::DAGCombinerInfo &DCI) {
7437   SDValue N0 = N->getOperand(0);
7438   SDValue N1 = N->getOperand(1);
7439
7440   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7441   if (N1.getNode()->hasOneUse()) {
7442     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7443     if (Result.getNode()) return Result;
7444   }
7445
7446   return SDValue();
7447 }
7448
7449 /// PerformVMULCombine
7450 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7451 /// special multiplier accumulator forwarding.
7452 ///   vmul d3, d0, d2
7453 ///   vmla d3, d1, d2
7454 /// is faster than
7455 ///   vadd d3, d0, d1
7456 ///   vmul d3, d3, d2
7457 static SDValue PerformVMULCombine(SDNode *N,
7458                                   TargetLowering::DAGCombinerInfo &DCI,
7459                                   const ARMSubtarget *Subtarget) {
7460   if (!Subtarget->hasVMLxForwarding())
7461     return SDValue();
7462
7463   SelectionDAG &DAG = DCI.DAG;
7464   SDValue N0 = N->getOperand(0);
7465   SDValue N1 = N->getOperand(1);
7466   unsigned Opcode = N0.getOpcode();
7467   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7468       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7469     Opcode = N1.getOpcode();
7470     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7471         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7472       return SDValue();
7473     std::swap(N0, N1);
7474   }
7475
7476   EVT VT = N->getValueType(0);
7477   DebugLoc DL = N->getDebugLoc();
7478   SDValue N00 = N0->getOperand(0);
7479   SDValue N01 = N0->getOperand(1);
7480   return DAG.getNode(Opcode, DL, VT,
7481                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7482                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7483 }
7484
7485 static SDValue PerformMULCombine(SDNode *N,
7486                                  TargetLowering::DAGCombinerInfo &DCI,
7487                                  const ARMSubtarget *Subtarget) {
7488   SelectionDAG &DAG = DCI.DAG;
7489
7490   if (Subtarget->isThumb1Only())
7491     return SDValue();
7492
7493   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7494     return SDValue();
7495
7496   EVT VT = N->getValueType(0);
7497   if (VT.is64BitVector() || VT.is128BitVector())
7498     return PerformVMULCombine(N, DCI, Subtarget);
7499   if (VT != MVT::i32)
7500     return SDValue();
7501
7502   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7503   if (!C)
7504     return SDValue();
7505
7506   int64_t MulAmt = C->getSExtValue();
7507   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7508
7509   ShiftAmt = ShiftAmt & (32 - 1);
7510   SDValue V = N->getOperand(0);
7511   DebugLoc DL = N->getDebugLoc();
7512
7513   SDValue Res;
7514   MulAmt >>= ShiftAmt;
7515
7516   if (MulAmt >= 0) {
7517     if (isPowerOf2_32(MulAmt - 1)) {
7518       // (mul x, 2^N + 1) => (add (shl x, N), x)
7519       Res = DAG.getNode(ISD::ADD, DL, VT,
7520                         V,
7521                         DAG.getNode(ISD::SHL, DL, VT,
7522                                     V,
7523                                     DAG.getConstant(Log2_32(MulAmt - 1),
7524                                                     MVT::i32)));
7525     } else if (isPowerOf2_32(MulAmt + 1)) {
7526       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7527       Res = DAG.getNode(ISD::SUB, DL, VT,
7528                         DAG.getNode(ISD::SHL, DL, VT,
7529                                     V,
7530                                     DAG.getConstant(Log2_32(MulAmt + 1),
7531                                                     MVT::i32)),
7532                         V);
7533     } else
7534       return SDValue();
7535   } else {
7536     uint64_t MulAmtAbs = -MulAmt;
7537     if (isPowerOf2_32(MulAmtAbs + 1)) {
7538       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7539       Res = DAG.getNode(ISD::SUB, DL, VT,
7540                         V,
7541                         DAG.getNode(ISD::SHL, DL, VT,
7542                                     V,
7543                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7544                                                     MVT::i32)));
7545     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7546       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7547       Res = DAG.getNode(ISD::ADD, DL, VT,
7548                         V,
7549                         DAG.getNode(ISD::SHL, DL, VT,
7550                                     V,
7551                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7552                                                     MVT::i32)));
7553       Res = DAG.getNode(ISD::SUB, DL, VT,
7554                         DAG.getConstant(0, MVT::i32),Res);
7555
7556     } else
7557       return SDValue();
7558   }
7559
7560   if (ShiftAmt != 0)
7561     Res = DAG.getNode(ISD::SHL, DL, VT,
7562                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7563
7564   // Do not add new nodes to DAG combiner worklist.
7565   DCI.CombineTo(N, Res, false);
7566   return SDValue();
7567 }
7568
7569 static SDValue PerformANDCombine(SDNode *N,
7570                                  TargetLowering::DAGCombinerInfo &DCI,
7571                                  const ARMSubtarget *Subtarget) {
7572
7573   // Attempt to use immediate-form VBIC
7574   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7575   DebugLoc dl = N->getDebugLoc();
7576   EVT VT = N->getValueType(0);
7577   SelectionDAG &DAG = DCI.DAG;
7578
7579   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7580     return SDValue();
7581
7582   APInt SplatBits, SplatUndef;
7583   unsigned SplatBitSize;
7584   bool HasAnyUndefs;
7585   if (BVN &&
7586       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7587     if (SplatBitSize <= 64) {
7588       EVT VbicVT;
7589       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7590                                       SplatUndef.getZExtValue(), SplatBitSize,
7591                                       DAG, VbicVT, VT.is128BitVector(),
7592                                       OtherModImm);
7593       if (Val.getNode()) {
7594         SDValue Input =
7595           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7596         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7597         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7598       }
7599     }
7600   }
7601
7602   if (!Subtarget->isThumb1Only()) {
7603     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7604     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7605     if (Result.getNode())
7606       return Result;
7607   }
7608
7609   return SDValue();
7610 }
7611
7612 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7613 static SDValue PerformORCombine(SDNode *N,
7614                                 TargetLowering::DAGCombinerInfo &DCI,
7615                                 const ARMSubtarget *Subtarget) {
7616   // Attempt to use immediate-form VORR
7617   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7618   DebugLoc dl = N->getDebugLoc();
7619   EVT VT = N->getValueType(0);
7620   SelectionDAG &DAG = DCI.DAG;
7621
7622   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7623     return SDValue();
7624
7625   APInt SplatBits, SplatUndef;
7626   unsigned SplatBitSize;
7627   bool HasAnyUndefs;
7628   if (BVN && Subtarget->hasNEON() &&
7629       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7630     if (SplatBitSize <= 64) {
7631       EVT VorrVT;
7632       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7633                                       SplatUndef.getZExtValue(), SplatBitSize,
7634                                       DAG, VorrVT, VT.is128BitVector(),
7635                                       OtherModImm);
7636       if (Val.getNode()) {
7637         SDValue Input =
7638           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7639         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7640         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7641       }
7642     }
7643   }
7644
7645   if (!Subtarget->isThumb1Only()) {
7646     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7647     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7648     if (Result.getNode())
7649       return Result;
7650   }
7651
7652   // The code below optimizes (or (and X, Y), Z).
7653   // The AND operand needs to have a single user to make these optimizations
7654   // profitable.
7655   SDValue N0 = N->getOperand(0);
7656   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7657     return SDValue();
7658   SDValue N1 = N->getOperand(1);
7659
7660   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7661   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7662       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7663     APInt SplatUndef;
7664     unsigned SplatBitSize;
7665     bool HasAnyUndefs;
7666
7667     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7668     APInt SplatBits0;
7669     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7670                                   HasAnyUndefs) && !HasAnyUndefs) {
7671       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7672       APInt SplatBits1;
7673       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7674                                     HasAnyUndefs) && !HasAnyUndefs &&
7675           SplatBits0 == ~SplatBits1) {
7676         // Canonicalize the vector type to make instruction selection simpler.
7677         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7678         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7679                                      N0->getOperand(1), N0->getOperand(0),
7680                                      N1->getOperand(0));
7681         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7682       }
7683     }
7684   }
7685
7686   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7687   // reasonable.
7688
7689   // BFI is only available on V6T2+
7690   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7691     return SDValue();
7692
7693   DebugLoc DL = N->getDebugLoc();
7694   // 1) or (and A, mask), val => ARMbfi A, val, mask
7695   //      iff (val & mask) == val
7696   //
7697   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7698   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7699   //          && mask == ~mask2
7700   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7701   //          && ~mask == mask2
7702   //  (i.e., copy a bitfield value into another bitfield of the same width)
7703
7704   if (VT != MVT::i32)
7705     return SDValue();
7706
7707   SDValue N00 = N0.getOperand(0);
7708
7709   // The value and the mask need to be constants so we can verify this is
7710   // actually a bitfield set. If the mask is 0xffff, we can do better
7711   // via a movt instruction, so don't use BFI in that case.
7712   SDValue MaskOp = N0.getOperand(1);
7713   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7714   if (!MaskC)
7715     return SDValue();
7716   unsigned Mask = MaskC->getZExtValue();
7717   if (Mask == 0xffff)
7718     return SDValue();
7719   SDValue Res;
7720   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7721   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7722   if (N1C) {
7723     unsigned Val = N1C->getZExtValue();
7724     if ((Val & ~Mask) != Val)
7725       return SDValue();
7726
7727     if (ARM::isBitFieldInvertedMask(Mask)) {
7728       Val >>= CountTrailingZeros_32(~Mask);
7729
7730       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7731                         DAG.getConstant(Val, MVT::i32),
7732                         DAG.getConstant(Mask, MVT::i32));
7733
7734       // Do not add new nodes to DAG combiner worklist.
7735       DCI.CombineTo(N, Res, false);
7736       return SDValue();
7737     }
7738   } else if (N1.getOpcode() == ISD::AND) {
7739     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7740     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7741     if (!N11C)
7742       return SDValue();
7743     unsigned Mask2 = N11C->getZExtValue();
7744
7745     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7746     // as is to match.
7747     if (ARM::isBitFieldInvertedMask(Mask) &&
7748         (Mask == ~Mask2)) {
7749       // The pack halfword instruction works better for masks that fit it,
7750       // so use that when it's available.
7751       if (Subtarget->hasT2ExtractPack() &&
7752           (Mask == 0xffff || Mask == 0xffff0000))
7753         return SDValue();
7754       // 2a
7755       unsigned amt = CountTrailingZeros_32(Mask2);
7756       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7757                         DAG.getConstant(amt, MVT::i32));
7758       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7759                         DAG.getConstant(Mask, MVT::i32));
7760       // Do not add new nodes to DAG combiner worklist.
7761       DCI.CombineTo(N, Res, false);
7762       return SDValue();
7763     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7764                (~Mask == Mask2)) {
7765       // The pack halfword instruction works better for masks that fit it,
7766       // so use that when it's available.
7767       if (Subtarget->hasT2ExtractPack() &&
7768           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7769         return SDValue();
7770       // 2b
7771       unsigned lsb = CountTrailingZeros_32(Mask);
7772       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7773                         DAG.getConstant(lsb, MVT::i32));
7774       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7775                         DAG.getConstant(Mask2, MVT::i32));
7776       // Do not add new nodes to DAG combiner worklist.
7777       DCI.CombineTo(N, Res, false);
7778       return SDValue();
7779     }
7780   }
7781
7782   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7783       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7784       ARM::isBitFieldInvertedMask(~Mask)) {
7785     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7786     // where lsb(mask) == #shamt and masked bits of B are known zero.
7787     SDValue ShAmt = N00.getOperand(1);
7788     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7789     unsigned LSB = CountTrailingZeros_32(Mask);
7790     if (ShAmtC != LSB)
7791       return SDValue();
7792
7793     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7794                       DAG.getConstant(~Mask, MVT::i32));
7795
7796     // Do not add new nodes to DAG combiner worklist.
7797     DCI.CombineTo(N, Res, false);
7798   }
7799
7800   return SDValue();
7801 }
7802
7803 static SDValue PerformXORCombine(SDNode *N,
7804                                  TargetLowering::DAGCombinerInfo &DCI,
7805                                  const ARMSubtarget *Subtarget) {
7806   EVT VT = N->getValueType(0);
7807   SelectionDAG &DAG = DCI.DAG;
7808
7809   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7810     return SDValue();
7811
7812   if (!Subtarget->isThumb1Only()) {
7813     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7814     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7815     if (Result.getNode())
7816       return Result;
7817   }
7818
7819   return SDValue();
7820 }
7821
7822 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7823 /// the bits being cleared by the AND are not demanded by the BFI.
7824 static SDValue PerformBFICombine(SDNode *N,
7825                                  TargetLowering::DAGCombinerInfo &DCI) {
7826   SDValue N1 = N->getOperand(1);
7827   if (N1.getOpcode() == ISD::AND) {
7828     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7829     if (!N11C)
7830       return SDValue();
7831     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7832     unsigned LSB = CountTrailingZeros_32(~InvMask);
7833     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7834     unsigned Mask = (1 << Width)-1;
7835     unsigned Mask2 = N11C->getZExtValue();
7836     if ((Mask & (~Mask2)) == 0)
7837       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7838                              N->getOperand(0), N1.getOperand(0),
7839                              N->getOperand(2));
7840   }
7841   return SDValue();
7842 }
7843
7844 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7845 /// ARMISD::VMOVRRD.
7846 static SDValue PerformVMOVRRDCombine(SDNode *N,
7847                                      TargetLowering::DAGCombinerInfo &DCI) {
7848   // vmovrrd(vmovdrr x, y) -> x,y
7849   SDValue InDouble = N->getOperand(0);
7850   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7851     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7852
7853   // vmovrrd(load f64) -> (load i32), (load i32)
7854   SDNode *InNode = InDouble.getNode();
7855   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7856       InNode->getValueType(0) == MVT::f64 &&
7857       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7858       !cast<LoadSDNode>(InNode)->isVolatile()) {
7859     // TODO: Should this be done for non-FrameIndex operands?
7860     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7861
7862     SelectionDAG &DAG = DCI.DAG;
7863     DebugLoc DL = LD->getDebugLoc();
7864     SDValue BasePtr = LD->getBasePtr();
7865     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7866                                  LD->getPointerInfo(), LD->isVolatile(),
7867                                  LD->isNonTemporal(), LD->isInvariant(),
7868                                  LD->getAlignment());
7869
7870     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7871                                     DAG.getConstant(4, MVT::i32));
7872     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7873                                  LD->getPointerInfo(), LD->isVolatile(),
7874                                  LD->isNonTemporal(), LD->isInvariant(),
7875                                  std::min(4U, LD->getAlignment() / 2));
7876
7877     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7878     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7879     DCI.RemoveFromWorklist(LD);
7880     DAG.DeleteNode(LD);
7881     return Result;
7882   }
7883
7884   return SDValue();
7885 }
7886
7887 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7888 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7889 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7890   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7891   SDValue Op0 = N->getOperand(0);
7892   SDValue Op1 = N->getOperand(1);
7893   if (Op0.getOpcode() == ISD::BITCAST)
7894     Op0 = Op0.getOperand(0);
7895   if (Op1.getOpcode() == ISD::BITCAST)
7896     Op1 = Op1.getOperand(0);
7897   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7898       Op0.getNode() == Op1.getNode() &&
7899       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7900     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7901                        N->getValueType(0), Op0.getOperand(0));
7902   return SDValue();
7903 }
7904
7905 /// PerformSTORECombine - Target-specific dag combine xforms for
7906 /// ISD::STORE.
7907 static SDValue PerformSTORECombine(SDNode *N,
7908                                    TargetLowering::DAGCombinerInfo &DCI) {
7909   StoreSDNode *St = cast<StoreSDNode>(N);
7910   if (St->isVolatile())
7911     return SDValue();
7912
7913   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
7914   // pack all of the elements in one place.  Next, store to memory in fewer
7915   // chunks.
7916   SDValue StVal = St->getValue();
7917   EVT VT = StVal.getValueType();
7918   if (St->isTruncatingStore() && VT.isVector()) {
7919     SelectionDAG &DAG = DCI.DAG;
7920     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7921     EVT StVT = St->getMemoryVT();
7922     unsigned NumElems = VT.getVectorNumElements();
7923     assert(StVT != VT && "Cannot truncate to the same type");
7924     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7925     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7926
7927     // From, To sizes and ElemCount must be pow of two
7928     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7929
7930     // We are going to use the original vector elt for storing.
7931     // Accumulated smaller vector elements must be a multiple of the store size.
7932     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7933
7934     unsigned SizeRatio  = FromEltSz / ToEltSz;
7935     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7936
7937     // Create a type on which we perform the shuffle.
7938     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7939                                      NumElems*SizeRatio);
7940     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7941
7942     DebugLoc DL = St->getDebugLoc();
7943     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7944     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7945     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7946
7947     // Can't shuffle using an illegal type.
7948     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7949
7950     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7951                                 DAG.getUNDEF(WideVec.getValueType()),
7952                                 ShuffleVec.data());
7953     // At this point all of the data is stored at the bottom of the
7954     // register. We now need to save it to mem.
7955
7956     // Find the largest store unit
7957     MVT StoreType = MVT::i8;
7958     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7959          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7960       MVT Tp = (MVT::SimpleValueType)tp;
7961       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7962         StoreType = Tp;
7963     }
7964     // Didn't find a legal store type.
7965     if (!TLI.isTypeLegal(StoreType))
7966       return SDValue();
7967
7968     // Bitcast the original vector into a vector of store-size units
7969     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7970             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7971     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7972     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7973     SmallVector<SDValue, 8> Chains;
7974     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7975                                         TLI.getPointerTy());
7976     SDValue BasePtr = St->getBasePtr();
7977
7978     // Perform one or more big stores into memory.
7979     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7980     for (unsigned I = 0; I < E; I++) {
7981       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7982                                    StoreType, ShuffWide,
7983                                    DAG.getIntPtrConstant(I));
7984       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7985                                 St->getPointerInfo(), St->isVolatile(),
7986                                 St->isNonTemporal(), St->getAlignment());
7987       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7988                             Increment);
7989       Chains.push_back(Ch);
7990     }
7991     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7992                        Chains.size());
7993   }
7994
7995   if (!ISD::isNormalStore(St))
7996     return SDValue();
7997
7998   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7999   // ARM stores of arguments in the same cache line.
8000   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8001       StVal.getNode()->hasOneUse()) {
8002     SelectionDAG  &DAG = DCI.DAG;
8003     DebugLoc DL = St->getDebugLoc();
8004     SDValue BasePtr = St->getBasePtr();
8005     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8006                                   StVal.getNode()->getOperand(0), BasePtr,
8007                                   St->getPointerInfo(), St->isVolatile(),
8008                                   St->isNonTemporal(), St->getAlignment());
8009
8010     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8011                                     DAG.getConstant(4, MVT::i32));
8012     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8013                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8014                         St->isNonTemporal(),
8015                         std::min(4U, St->getAlignment() / 2));
8016   }
8017
8018   if (StVal.getValueType() != MVT::i64 ||
8019       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8020     return SDValue();
8021
8022   // Bitcast an i64 store extracted from a vector to f64.
8023   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8024   SelectionDAG &DAG = DCI.DAG;
8025   DebugLoc dl = StVal.getDebugLoc();
8026   SDValue IntVec = StVal.getOperand(0);
8027   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8028                                  IntVec.getValueType().getVectorNumElements());
8029   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8030   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8031                                Vec, StVal.getOperand(1));
8032   dl = N->getDebugLoc();
8033   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8034   // Make the DAGCombiner fold the bitcasts.
8035   DCI.AddToWorklist(Vec.getNode());
8036   DCI.AddToWorklist(ExtElt.getNode());
8037   DCI.AddToWorklist(V.getNode());
8038   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8039                       St->getPointerInfo(), St->isVolatile(),
8040                       St->isNonTemporal(), St->getAlignment(),
8041                       St->getTBAAInfo());
8042 }
8043
8044 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8045 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8046 /// i64 vector to have f64 elements, since the value can then be loaded
8047 /// directly into a VFP register.
8048 static bool hasNormalLoadOperand(SDNode *N) {
8049   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8050   for (unsigned i = 0; i < NumElts; ++i) {
8051     SDNode *Elt = N->getOperand(i).getNode();
8052     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8053       return true;
8054   }
8055   return false;
8056 }
8057
8058 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8059 /// ISD::BUILD_VECTOR.
8060 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8061                                           TargetLowering::DAGCombinerInfo &DCI){
8062   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8063   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8064   // into a pair of GPRs, which is fine when the value is used as a scalar,
8065   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8066   SelectionDAG &DAG = DCI.DAG;
8067   if (N->getNumOperands() == 2) {
8068     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8069     if (RV.getNode())
8070       return RV;
8071   }
8072
8073   // Load i64 elements as f64 values so that type legalization does not split
8074   // them up into i32 values.
8075   EVT VT = N->getValueType(0);
8076   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8077     return SDValue();
8078   DebugLoc dl = N->getDebugLoc();
8079   SmallVector<SDValue, 8> Ops;
8080   unsigned NumElts = VT.getVectorNumElements();
8081   for (unsigned i = 0; i < NumElts; ++i) {
8082     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8083     Ops.push_back(V);
8084     // Make the DAGCombiner fold the bitcast.
8085     DCI.AddToWorklist(V.getNode());
8086   }
8087   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8088   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8089   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8090 }
8091
8092 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8093 /// ISD::INSERT_VECTOR_ELT.
8094 static SDValue PerformInsertEltCombine(SDNode *N,
8095                                        TargetLowering::DAGCombinerInfo &DCI) {
8096   // Bitcast an i64 load inserted into a vector to f64.
8097   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8098   EVT VT = N->getValueType(0);
8099   SDNode *Elt = N->getOperand(1).getNode();
8100   if (VT.getVectorElementType() != MVT::i64 ||
8101       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8102     return SDValue();
8103
8104   SelectionDAG &DAG = DCI.DAG;
8105   DebugLoc dl = N->getDebugLoc();
8106   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8107                                  VT.getVectorNumElements());
8108   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8109   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8110   // Make the DAGCombiner fold the bitcasts.
8111   DCI.AddToWorklist(Vec.getNode());
8112   DCI.AddToWorklist(V.getNode());
8113   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8114                                Vec, V, N->getOperand(2));
8115   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8116 }
8117
8118 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8119 /// ISD::VECTOR_SHUFFLE.
8120 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8121   // The LLVM shufflevector instruction does not require the shuffle mask
8122   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8123   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8124   // operands do not match the mask length, they are extended by concatenating
8125   // them with undef vectors.  That is probably the right thing for other
8126   // targets, but for NEON it is better to concatenate two double-register
8127   // size vector operands into a single quad-register size vector.  Do that
8128   // transformation here:
8129   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8130   //   shuffle(concat(v1, v2), undef)
8131   SDValue Op0 = N->getOperand(0);
8132   SDValue Op1 = N->getOperand(1);
8133   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8134       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8135       Op0.getNumOperands() != 2 ||
8136       Op1.getNumOperands() != 2)
8137     return SDValue();
8138   SDValue Concat0Op1 = Op0.getOperand(1);
8139   SDValue Concat1Op1 = Op1.getOperand(1);
8140   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8141       Concat1Op1.getOpcode() != ISD::UNDEF)
8142     return SDValue();
8143   // Skip the transformation if any of the types are illegal.
8144   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8145   EVT VT = N->getValueType(0);
8146   if (!TLI.isTypeLegal(VT) ||
8147       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8148       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8149     return SDValue();
8150
8151   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8152                                   Op0.getOperand(0), Op1.getOperand(0));
8153   // Translate the shuffle mask.
8154   SmallVector<int, 16> NewMask;
8155   unsigned NumElts = VT.getVectorNumElements();
8156   unsigned HalfElts = NumElts/2;
8157   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8158   for (unsigned n = 0; n < NumElts; ++n) {
8159     int MaskElt = SVN->getMaskElt(n);
8160     int NewElt = -1;
8161     if (MaskElt < (int)HalfElts)
8162       NewElt = MaskElt;
8163     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8164       NewElt = HalfElts + MaskElt - NumElts;
8165     NewMask.push_back(NewElt);
8166   }
8167   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8168                               DAG.getUNDEF(VT), NewMask.data());
8169 }
8170
8171 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8172 /// NEON load/store intrinsics to merge base address updates.
8173 static SDValue CombineBaseUpdate(SDNode *N,
8174                                  TargetLowering::DAGCombinerInfo &DCI) {
8175   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8176     return SDValue();
8177
8178   SelectionDAG &DAG = DCI.DAG;
8179   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8180                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8181   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8182   SDValue Addr = N->getOperand(AddrOpIdx);
8183
8184   // Search for a use of the address operand that is an increment.
8185   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8186          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8187     SDNode *User = *UI;
8188     if (User->getOpcode() != ISD::ADD ||
8189         UI.getUse().getResNo() != Addr.getResNo())
8190       continue;
8191
8192     // Check that the add is independent of the load/store.  Otherwise, folding
8193     // it would create a cycle.
8194     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8195       continue;
8196
8197     // Find the new opcode for the updating load/store.
8198     bool isLoad = true;
8199     bool isLaneOp = false;
8200     unsigned NewOpc = 0;
8201     unsigned NumVecs = 0;
8202     if (isIntrinsic) {
8203       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8204       switch (IntNo) {
8205       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8206       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8207         NumVecs = 1; break;
8208       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8209         NumVecs = 2; break;
8210       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8211         NumVecs = 3; break;
8212       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8213         NumVecs = 4; break;
8214       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8215         NumVecs = 2; isLaneOp = true; break;
8216       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8217         NumVecs = 3; isLaneOp = true; break;
8218       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8219         NumVecs = 4; isLaneOp = true; break;
8220       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8221         NumVecs = 1; isLoad = false; break;
8222       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8223         NumVecs = 2; isLoad = false; break;
8224       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8225         NumVecs = 3; isLoad = false; break;
8226       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8227         NumVecs = 4; isLoad = false; break;
8228       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8229         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8230       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8231         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8232       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8233         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8234       }
8235     } else {
8236       isLaneOp = true;
8237       switch (N->getOpcode()) {
8238       default: llvm_unreachable("unexpected opcode for Neon base update");
8239       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8240       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8241       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8242       }
8243     }
8244
8245     // Find the size of memory referenced by the load/store.
8246     EVT VecTy;
8247     if (isLoad)
8248       VecTy = N->getValueType(0);
8249     else
8250       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8251     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8252     if (isLaneOp)
8253       NumBytes /= VecTy.getVectorNumElements();
8254
8255     // If the increment is a constant, it must match the memory ref size.
8256     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8257     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8258       uint64_t IncVal = CInc->getZExtValue();
8259       if (IncVal != NumBytes)
8260         continue;
8261     } else if (NumBytes >= 3 * 16) {
8262       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8263       // separate instructions that make it harder to use a non-constant update.
8264       continue;
8265     }
8266
8267     // Create the new updating load/store node.
8268     EVT Tys[6];
8269     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8270     unsigned n;
8271     for (n = 0; n < NumResultVecs; ++n)
8272       Tys[n] = VecTy;
8273     Tys[n++] = MVT::i32;
8274     Tys[n] = MVT::Other;
8275     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8276     SmallVector<SDValue, 8> Ops;
8277     Ops.push_back(N->getOperand(0)); // incoming chain
8278     Ops.push_back(N->getOperand(AddrOpIdx));
8279     Ops.push_back(Inc);
8280     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8281       Ops.push_back(N->getOperand(i));
8282     }
8283     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8284     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8285                                            Ops.data(), Ops.size(),
8286                                            MemInt->getMemoryVT(),
8287                                            MemInt->getMemOperand());
8288
8289     // Update the uses.
8290     std::vector<SDValue> NewResults;
8291     for (unsigned i = 0; i < NumResultVecs; ++i) {
8292       NewResults.push_back(SDValue(UpdN.getNode(), i));
8293     }
8294     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8295     DCI.CombineTo(N, NewResults);
8296     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8297
8298     break;
8299   }
8300   return SDValue();
8301 }
8302
8303 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8304 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8305 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8306 /// return true.
8307 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8308   SelectionDAG &DAG = DCI.DAG;
8309   EVT VT = N->getValueType(0);
8310   // vldN-dup instructions only support 64-bit vectors for N > 1.
8311   if (!VT.is64BitVector())
8312     return false;
8313
8314   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8315   SDNode *VLD = N->getOperand(0).getNode();
8316   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8317     return false;
8318   unsigned NumVecs = 0;
8319   unsigned NewOpc = 0;
8320   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8321   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8322     NumVecs = 2;
8323     NewOpc = ARMISD::VLD2DUP;
8324   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8325     NumVecs = 3;
8326     NewOpc = ARMISD::VLD3DUP;
8327   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8328     NumVecs = 4;
8329     NewOpc = ARMISD::VLD4DUP;
8330   } else {
8331     return false;
8332   }
8333
8334   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8335   // numbers match the load.
8336   unsigned VLDLaneNo =
8337     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8338   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8339        UI != UE; ++UI) {
8340     // Ignore uses of the chain result.
8341     if (UI.getUse().getResNo() == NumVecs)
8342       continue;
8343     SDNode *User = *UI;
8344     if (User->getOpcode() != ARMISD::VDUPLANE ||
8345         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8346       return false;
8347   }
8348
8349   // Create the vldN-dup node.
8350   EVT Tys[5];
8351   unsigned n;
8352   for (n = 0; n < NumVecs; ++n)
8353     Tys[n] = VT;
8354   Tys[n] = MVT::Other;
8355   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8356   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8357   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8358   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8359                                            Ops, 2, VLDMemInt->getMemoryVT(),
8360                                            VLDMemInt->getMemOperand());
8361
8362   // Update the uses.
8363   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8364        UI != UE; ++UI) {
8365     unsigned ResNo = UI.getUse().getResNo();
8366     // Ignore uses of the chain result.
8367     if (ResNo == NumVecs)
8368       continue;
8369     SDNode *User = *UI;
8370     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8371   }
8372
8373   // Now the vldN-lane intrinsic is dead except for its chain result.
8374   // Update uses of the chain.
8375   std::vector<SDValue> VLDDupResults;
8376   for (unsigned n = 0; n < NumVecs; ++n)
8377     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8378   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8379   DCI.CombineTo(VLD, VLDDupResults);
8380
8381   return true;
8382 }
8383
8384 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8385 /// ARMISD::VDUPLANE.
8386 static SDValue PerformVDUPLANECombine(SDNode *N,
8387                                       TargetLowering::DAGCombinerInfo &DCI) {
8388   SDValue Op = N->getOperand(0);
8389
8390   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8391   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8392   if (CombineVLDDUP(N, DCI))
8393     return SDValue(N, 0);
8394
8395   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8396   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8397   while (Op.getOpcode() == ISD::BITCAST)
8398     Op = Op.getOperand(0);
8399   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8400     return SDValue();
8401
8402   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8403   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8404   // The canonical VMOV for a zero vector uses a 32-bit element size.
8405   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8406   unsigned EltBits;
8407   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8408     EltSize = 8;
8409   EVT VT = N->getValueType(0);
8410   if (EltSize > VT.getVectorElementType().getSizeInBits())
8411     return SDValue();
8412
8413   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8414 }
8415
8416 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8417 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8418 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8419 {
8420   integerPart cN;
8421   integerPart c0 = 0;
8422   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8423        I != E; I++) {
8424     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8425     if (!C)
8426       return false;
8427
8428     bool isExact;
8429     APFloat APF = C->getValueAPF();
8430     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8431         != APFloat::opOK || !isExact)
8432       return false;
8433
8434     c0 = (I == 0) ? cN : c0;
8435     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8436       return false;
8437   }
8438   C = c0;
8439   return true;
8440 }
8441
8442 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8443 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8444 /// when the VMUL has a constant operand that is a power of 2.
8445 ///
8446 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8447 ///  vmul.f32        d16, d17, d16
8448 ///  vcvt.s32.f32    d16, d16
8449 /// becomes:
8450 ///  vcvt.s32.f32    d16, d16, #3
8451 static SDValue PerformVCVTCombine(SDNode *N,
8452                                   TargetLowering::DAGCombinerInfo &DCI,
8453                                   const ARMSubtarget *Subtarget) {
8454   SelectionDAG &DAG = DCI.DAG;
8455   SDValue Op = N->getOperand(0);
8456
8457   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8458       Op.getOpcode() != ISD::FMUL)
8459     return SDValue();
8460
8461   uint64_t C;
8462   SDValue N0 = Op->getOperand(0);
8463   SDValue ConstVec = Op->getOperand(1);
8464   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8465
8466   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8467       !isConstVecPow2(ConstVec, isSigned, C))
8468     return SDValue();
8469
8470   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8471     Intrinsic::arm_neon_vcvtfp2fxu;
8472   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8473                      N->getValueType(0),
8474                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8475                      DAG.getConstant(Log2_64(C), MVT::i32));
8476 }
8477
8478 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8479 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8480 /// when the VDIV has a constant operand that is a power of 2.
8481 ///
8482 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8483 ///  vcvt.f32.s32    d16, d16
8484 ///  vdiv.f32        d16, d17, d16
8485 /// becomes:
8486 ///  vcvt.f32.s32    d16, d16, #3
8487 static SDValue PerformVDIVCombine(SDNode *N,
8488                                   TargetLowering::DAGCombinerInfo &DCI,
8489                                   const ARMSubtarget *Subtarget) {
8490   SelectionDAG &DAG = DCI.DAG;
8491   SDValue Op = N->getOperand(0);
8492   unsigned OpOpcode = Op.getNode()->getOpcode();
8493
8494   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8495       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8496     return SDValue();
8497
8498   uint64_t C;
8499   SDValue ConstVec = N->getOperand(1);
8500   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8501
8502   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8503       !isConstVecPow2(ConstVec, isSigned, C))
8504     return SDValue();
8505
8506   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8507     Intrinsic::arm_neon_vcvtfxu2fp;
8508   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8509                      Op.getValueType(),
8510                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8511                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8512 }
8513
8514 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8515 /// operand of a vector shift operation, where all the elements of the
8516 /// build_vector must have the same constant integer value.
8517 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8518   // Ignore bit_converts.
8519   while (Op.getOpcode() == ISD::BITCAST)
8520     Op = Op.getOperand(0);
8521   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8522   APInt SplatBits, SplatUndef;
8523   unsigned SplatBitSize;
8524   bool HasAnyUndefs;
8525   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8526                                       HasAnyUndefs, ElementBits) ||
8527       SplatBitSize > ElementBits)
8528     return false;
8529   Cnt = SplatBits.getSExtValue();
8530   return true;
8531 }
8532
8533 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8534 /// operand of a vector shift left operation.  That value must be in the range:
8535 ///   0 <= Value < ElementBits for a left shift; or
8536 ///   0 <= Value <= ElementBits for a long left shift.
8537 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8538   assert(VT.isVector() && "vector shift count is not a vector type");
8539   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8540   if (! getVShiftImm(Op, ElementBits, Cnt))
8541     return false;
8542   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8543 }
8544
8545 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8546 /// operand of a vector shift right operation.  For a shift opcode, the value
8547 /// is positive, but for an intrinsic the value count must be negative. The
8548 /// absolute value must be in the range:
8549 ///   1 <= |Value| <= ElementBits for a right shift; or
8550 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8551 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8552                          int64_t &Cnt) {
8553   assert(VT.isVector() && "vector shift count is not a vector type");
8554   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8555   if (! getVShiftImm(Op, ElementBits, Cnt))
8556     return false;
8557   if (isIntrinsic)
8558     Cnt = -Cnt;
8559   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8560 }
8561
8562 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8563 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8564   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8565   switch (IntNo) {
8566   default:
8567     // Don't do anything for most intrinsics.
8568     break;
8569
8570   // Vector shifts: check for immediate versions and lower them.
8571   // Note: This is done during DAG combining instead of DAG legalizing because
8572   // the build_vectors for 64-bit vector element shift counts are generally
8573   // not legal, and it is hard to see their values after they get legalized to
8574   // loads from a constant pool.
8575   case Intrinsic::arm_neon_vshifts:
8576   case Intrinsic::arm_neon_vshiftu:
8577   case Intrinsic::arm_neon_vshiftls:
8578   case Intrinsic::arm_neon_vshiftlu:
8579   case Intrinsic::arm_neon_vshiftn:
8580   case Intrinsic::arm_neon_vrshifts:
8581   case Intrinsic::arm_neon_vrshiftu:
8582   case Intrinsic::arm_neon_vrshiftn:
8583   case Intrinsic::arm_neon_vqshifts:
8584   case Intrinsic::arm_neon_vqshiftu:
8585   case Intrinsic::arm_neon_vqshiftsu:
8586   case Intrinsic::arm_neon_vqshiftns:
8587   case Intrinsic::arm_neon_vqshiftnu:
8588   case Intrinsic::arm_neon_vqshiftnsu:
8589   case Intrinsic::arm_neon_vqrshiftns:
8590   case Intrinsic::arm_neon_vqrshiftnu:
8591   case Intrinsic::arm_neon_vqrshiftnsu: {
8592     EVT VT = N->getOperand(1).getValueType();
8593     int64_t Cnt;
8594     unsigned VShiftOpc = 0;
8595
8596     switch (IntNo) {
8597     case Intrinsic::arm_neon_vshifts:
8598     case Intrinsic::arm_neon_vshiftu:
8599       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8600         VShiftOpc = ARMISD::VSHL;
8601         break;
8602       }
8603       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8604         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8605                      ARMISD::VSHRs : ARMISD::VSHRu);
8606         break;
8607       }
8608       return SDValue();
8609
8610     case Intrinsic::arm_neon_vshiftls:
8611     case Intrinsic::arm_neon_vshiftlu:
8612       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8613         break;
8614       llvm_unreachable("invalid shift count for vshll intrinsic");
8615
8616     case Intrinsic::arm_neon_vrshifts:
8617     case Intrinsic::arm_neon_vrshiftu:
8618       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8619         break;
8620       return SDValue();
8621
8622     case Intrinsic::arm_neon_vqshifts:
8623     case Intrinsic::arm_neon_vqshiftu:
8624       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8625         break;
8626       return SDValue();
8627
8628     case Intrinsic::arm_neon_vqshiftsu:
8629       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8630         break;
8631       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8632
8633     case Intrinsic::arm_neon_vshiftn:
8634     case Intrinsic::arm_neon_vrshiftn:
8635     case Intrinsic::arm_neon_vqshiftns:
8636     case Intrinsic::arm_neon_vqshiftnu:
8637     case Intrinsic::arm_neon_vqshiftnsu:
8638     case Intrinsic::arm_neon_vqrshiftns:
8639     case Intrinsic::arm_neon_vqrshiftnu:
8640     case Intrinsic::arm_neon_vqrshiftnsu:
8641       // Narrowing shifts require an immediate right shift.
8642       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8643         break;
8644       llvm_unreachable("invalid shift count for narrowing vector shift "
8645                        "intrinsic");
8646
8647     default:
8648       llvm_unreachable("unhandled vector shift");
8649     }
8650
8651     switch (IntNo) {
8652     case Intrinsic::arm_neon_vshifts:
8653     case Intrinsic::arm_neon_vshiftu:
8654       // Opcode already set above.
8655       break;
8656     case Intrinsic::arm_neon_vshiftls:
8657     case Intrinsic::arm_neon_vshiftlu:
8658       if (Cnt == VT.getVectorElementType().getSizeInBits())
8659         VShiftOpc = ARMISD::VSHLLi;
8660       else
8661         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8662                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8663       break;
8664     case Intrinsic::arm_neon_vshiftn:
8665       VShiftOpc = ARMISD::VSHRN; break;
8666     case Intrinsic::arm_neon_vrshifts:
8667       VShiftOpc = ARMISD::VRSHRs; break;
8668     case Intrinsic::arm_neon_vrshiftu:
8669       VShiftOpc = ARMISD::VRSHRu; break;
8670     case Intrinsic::arm_neon_vrshiftn:
8671       VShiftOpc = ARMISD::VRSHRN; break;
8672     case Intrinsic::arm_neon_vqshifts:
8673       VShiftOpc = ARMISD::VQSHLs; break;
8674     case Intrinsic::arm_neon_vqshiftu:
8675       VShiftOpc = ARMISD::VQSHLu; break;
8676     case Intrinsic::arm_neon_vqshiftsu:
8677       VShiftOpc = ARMISD::VQSHLsu; break;
8678     case Intrinsic::arm_neon_vqshiftns:
8679       VShiftOpc = ARMISD::VQSHRNs; break;
8680     case Intrinsic::arm_neon_vqshiftnu:
8681       VShiftOpc = ARMISD::VQSHRNu; break;
8682     case Intrinsic::arm_neon_vqshiftnsu:
8683       VShiftOpc = ARMISD::VQSHRNsu; break;
8684     case Intrinsic::arm_neon_vqrshiftns:
8685       VShiftOpc = ARMISD::VQRSHRNs; break;
8686     case Intrinsic::arm_neon_vqrshiftnu:
8687       VShiftOpc = ARMISD::VQRSHRNu; break;
8688     case Intrinsic::arm_neon_vqrshiftnsu:
8689       VShiftOpc = ARMISD::VQRSHRNsu; break;
8690     }
8691
8692     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8693                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8694   }
8695
8696   case Intrinsic::arm_neon_vshiftins: {
8697     EVT VT = N->getOperand(1).getValueType();
8698     int64_t Cnt;
8699     unsigned VShiftOpc = 0;
8700
8701     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8702       VShiftOpc = ARMISD::VSLI;
8703     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8704       VShiftOpc = ARMISD::VSRI;
8705     else {
8706       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8707     }
8708
8709     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8710                        N->getOperand(1), N->getOperand(2),
8711                        DAG.getConstant(Cnt, MVT::i32));
8712   }
8713
8714   case Intrinsic::arm_neon_vqrshifts:
8715   case Intrinsic::arm_neon_vqrshiftu:
8716     // No immediate versions of these to check for.
8717     break;
8718   }
8719
8720   return SDValue();
8721 }
8722
8723 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8724 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8725 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8726 /// vector element shift counts are generally not legal, and it is hard to see
8727 /// their values after they get legalized to loads from a constant pool.
8728 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8729                                    const ARMSubtarget *ST) {
8730   EVT VT = N->getValueType(0);
8731   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8732     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8733     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8734     SDValue N1 = N->getOperand(1);
8735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8736       SDValue N0 = N->getOperand(0);
8737       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8738           DAG.MaskedValueIsZero(N0.getOperand(0),
8739                                 APInt::getHighBitsSet(32, 16)))
8740         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8741     }
8742   }
8743
8744   // Nothing to be done for scalar shifts.
8745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8746   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8747     return SDValue();
8748
8749   assert(ST->hasNEON() && "unexpected vector shift");
8750   int64_t Cnt;
8751
8752   switch (N->getOpcode()) {
8753   default: llvm_unreachable("unexpected shift opcode");
8754
8755   case ISD::SHL:
8756     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8757       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8758                          DAG.getConstant(Cnt, MVT::i32));
8759     break;
8760
8761   case ISD::SRA:
8762   case ISD::SRL:
8763     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8764       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8765                             ARMISD::VSHRs : ARMISD::VSHRu);
8766       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8767                          DAG.getConstant(Cnt, MVT::i32));
8768     }
8769   }
8770   return SDValue();
8771 }
8772
8773 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8774 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8775 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8776                                     const ARMSubtarget *ST) {
8777   SDValue N0 = N->getOperand(0);
8778
8779   // Check for sign- and zero-extensions of vector extract operations of 8-
8780   // and 16-bit vector elements.  NEON supports these directly.  They are
8781   // handled during DAG combining because type legalization will promote them
8782   // to 32-bit types and it is messy to recognize the operations after that.
8783   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8784     SDValue Vec = N0.getOperand(0);
8785     SDValue Lane = N0.getOperand(1);
8786     EVT VT = N->getValueType(0);
8787     EVT EltVT = N0.getValueType();
8788     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8789
8790     if (VT == MVT::i32 &&
8791         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8792         TLI.isTypeLegal(Vec.getValueType()) &&
8793         isa<ConstantSDNode>(Lane)) {
8794
8795       unsigned Opc = 0;
8796       switch (N->getOpcode()) {
8797       default: llvm_unreachable("unexpected opcode");
8798       case ISD::SIGN_EXTEND:
8799         Opc = ARMISD::VGETLANEs;
8800         break;
8801       case ISD::ZERO_EXTEND:
8802       case ISD::ANY_EXTEND:
8803         Opc = ARMISD::VGETLANEu;
8804         break;
8805       }
8806       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8807     }
8808   }
8809
8810   return SDValue();
8811 }
8812
8813 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8814 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8815 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8816                                        const ARMSubtarget *ST) {
8817   // If the target supports NEON, try to use vmax/vmin instructions for f32
8818   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8819   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8820   // a NaN; only do the transformation when it matches that behavior.
8821
8822   // For now only do this when using NEON for FP operations; if using VFP, it
8823   // is not obvious that the benefit outweighs the cost of switching to the
8824   // NEON pipeline.
8825   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8826       N->getValueType(0) != MVT::f32)
8827     return SDValue();
8828
8829   SDValue CondLHS = N->getOperand(0);
8830   SDValue CondRHS = N->getOperand(1);
8831   SDValue LHS = N->getOperand(2);
8832   SDValue RHS = N->getOperand(3);
8833   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8834
8835   unsigned Opcode = 0;
8836   bool IsReversed;
8837   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8838     IsReversed = false; // x CC y ? x : y
8839   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8840     IsReversed = true ; // x CC y ? y : x
8841   } else {
8842     return SDValue();
8843   }
8844
8845   bool IsUnordered;
8846   switch (CC) {
8847   default: break;
8848   case ISD::SETOLT:
8849   case ISD::SETOLE:
8850   case ISD::SETLT:
8851   case ISD::SETLE:
8852   case ISD::SETULT:
8853   case ISD::SETULE:
8854     // If LHS is NaN, an ordered comparison will be false and the result will
8855     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8856     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8857     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8858     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8859       break;
8860     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8861     // will return -0, so vmin can only be used for unsafe math or if one of
8862     // the operands is known to be nonzero.
8863     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8864         !DAG.getTarget().Options.UnsafeFPMath &&
8865         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8866       break;
8867     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8868     break;
8869
8870   case ISD::SETOGT:
8871   case ISD::SETOGE:
8872   case ISD::SETGT:
8873   case ISD::SETGE:
8874   case ISD::SETUGT:
8875   case ISD::SETUGE:
8876     // If LHS is NaN, an ordered comparison will be false and the result will
8877     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8878     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8879     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8880     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8881       break;
8882     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8883     // will return +0, so vmax can only be used for unsafe math or if one of
8884     // the operands is known to be nonzero.
8885     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8886         !DAG.getTarget().Options.UnsafeFPMath &&
8887         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8888       break;
8889     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8890     break;
8891   }
8892
8893   if (!Opcode)
8894     return SDValue();
8895   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8896 }
8897
8898 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8899 SDValue
8900 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8901   SDValue Cmp = N->getOperand(4);
8902   if (Cmp.getOpcode() != ARMISD::CMPZ)
8903     // Only looking at EQ and NE cases.
8904     return SDValue();
8905
8906   EVT VT = N->getValueType(0);
8907   DebugLoc dl = N->getDebugLoc();
8908   SDValue LHS = Cmp.getOperand(0);
8909   SDValue RHS = Cmp.getOperand(1);
8910   SDValue FalseVal = N->getOperand(0);
8911   SDValue TrueVal = N->getOperand(1);
8912   SDValue ARMcc = N->getOperand(2);
8913   ARMCC::CondCodes CC =
8914     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8915
8916   // Simplify
8917   //   mov     r1, r0
8918   //   cmp     r1, x
8919   //   mov     r0, y
8920   //   moveq   r0, x
8921   // to
8922   //   cmp     r0, x
8923   //   movne   r0, y
8924   //
8925   //   mov     r1, r0
8926   //   cmp     r1, x
8927   //   mov     r0, x
8928   //   movne   r0, y
8929   // to
8930   //   cmp     r0, x
8931   //   movne   r0, y
8932   /// FIXME: Turn this into a target neutral optimization?
8933   SDValue Res;
8934   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8935     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8936                       N->getOperand(3), Cmp);
8937   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8938     SDValue ARMcc;
8939     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8940     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8941                       N->getOperand(3), NewCmp);
8942   }
8943
8944   if (Res.getNode()) {
8945     APInt KnownZero, KnownOne;
8946     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8947     // Capture demanded bits information that would be otherwise lost.
8948     if (KnownZero == 0xfffffffe)
8949       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8950                         DAG.getValueType(MVT::i1));
8951     else if (KnownZero == 0xffffff00)
8952       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8953                         DAG.getValueType(MVT::i8));
8954     else if (KnownZero == 0xffff0000)
8955       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8956                         DAG.getValueType(MVT::i16));
8957   }
8958
8959   return Res;
8960 }
8961
8962 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8963                                              DAGCombinerInfo &DCI) const {
8964   switch (N->getOpcode()) {
8965   default: break;
8966   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
8967   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8968   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8969   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8970   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8971   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8972   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8973   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8974   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8975   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8976   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8977   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8978   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8979   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8980   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8981   case ISD::FP_TO_SINT:
8982   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8983   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8984   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8985   case ISD::SHL:
8986   case ISD::SRA:
8987   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8988   case ISD::SIGN_EXTEND:
8989   case ISD::ZERO_EXTEND:
8990   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8991   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8992   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8993   case ARMISD::VLD2DUP:
8994   case ARMISD::VLD3DUP:
8995   case ARMISD::VLD4DUP:
8996     return CombineBaseUpdate(N, DCI);
8997   case ISD::INTRINSIC_VOID:
8998   case ISD::INTRINSIC_W_CHAIN:
8999     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9000     case Intrinsic::arm_neon_vld1:
9001     case Intrinsic::arm_neon_vld2:
9002     case Intrinsic::arm_neon_vld3:
9003     case Intrinsic::arm_neon_vld4:
9004     case Intrinsic::arm_neon_vld2lane:
9005     case Intrinsic::arm_neon_vld3lane:
9006     case Intrinsic::arm_neon_vld4lane:
9007     case Intrinsic::arm_neon_vst1:
9008     case Intrinsic::arm_neon_vst2:
9009     case Intrinsic::arm_neon_vst3:
9010     case Intrinsic::arm_neon_vst4:
9011     case Intrinsic::arm_neon_vst2lane:
9012     case Intrinsic::arm_neon_vst3lane:
9013     case Intrinsic::arm_neon_vst4lane:
9014       return CombineBaseUpdate(N, DCI);
9015     default: break;
9016     }
9017     break;
9018   }
9019   return SDValue();
9020 }
9021
9022 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9023                                                           EVT VT) const {
9024   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9025 }
9026
9027 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9028   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9029   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9030
9031   switch (VT.getSimpleVT().SimpleTy) {
9032   default:
9033     return false;
9034   case MVT::i8:
9035   case MVT::i16:
9036   case MVT::i32:
9037     // Unaligned access can use (for example) LRDB, LRDH, LDR
9038     return AllowsUnaligned;
9039   case MVT::f64:
9040   case MVT::v2f64:
9041     // For any little-endian targets with neon, we can support unaligned ld/st
9042     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9043     // A big-endian target may also explictly support unaligned accesses
9044     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9045   }
9046 }
9047
9048 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9049                        unsigned AlignCheck) {
9050   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9051           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9052 }
9053
9054 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9055                                            unsigned DstAlign, unsigned SrcAlign,
9056                                            bool IsZeroVal,
9057                                            bool MemcpyStrSrc,
9058                                            MachineFunction &MF) const {
9059   const Function *F = MF.getFunction();
9060
9061   // See if we can use NEON instructions for this...
9062   if (IsZeroVal &&
9063       !F->getFnAttributes().hasNoImplicitFloatAttr() &&
9064       Subtarget->hasNEON()) {
9065     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9066       return MVT::v4i32;
9067     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9068       return MVT::v2i32;
9069     }
9070   }
9071
9072   // Lowering to i32/i16 if the size permits.
9073   if (Size >= 4) {
9074     return MVT::i32;
9075   } else if (Size >= 2) {
9076     return MVT::i16;
9077   }
9078
9079   // Let the target-independent logic figure it out.
9080   return MVT::Other;
9081 }
9082
9083 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9084   if (V < 0)
9085     return false;
9086
9087   unsigned Scale = 1;
9088   switch (VT.getSimpleVT().SimpleTy) {
9089   default: return false;
9090   case MVT::i1:
9091   case MVT::i8:
9092     // Scale == 1;
9093     break;
9094   case MVT::i16:
9095     // Scale == 2;
9096     Scale = 2;
9097     break;
9098   case MVT::i32:
9099     // Scale == 4;
9100     Scale = 4;
9101     break;
9102   }
9103
9104   if ((V & (Scale - 1)) != 0)
9105     return false;
9106   V /= Scale;
9107   return V == (V & ((1LL << 5) - 1));
9108 }
9109
9110 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9111                                       const ARMSubtarget *Subtarget) {
9112   bool isNeg = false;
9113   if (V < 0) {
9114     isNeg = true;
9115     V = - V;
9116   }
9117
9118   switch (VT.getSimpleVT().SimpleTy) {
9119   default: return false;
9120   case MVT::i1:
9121   case MVT::i8:
9122   case MVT::i16:
9123   case MVT::i32:
9124     // + imm12 or - imm8
9125     if (isNeg)
9126       return V == (V & ((1LL << 8) - 1));
9127     return V == (V & ((1LL << 12) - 1));
9128   case MVT::f32:
9129   case MVT::f64:
9130     // Same as ARM mode. FIXME: NEON?
9131     if (!Subtarget->hasVFP2())
9132       return false;
9133     if ((V & 3) != 0)
9134       return false;
9135     V >>= 2;
9136     return V == (V & ((1LL << 8) - 1));
9137   }
9138 }
9139
9140 /// isLegalAddressImmediate - Return true if the integer value can be used
9141 /// as the offset of the target addressing mode for load / store of the
9142 /// given type.
9143 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9144                                     const ARMSubtarget *Subtarget) {
9145   if (V == 0)
9146     return true;
9147
9148   if (!VT.isSimple())
9149     return false;
9150
9151   if (Subtarget->isThumb1Only())
9152     return isLegalT1AddressImmediate(V, VT);
9153   else if (Subtarget->isThumb2())
9154     return isLegalT2AddressImmediate(V, VT, Subtarget);
9155
9156   // ARM mode.
9157   if (V < 0)
9158     V = - V;
9159   switch (VT.getSimpleVT().SimpleTy) {
9160   default: return false;
9161   case MVT::i1:
9162   case MVT::i8:
9163   case MVT::i32:
9164     // +- imm12
9165     return V == (V & ((1LL << 12) - 1));
9166   case MVT::i16:
9167     // +- imm8
9168     return V == (V & ((1LL << 8) - 1));
9169   case MVT::f32:
9170   case MVT::f64:
9171     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9172       return false;
9173     if ((V & 3) != 0)
9174       return false;
9175     V >>= 2;
9176     return V == (V & ((1LL << 8) - 1));
9177   }
9178 }
9179
9180 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9181                                                       EVT VT) const {
9182   int Scale = AM.Scale;
9183   if (Scale < 0)
9184     return false;
9185
9186   switch (VT.getSimpleVT().SimpleTy) {
9187   default: return false;
9188   case MVT::i1:
9189   case MVT::i8:
9190   case MVT::i16:
9191   case MVT::i32:
9192     if (Scale == 1)
9193       return true;
9194     // r + r << imm
9195     Scale = Scale & ~1;
9196     return Scale == 2 || Scale == 4 || Scale == 8;
9197   case MVT::i64:
9198     // r + r
9199     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9200       return true;
9201     return false;
9202   case MVT::isVoid:
9203     // Note, we allow "void" uses (basically, uses that aren't loads or
9204     // stores), because arm allows folding a scale into many arithmetic
9205     // operations.  This should be made more precise and revisited later.
9206
9207     // Allow r << imm, but the imm has to be a multiple of two.
9208     if (Scale & 1) return false;
9209     return isPowerOf2_32(Scale);
9210   }
9211 }
9212
9213 /// isLegalAddressingMode - Return true if the addressing mode represented
9214 /// by AM is legal for this target, for a load/store of the specified type.
9215 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9216                                               Type *Ty) const {
9217   EVT VT = getValueType(Ty, true);
9218   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9219     return false;
9220
9221   // Can never fold addr of global into load/store.
9222   if (AM.BaseGV)
9223     return false;
9224
9225   switch (AM.Scale) {
9226   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9227     break;
9228   case 1:
9229     if (Subtarget->isThumb1Only())
9230       return false;
9231     // FALL THROUGH.
9232   default:
9233     // ARM doesn't support any R+R*scale+imm addr modes.
9234     if (AM.BaseOffs)
9235       return false;
9236
9237     if (!VT.isSimple())
9238       return false;
9239
9240     if (Subtarget->isThumb2())
9241       return isLegalT2ScaledAddressingMode(AM, VT);
9242
9243     int Scale = AM.Scale;
9244     switch (VT.getSimpleVT().SimpleTy) {
9245     default: return false;
9246     case MVT::i1:
9247     case MVT::i8:
9248     case MVT::i32:
9249       if (Scale < 0) Scale = -Scale;
9250       if (Scale == 1)
9251         return true;
9252       // r + r << imm
9253       return isPowerOf2_32(Scale & ~1);
9254     case MVT::i16:
9255     case MVT::i64:
9256       // r + r
9257       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9258         return true;
9259       return false;
9260
9261     case MVT::isVoid:
9262       // Note, we allow "void" uses (basically, uses that aren't loads or
9263       // stores), because arm allows folding a scale into many arithmetic
9264       // operations.  This should be made more precise and revisited later.
9265
9266       // Allow r << imm, but the imm has to be a multiple of two.
9267       if (Scale & 1) return false;
9268       return isPowerOf2_32(Scale);
9269     }
9270   }
9271   return true;
9272 }
9273
9274 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9275 /// icmp immediate, that is the target has icmp instructions which can compare
9276 /// a register against the immediate without having to materialize the
9277 /// immediate into a register.
9278 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9279   // Thumb2 and ARM modes can use cmn for negative immediates.
9280   if (!Subtarget->isThumb())
9281     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9282   if (Subtarget->isThumb2())
9283     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9284   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9285   return Imm >= 0 && Imm <= 255;
9286 }
9287
9288 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9289 /// *or sub* immediate, that is the target has add or sub instructions which can
9290 /// add a register with the immediate without having to materialize the
9291 /// immediate into a register.
9292 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9293   // Same encoding for add/sub, just flip the sign.
9294   int64_t AbsImm = llvm::abs64(Imm);
9295   if (!Subtarget->isThumb())
9296     return ARM_AM::getSOImmVal(AbsImm) != -1;
9297   if (Subtarget->isThumb2())
9298     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9299   // Thumb1 only has 8-bit unsigned immediate.
9300   return AbsImm >= 0 && AbsImm <= 255;
9301 }
9302
9303 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9304                                       bool isSEXTLoad, SDValue &Base,
9305                                       SDValue &Offset, bool &isInc,
9306                                       SelectionDAG &DAG) {
9307   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9308     return false;
9309
9310   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9311     // AddressingMode 3
9312     Base = Ptr->getOperand(0);
9313     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9314       int RHSC = (int)RHS->getZExtValue();
9315       if (RHSC < 0 && RHSC > -256) {
9316         assert(Ptr->getOpcode() == ISD::ADD);
9317         isInc = false;
9318         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9319         return true;
9320       }
9321     }
9322     isInc = (Ptr->getOpcode() == ISD::ADD);
9323     Offset = Ptr->getOperand(1);
9324     return true;
9325   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9326     // AddressingMode 2
9327     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9328       int RHSC = (int)RHS->getZExtValue();
9329       if (RHSC < 0 && RHSC > -0x1000) {
9330         assert(Ptr->getOpcode() == ISD::ADD);
9331         isInc = false;
9332         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9333         Base = Ptr->getOperand(0);
9334         return true;
9335       }
9336     }
9337
9338     if (Ptr->getOpcode() == ISD::ADD) {
9339       isInc = true;
9340       ARM_AM::ShiftOpc ShOpcVal=
9341         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9342       if (ShOpcVal != ARM_AM::no_shift) {
9343         Base = Ptr->getOperand(1);
9344         Offset = Ptr->getOperand(0);
9345       } else {
9346         Base = Ptr->getOperand(0);
9347         Offset = Ptr->getOperand(1);
9348       }
9349       return true;
9350     }
9351
9352     isInc = (Ptr->getOpcode() == ISD::ADD);
9353     Base = Ptr->getOperand(0);
9354     Offset = Ptr->getOperand(1);
9355     return true;
9356   }
9357
9358   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9359   return false;
9360 }
9361
9362 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9363                                      bool isSEXTLoad, SDValue &Base,
9364                                      SDValue &Offset, bool &isInc,
9365                                      SelectionDAG &DAG) {
9366   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9367     return false;
9368
9369   Base = Ptr->getOperand(0);
9370   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9371     int RHSC = (int)RHS->getZExtValue();
9372     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9373       assert(Ptr->getOpcode() == ISD::ADD);
9374       isInc = false;
9375       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9376       return true;
9377     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9378       isInc = Ptr->getOpcode() == ISD::ADD;
9379       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9380       return true;
9381     }
9382   }
9383
9384   return false;
9385 }
9386
9387 /// getPreIndexedAddressParts - returns true by value, base pointer and
9388 /// offset pointer and addressing mode by reference if the node's address
9389 /// can be legally represented as pre-indexed load / store address.
9390 bool
9391 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9392                                              SDValue &Offset,
9393                                              ISD::MemIndexedMode &AM,
9394                                              SelectionDAG &DAG) const {
9395   if (Subtarget->isThumb1Only())
9396     return false;
9397
9398   EVT VT;
9399   SDValue Ptr;
9400   bool isSEXTLoad = false;
9401   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9402     Ptr = LD->getBasePtr();
9403     VT  = LD->getMemoryVT();
9404     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9405   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9406     Ptr = ST->getBasePtr();
9407     VT  = ST->getMemoryVT();
9408   } else
9409     return false;
9410
9411   bool isInc;
9412   bool isLegal = false;
9413   if (Subtarget->isThumb2())
9414     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9415                                        Offset, isInc, DAG);
9416   else
9417     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9418                                         Offset, isInc, DAG);
9419   if (!isLegal)
9420     return false;
9421
9422   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9423   return true;
9424 }
9425
9426 /// getPostIndexedAddressParts - returns true by value, base pointer and
9427 /// offset pointer and addressing mode by reference if this node can be
9428 /// combined with a load / store to form a post-indexed load / store.
9429 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9430                                                    SDValue &Base,
9431                                                    SDValue &Offset,
9432                                                    ISD::MemIndexedMode &AM,
9433                                                    SelectionDAG &DAG) const {
9434   if (Subtarget->isThumb1Only())
9435     return false;
9436
9437   EVT VT;
9438   SDValue Ptr;
9439   bool isSEXTLoad = false;
9440   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9441     VT  = LD->getMemoryVT();
9442     Ptr = LD->getBasePtr();
9443     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9444   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9445     VT  = ST->getMemoryVT();
9446     Ptr = ST->getBasePtr();
9447   } else
9448     return false;
9449
9450   bool isInc;
9451   bool isLegal = false;
9452   if (Subtarget->isThumb2())
9453     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9454                                        isInc, DAG);
9455   else
9456     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9457                                         isInc, DAG);
9458   if (!isLegal)
9459     return false;
9460
9461   if (Ptr != Base) {
9462     // Swap base ptr and offset to catch more post-index load / store when
9463     // it's legal. In Thumb2 mode, offset must be an immediate.
9464     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9465         !Subtarget->isThumb2())
9466       std::swap(Base, Offset);
9467
9468     // Post-indexed load / store update the base pointer.
9469     if (Ptr != Base)
9470       return false;
9471   }
9472
9473   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9474   return true;
9475 }
9476
9477 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9478                                                        APInt &KnownZero,
9479                                                        APInt &KnownOne,
9480                                                        const SelectionDAG &DAG,
9481                                                        unsigned Depth) const {
9482   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9483   switch (Op.getOpcode()) {
9484   default: break;
9485   case ARMISD::CMOV: {
9486     // Bits are known zero/one if known on the LHS and RHS.
9487     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9488     if (KnownZero == 0 && KnownOne == 0) return;
9489
9490     APInt KnownZeroRHS, KnownOneRHS;
9491     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9492     KnownZero &= KnownZeroRHS;
9493     KnownOne  &= KnownOneRHS;
9494     return;
9495   }
9496   }
9497 }
9498
9499 //===----------------------------------------------------------------------===//
9500 //                           ARM Inline Assembly Support
9501 //===----------------------------------------------------------------------===//
9502
9503 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9504   // Looking for "rev" which is V6+.
9505   if (!Subtarget->hasV6Ops())
9506     return false;
9507
9508   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9509   std::string AsmStr = IA->getAsmString();
9510   SmallVector<StringRef, 4> AsmPieces;
9511   SplitString(AsmStr, AsmPieces, ";\n");
9512
9513   switch (AsmPieces.size()) {
9514   default: return false;
9515   case 1:
9516     AsmStr = AsmPieces[0];
9517     AsmPieces.clear();
9518     SplitString(AsmStr, AsmPieces, " \t,");
9519
9520     // rev $0, $1
9521     if (AsmPieces.size() == 3 &&
9522         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9523         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9524       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9525       if (Ty && Ty->getBitWidth() == 32)
9526         return IntrinsicLowering::LowerToByteSwap(CI);
9527     }
9528     break;
9529   }
9530
9531   return false;
9532 }
9533
9534 /// getConstraintType - Given a constraint letter, return the type of
9535 /// constraint it is for this target.
9536 ARMTargetLowering::ConstraintType
9537 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9538   if (Constraint.size() == 1) {
9539     switch (Constraint[0]) {
9540     default:  break;
9541     case 'l': return C_RegisterClass;
9542     case 'w': return C_RegisterClass;
9543     case 'h': return C_RegisterClass;
9544     case 'x': return C_RegisterClass;
9545     case 't': return C_RegisterClass;
9546     case 'j': return C_Other; // Constant for movw.
9547       // An address with a single base register. Due to the way we
9548       // currently handle addresses it is the same as an 'r' memory constraint.
9549     case 'Q': return C_Memory;
9550     }
9551   } else if (Constraint.size() == 2) {
9552     switch (Constraint[0]) {
9553     default: break;
9554     // All 'U+' constraints are addresses.
9555     case 'U': return C_Memory;
9556     }
9557   }
9558   return TargetLowering::getConstraintType(Constraint);
9559 }
9560
9561 /// Examine constraint type and operand type and determine a weight value.
9562 /// This object must already have been set up with the operand type
9563 /// and the current alternative constraint selected.
9564 TargetLowering::ConstraintWeight
9565 ARMTargetLowering::getSingleConstraintMatchWeight(
9566     AsmOperandInfo &info, const char *constraint) const {
9567   ConstraintWeight weight = CW_Invalid;
9568   Value *CallOperandVal = info.CallOperandVal;
9569     // If we don't have a value, we can't do a match,
9570     // but allow it at the lowest weight.
9571   if (CallOperandVal == NULL)
9572     return CW_Default;
9573   Type *type = CallOperandVal->getType();
9574   // Look at the constraint type.
9575   switch (*constraint) {
9576   default:
9577     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9578     break;
9579   case 'l':
9580     if (type->isIntegerTy()) {
9581       if (Subtarget->isThumb())
9582         weight = CW_SpecificReg;
9583       else
9584         weight = CW_Register;
9585     }
9586     break;
9587   case 'w':
9588     if (type->isFloatingPointTy())
9589       weight = CW_Register;
9590     break;
9591   }
9592   return weight;
9593 }
9594
9595 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9596 RCPair
9597 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9598                                                 EVT VT) const {
9599   if (Constraint.size() == 1) {
9600     // GCC ARM Constraint Letters
9601     switch (Constraint[0]) {
9602     case 'l': // Low regs or general regs.
9603       if (Subtarget->isThumb())
9604         return RCPair(0U, &ARM::tGPRRegClass);
9605       return RCPair(0U, &ARM::GPRRegClass);
9606     case 'h': // High regs or no regs.
9607       if (Subtarget->isThumb())
9608         return RCPair(0U, &ARM::hGPRRegClass);
9609       break;
9610     case 'r':
9611       return RCPair(0U, &ARM::GPRRegClass);
9612     case 'w':
9613       if (VT == MVT::f32)
9614         return RCPair(0U, &ARM::SPRRegClass);
9615       if (VT.getSizeInBits() == 64)
9616         return RCPair(0U, &ARM::DPRRegClass);
9617       if (VT.getSizeInBits() == 128)
9618         return RCPair(0U, &ARM::QPRRegClass);
9619       break;
9620     case 'x':
9621       if (VT == MVT::f32)
9622         return RCPair(0U, &ARM::SPR_8RegClass);
9623       if (VT.getSizeInBits() == 64)
9624         return RCPair(0U, &ARM::DPR_8RegClass);
9625       if (VT.getSizeInBits() == 128)
9626         return RCPair(0U, &ARM::QPR_8RegClass);
9627       break;
9628     case 't':
9629       if (VT == MVT::f32)
9630         return RCPair(0U, &ARM::SPRRegClass);
9631       break;
9632     }
9633   }
9634   if (StringRef("{cc}").equals_lower(Constraint))
9635     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9636
9637   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9638 }
9639
9640 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9641 /// vector.  If it is invalid, don't add anything to Ops.
9642 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9643                                                      std::string &Constraint,
9644                                                      std::vector<SDValue>&Ops,
9645                                                      SelectionDAG &DAG) const {
9646   SDValue Result(0, 0);
9647
9648   // Currently only support length 1 constraints.
9649   if (Constraint.length() != 1) return;
9650
9651   char ConstraintLetter = Constraint[0];
9652   switch (ConstraintLetter) {
9653   default: break;
9654   case 'j':
9655   case 'I': case 'J': case 'K': case 'L':
9656   case 'M': case 'N': case 'O':
9657     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9658     if (!C)
9659       return;
9660
9661     int64_t CVal64 = C->getSExtValue();
9662     int CVal = (int) CVal64;
9663     // None of these constraints allow values larger than 32 bits.  Check
9664     // that the value fits in an int.
9665     if (CVal != CVal64)
9666       return;
9667
9668     switch (ConstraintLetter) {
9669       case 'j':
9670         // Constant suitable for movw, must be between 0 and
9671         // 65535.
9672         if (Subtarget->hasV6T2Ops())
9673           if (CVal >= 0 && CVal <= 65535)
9674             break;
9675         return;
9676       case 'I':
9677         if (Subtarget->isThumb1Only()) {
9678           // This must be a constant between 0 and 255, for ADD
9679           // immediates.
9680           if (CVal >= 0 && CVal <= 255)
9681             break;
9682         } else if (Subtarget->isThumb2()) {
9683           // A constant that can be used as an immediate value in a
9684           // data-processing instruction.
9685           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9686             break;
9687         } else {
9688           // A constant that can be used as an immediate value in a
9689           // data-processing instruction.
9690           if (ARM_AM::getSOImmVal(CVal) != -1)
9691             break;
9692         }
9693         return;
9694
9695       case 'J':
9696         if (Subtarget->isThumb()) {  // FIXME thumb2
9697           // This must be a constant between -255 and -1, for negated ADD
9698           // immediates. This can be used in GCC with an "n" modifier that
9699           // prints the negated value, for use with SUB instructions. It is
9700           // not useful otherwise but is implemented for compatibility.
9701           if (CVal >= -255 && CVal <= -1)
9702             break;
9703         } else {
9704           // This must be a constant between -4095 and 4095. It is not clear
9705           // what this constraint is intended for. Implemented for
9706           // compatibility with GCC.
9707           if (CVal >= -4095 && CVal <= 4095)
9708             break;
9709         }
9710         return;
9711
9712       case 'K':
9713         if (Subtarget->isThumb1Only()) {
9714           // A 32-bit value where only one byte has a nonzero value. Exclude
9715           // zero to match GCC. This constraint is used by GCC internally for
9716           // constants that can be loaded with a move/shift combination.
9717           // It is not useful otherwise but is implemented for compatibility.
9718           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9719             break;
9720         } else if (Subtarget->isThumb2()) {
9721           // A constant whose bitwise inverse can be used as an immediate
9722           // value in a data-processing instruction. This can be used in GCC
9723           // with a "B" modifier that prints the inverted value, for use with
9724           // BIC and MVN instructions. It is not useful otherwise but is
9725           // implemented for compatibility.
9726           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9727             break;
9728         } else {
9729           // A constant whose bitwise inverse can be used as an immediate
9730           // value in a data-processing instruction. This can be used in GCC
9731           // with a "B" modifier that prints the inverted value, for use with
9732           // BIC and MVN instructions. It is not useful otherwise but is
9733           // implemented for compatibility.
9734           if (ARM_AM::getSOImmVal(~CVal) != -1)
9735             break;
9736         }
9737         return;
9738
9739       case 'L':
9740         if (Subtarget->isThumb1Only()) {
9741           // This must be a constant between -7 and 7,
9742           // for 3-operand ADD/SUB immediate instructions.
9743           if (CVal >= -7 && CVal < 7)
9744             break;
9745         } else if (Subtarget->isThumb2()) {
9746           // A constant whose negation can be used as an immediate value in a
9747           // data-processing instruction. This can be used in GCC with an "n"
9748           // modifier that prints the negated value, for use with SUB
9749           // instructions. It is not useful otherwise but is implemented for
9750           // compatibility.
9751           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9752             break;
9753         } else {
9754           // A constant whose negation can be used as an immediate value in a
9755           // data-processing instruction. This can be used in GCC with an "n"
9756           // modifier that prints the negated value, for use with SUB
9757           // instructions. It is not useful otherwise but is implemented for
9758           // compatibility.
9759           if (ARM_AM::getSOImmVal(-CVal) != -1)
9760             break;
9761         }
9762         return;
9763
9764       case 'M':
9765         if (Subtarget->isThumb()) { // FIXME thumb2
9766           // This must be a multiple of 4 between 0 and 1020, for
9767           // ADD sp + immediate.
9768           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9769             break;
9770         } else {
9771           // A power of two or a constant between 0 and 32.  This is used in
9772           // GCC for the shift amount on shifted register operands, but it is
9773           // useful in general for any shift amounts.
9774           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9775             break;
9776         }
9777         return;
9778
9779       case 'N':
9780         if (Subtarget->isThumb()) {  // FIXME thumb2
9781           // This must be a constant between 0 and 31, for shift amounts.
9782           if (CVal >= 0 && CVal <= 31)
9783             break;
9784         }
9785         return;
9786
9787       case 'O':
9788         if (Subtarget->isThumb()) {  // FIXME thumb2
9789           // This must be a multiple of 4 between -508 and 508, for
9790           // ADD/SUB sp = sp + immediate.
9791           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9792             break;
9793         }
9794         return;
9795     }
9796     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9797     break;
9798   }
9799
9800   if (Result.getNode()) {
9801     Ops.push_back(Result);
9802     return;
9803   }
9804   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9805 }
9806
9807 bool
9808 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9809   // The ARM target isn't yet aware of offsets.
9810   return false;
9811 }
9812
9813 bool ARM::isBitFieldInvertedMask(unsigned v) {
9814   if (v == 0xffffffff)
9815     return 0;
9816   // there can be 1's on either or both "outsides", all the "inside"
9817   // bits must be 0's
9818   unsigned int lsb = 0, msb = 31;
9819   while (v & (1 << msb)) --msb;
9820   while (v & (1 << lsb)) ++lsb;
9821   for (unsigned int i = lsb; i <= msb; ++i) {
9822     if (v & (1 << i))
9823       return 0;
9824   }
9825   return 1;
9826 }
9827
9828 /// isFPImmLegal - Returns true if the target can instruction select the
9829 /// specified FP immediate natively. If false, the legalizer will
9830 /// materialize the FP immediate as a load from a constant pool.
9831 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9832   if (!Subtarget->hasVFP3())
9833     return false;
9834   if (VT == MVT::f32)
9835     return ARM_AM::getFP32Imm(Imm) != -1;
9836   if (VT == MVT::f64)
9837     return ARM_AM::getFP64Imm(Imm) != -1;
9838   return false;
9839 }
9840
9841 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9842 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9843 /// specified in the intrinsic calls.
9844 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9845                                            const CallInst &I,
9846                                            unsigned Intrinsic) const {
9847   switch (Intrinsic) {
9848   case Intrinsic::arm_neon_vld1:
9849   case Intrinsic::arm_neon_vld2:
9850   case Intrinsic::arm_neon_vld3:
9851   case Intrinsic::arm_neon_vld4:
9852   case Intrinsic::arm_neon_vld2lane:
9853   case Intrinsic::arm_neon_vld3lane:
9854   case Intrinsic::arm_neon_vld4lane: {
9855     Info.opc = ISD::INTRINSIC_W_CHAIN;
9856     // Conservatively set memVT to the entire set of vectors loaded.
9857     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9858     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9859     Info.ptrVal = I.getArgOperand(0);
9860     Info.offset = 0;
9861     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9862     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9863     Info.vol = false; // volatile loads with NEON intrinsics not supported
9864     Info.readMem = true;
9865     Info.writeMem = false;
9866     return true;
9867   }
9868   case Intrinsic::arm_neon_vst1:
9869   case Intrinsic::arm_neon_vst2:
9870   case Intrinsic::arm_neon_vst3:
9871   case Intrinsic::arm_neon_vst4:
9872   case Intrinsic::arm_neon_vst2lane:
9873   case Intrinsic::arm_neon_vst3lane:
9874   case Intrinsic::arm_neon_vst4lane: {
9875     Info.opc = ISD::INTRINSIC_VOID;
9876     // Conservatively set memVT to the entire set of vectors stored.
9877     unsigned NumElts = 0;
9878     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9879       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9880       if (!ArgTy->isVectorTy())
9881         break;
9882       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9883     }
9884     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9885     Info.ptrVal = I.getArgOperand(0);
9886     Info.offset = 0;
9887     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9888     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9889     Info.vol = false; // volatile stores with NEON intrinsics not supported
9890     Info.readMem = false;
9891     Info.writeMem = true;
9892     return true;
9893   }
9894   case Intrinsic::arm_strexd: {
9895     Info.opc = ISD::INTRINSIC_W_CHAIN;
9896     Info.memVT = MVT::i64;
9897     Info.ptrVal = I.getArgOperand(2);
9898     Info.offset = 0;
9899     Info.align = 8;
9900     Info.vol = true;
9901     Info.readMem = false;
9902     Info.writeMem = true;
9903     return true;
9904   }
9905   case Intrinsic::arm_ldrexd: {
9906     Info.opc = ISD::INTRINSIC_W_CHAIN;
9907     Info.memVT = MVT::i64;
9908     Info.ptrVal = I.getArgOperand(0);
9909     Info.offset = 0;
9910     Info.align = 8;
9911     Info.vol = true;
9912     Info.readMem = true;
9913     Info.writeMem = false;
9914     return true;
9915   }
9916   default:
9917     break;
9918   }
9919
9920   return false;
9921 }