Disable the Thumb no-return call optimization:
[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::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507
508     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
509     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
510     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
519
520     // Neon does not support some operations on v1i64 and v2i64 types.
521     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
522     // Custom handling for some quad-vector types to detect VMULL.
523     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
524     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
525     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
526     // Custom handling for some vector types to avoid expensive expansions
527     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
528     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
529     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
532     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
533     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
534     // a destination type that is wider than the source, and nor does
535     // it have a FP_TO_[SU]INT instruction with a narrower destination than
536     // source.
537     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
538     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
539     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
540     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
541
542     setTargetDAGCombine(ISD::INTRINSIC_VOID);
543     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
544     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
545     setTargetDAGCombine(ISD::SHL);
546     setTargetDAGCombine(ISD::SRL);
547     setTargetDAGCombine(ISD::SRA);
548     setTargetDAGCombine(ISD::SIGN_EXTEND);
549     setTargetDAGCombine(ISD::ZERO_EXTEND);
550     setTargetDAGCombine(ISD::ANY_EXTEND);
551     setTargetDAGCombine(ISD::SELECT_CC);
552     setTargetDAGCombine(ISD::BUILD_VECTOR);
553     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
554     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
555     setTargetDAGCombine(ISD::STORE);
556     setTargetDAGCombine(ISD::FP_TO_SINT);
557     setTargetDAGCombine(ISD::FP_TO_UINT);
558     setTargetDAGCombine(ISD::FDIV);
559
560     // It is legal to extload from v4i8 to v4i16 or v4i32.
561     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
562                   MVT::v4i16, MVT::v2i16,
563                   MVT::v2i32};
564     for (unsigned i = 0; i < 6; ++i) {
565       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
566       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
567       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
568     }
569   }
570
571   // ARM and Thumb2 support UMLAL/SMLAL.
572   if (!Subtarget->isThumb1Only())
573     setTargetDAGCombine(ISD::ADDC);
574
575
576   computeRegisterProperties();
577
578   // ARM does not have f32 extending load.
579   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
580
581   // ARM does not have i1 sign extending load.
582   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
583
584   // ARM supports all 4 flavors of integer indexed load / store.
585   if (!Subtarget->isThumb1Only()) {
586     for (unsigned im = (unsigned)ISD::PRE_INC;
587          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
588       setIndexedLoadAction(im,  MVT::i1,  Legal);
589       setIndexedLoadAction(im,  MVT::i8,  Legal);
590       setIndexedLoadAction(im,  MVT::i16, Legal);
591       setIndexedLoadAction(im,  MVT::i32, Legal);
592       setIndexedStoreAction(im, MVT::i1,  Legal);
593       setIndexedStoreAction(im, MVT::i8,  Legal);
594       setIndexedStoreAction(im, MVT::i16, Legal);
595       setIndexedStoreAction(im, MVT::i32, Legal);
596     }
597   }
598
599   // i64 operation support.
600   setOperationAction(ISD::MUL,     MVT::i64, Expand);
601   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
602   if (Subtarget->isThumb1Only()) {
603     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
604     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
605   }
606   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
607       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
608     setOperationAction(ISD::MULHS, MVT::i32, Expand);
609
610   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
611   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
612   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
613   setOperationAction(ISD::SRL,       MVT::i64, Custom);
614   setOperationAction(ISD::SRA,       MVT::i64, Custom);
615
616   if (!Subtarget->isThumb1Only()) {
617     // FIXME: We should do this for Thumb1 as well.
618     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
619     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
620     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
621     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
622   }
623
624   // ARM does not have ROTL.
625   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
626   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
627   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
628   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
629     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
630
631   // These just redirect to CTTZ and CTLZ on ARM.
632   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
633   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
634
635   // Only ARMv6 has BSWAP.
636   if (!Subtarget->hasV6Ops())
637     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
638
639   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
640       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
641     // These are expanded into libcalls if the cpu doesn't have HW divider.
642     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
643     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
644   }
645   setOperationAction(ISD::SREM,  MVT::i32, Expand);
646   setOperationAction(ISD::UREM,  MVT::i32, Expand);
647   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
648   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
649
650   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
651   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
652   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
653   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
654   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
655
656   setOperationAction(ISD::TRAP, MVT::Other, Legal);
657
658   // Use the default implementation.
659   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
660   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
661   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
662   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
663   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
664   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
665
666   if (!Subtarget->isTargetDarwin()) {
667     // Non-Darwin platforms may return values in these registers via the
668     // personality function.
669     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
670     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
671     setExceptionPointerRegister(ARM::R0);
672     setExceptionSelectorRegister(ARM::R1);
673   }
674
675   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
676   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
677   // the default expansion.
678   // FIXME: This should be checking for v6k, not just v6.
679   if (Subtarget->hasDataBarrier() ||
680       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
681     // membarrier needs custom lowering; the rest are legal and handled
682     // normally.
683     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
684     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
685     // Custom lowering for 64-bit ops
686     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
690     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
691     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
692     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
693     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
694     setInsertFencesForAtomic(true);
695   } else {
696     // Set them all for expansion, which will force libcalls.
697     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
698     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
699     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
708     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
709     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
710     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
711     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
712     // Unordered/Monotonic case.
713     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
714     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
715     // Since the libcalls include locking, fold in the fences
716     setShouldFoldAtomicFences(true);
717   }
718
719   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
720
721   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
722   if (!Subtarget->hasV6Ops()) {
723     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
725   }
726   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
727
728   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
729       !Subtarget->isThumb1Only()) {
730     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
731     // iff target supports vfp2.
732     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
733     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
734   }
735
736   // We want to custom lower some of our intrinsics.
737   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
738   if (Subtarget->isTargetDarwin()) {
739     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
740     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
741     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
742   }
743
744   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
745   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
746   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
747   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
748   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
749   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
750   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
751   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
752   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
753
754   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
755   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
756   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
757   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
758   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
759
760   // We don't support sin/cos/fmod/copysign/pow
761   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
762   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
763   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
764   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
765   setOperationAction(ISD::FREM,      MVT::f64, Expand);
766   setOperationAction(ISD::FREM,      MVT::f32, Expand);
767   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
768       !Subtarget->isThumb1Only()) {
769     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
770     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
771   }
772   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
773   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
774
775   if (!Subtarget->hasVFP4()) {
776     setOperationAction(ISD::FMA, MVT::f64, Expand);
777     setOperationAction(ISD::FMA, MVT::f32, Expand);
778   }
779
780   // Various VFP goodness
781   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
782     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
783     if (Subtarget->hasVFP2()) {
784       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
785       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
786       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
787       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
788     }
789     // Special handling for half-precision FP.
790     if (!Subtarget->hasFP16()) {
791       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
792       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
793     }
794   }
795
796   // We have target-specific dag combine patterns for the following nodes:
797   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
798   setTargetDAGCombine(ISD::ADD);
799   setTargetDAGCombine(ISD::SUB);
800   setTargetDAGCombine(ISD::MUL);
801   setTargetDAGCombine(ISD::AND);
802   setTargetDAGCombine(ISD::OR);
803   setTargetDAGCombine(ISD::XOR);
804
805   if (Subtarget->hasV6Ops())
806     setTargetDAGCombine(ISD::SRL);
807
808   setStackPointerRegisterToSaveRestore(ARM::SP);
809
810   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
811       !Subtarget->hasVFP2())
812     setSchedulingPreference(Sched::RegPressure);
813   else
814     setSchedulingPreference(Sched::Hybrid);
815
816   //// temporary - rewrite interface to use type
817   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
818   maxStoresPerMemset = 16;
819   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
820
821   // On ARM arguments smaller than 4 bytes are extended, so all arguments
822   // are at least 4 bytes aligned.
823   setMinStackArgumentAlignment(4);
824
825   benefitFromCodePlacementOpt = true;
826
827   // Prefer likely predicted branches to selects on out-of-order cores.
828   predictableSelectIsExpensive = Subtarget->isLikeA9();
829
830   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
831 }
832
833 // FIXME: It might make sense to define the representative register class as the
834 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
835 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
836 // SPR's representative would be DPR_VFP2. This should work well if register
837 // pressure tracking were modified such that a register use would increment the
838 // pressure of the register class's representative and all of it's super
839 // classes' representatives transitively. We have not implemented this because
840 // of the difficulty prior to coalescing of modeling operand register classes
841 // due to the common occurrence of cross class copies and subregister insertions
842 // and extractions.
843 std::pair<const TargetRegisterClass*, uint8_t>
844 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
845   const TargetRegisterClass *RRC = 0;
846   uint8_t Cost = 1;
847   switch (VT.getSimpleVT().SimpleTy) {
848   default:
849     return TargetLowering::findRepresentativeClass(VT);
850   // Use DPR as representative register class for all floating point
851   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
852   // the cost is 1 for both f32 and f64.
853   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
854   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
855     RRC = &ARM::DPRRegClass;
856     // When NEON is used for SP, only half of the register file is available
857     // because operations that define both SP and DP results will be constrained
858     // to the VFP2 class (D0-D15). We currently model this constraint prior to
859     // coalescing by double-counting the SP regs. See the FIXME above.
860     if (Subtarget->useNEONForSinglePrecisionFP())
861       Cost = 2;
862     break;
863   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
864   case MVT::v4f32: case MVT::v2f64:
865     RRC = &ARM::DPRRegClass;
866     Cost = 2;
867     break;
868   case MVT::v4i64:
869     RRC = &ARM::DPRRegClass;
870     Cost = 4;
871     break;
872   case MVT::v8i64:
873     RRC = &ARM::DPRRegClass;
874     Cost = 8;
875     break;
876   }
877   return std::make_pair(RRC, Cost);
878 }
879
880 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
881   switch (Opcode) {
882   default: return 0;
883   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
884   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
885   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
886   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
887   case ARMISD::CALL:          return "ARMISD::CALL";
888   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
889   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
890   case ARMISD::tCALL:         return "ARMISD::tCALL";
891   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
892   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
893   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
894   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
895   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
896   case ARMISD::CMP:           return "ARMISD::CMP";
897   case ARMISD::CMN:           return "ARMISD::CMN";
898   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
899   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
900   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
901   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
902   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
903
904   case ARMISD::CMOV:          return "ARMISD::CMOV";
905
906   case ARMISD::RBIT:          return "ARMISD::RBIT";
907
908   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
909   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
910   case ARMISD::SITOF:         return "ARMISD::SITOF";
911   case ARMISD::UITOF:         return "ARMISD::UITOF";
912
913   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
914   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
915   case ARMISD::RRX:           return "ARMISD::RRX";
916
917   case ARMISD::ADDC:          return "ARMISD::ADDC";
918   case ARMISD::ADDE:          return "ARMISD::ADDE";
919   case ARMISD::SUBC:          return "ARMISD::SUBC";
920   case ARMISD::SUBE:          return "ARMISD::SUBE";
921
922   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
923   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
924
925   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
926   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
927
928   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
929
930   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
931
932   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
933
934   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
935   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
936
937   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
938
939   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
940   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
941   case ARMISD::VCGE:          return "ARMISD::VCGE";
942   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
943   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
944   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
945   case ARMISD::VCGT:          return "ARMISD::VCGT";
946   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
947   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
948   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
949   case ARMISD::VTST:          return "ARMISD::VTST";
950
951   case ARMISD::VSHL:          return "ARMISD::VSHL";
952   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
953   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
954   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
955   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
956   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
957   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
958   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
959   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
960   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
961   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
962   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
963   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
964   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
965   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
966   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
967   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
968   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
969   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
970   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
971   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
972   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
973   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
974   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
975   case ARMISD::VDUP:          return "ARMISD::VDUP";
976   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
977   case ARMISD::VEXT:          return "ARMISD::VEXT";
978   case ARMISD::VREV64:        return "ARMISD::VREV64";
979   case ARMISD::VREV32:        return "ARMISD::VREV32";
980   case ARMISD::VREV16:        return "ARMISD::VREV16";
981   case ARMISD::VZIP:          return "ARMISD::VZIP";
982   case ARMISD::VUZP:          return "ARMISD::VUZP";
983   case ARMISD::VTRN:          return "ARMISD::VTRN";
984   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
985   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
986   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
987   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
988   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
989   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
990   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
991   case ARMISD::FMAX:          return "ARMISD::FMAX";
992   case ARMISD::FMIN:          return "ARMISD::FMIN";
993   case ARMISD::BFI:           return "ARMISD::BFI";
994   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
995   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
996   case ARMISD::VBSL:          return "ARMISD::VBSL";
997   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
998   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
999   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1000   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1001   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1002   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1003   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1004   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1005   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1006   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1007   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1008   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1009   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1010   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1011   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1012   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1013   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1014   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1015   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1016   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1017   }
1018 }
1019
1020 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1021   if (!VT.isVector()) return getPointerTy();
1022   return VT.changeVectorElementTypeToInteger();
1023 }
1024
1025 /// getRegClassFor - Return the register class that should be used for the
1026 /// specified value type.
1027 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1028   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1029   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1030   // load / store 4 to 8 consecutive D registers.
1031   if (Subtarget->hasNEON()) {
1032     if (VT == MVT::v4i64)
1033       return &ARM::QQPRRegClass;
1034     if (VT == MVT::v8i64)
1035       return &ARM::QQQQPRRegClass;
1036   }
1037   return TargetLowering::getRegClassFor(VT);
1038 }
1039
1040 // Create a fast isel object.
1041 FastISel *
1042 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1043                                   const TargetLibraryInfo *libInfo) const {
1044   return ARM::createFastISel(funcInfo, libInfo);
1045 }
1046
1047 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1048 /// be used for loads / stores from the global.
1049 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1050   return (Subtarget->isThumb1Only() ? 127 : 4095);
1051 }
1052
1053 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1054   unsigned NumVals = N->getNumValues();
1055   if (!NumVals)
1056     return Sched::RegPressure;
1057
1058   for (unsigned i = 0; i != NumVals; ++i) {
1059     EVT VT = N->getValueType(i);
1060     if (VT == MVT::Glue || VT == MVT::Other)
1061       continue;
1062     if (VT.isFloatingPoint() || VT.isVector())
1063       return Sched::ILP;
1064   }
1065
1066   if (!N->isMachineOpcode())
1067     return Sched::RegPressure;
1068
1069   // Load are scheduled for latency even if there instruction itinerary
1070   // is not available.
1071   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1072   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1073
1074   if (MCID.getNumDefs() == 0)
1075     return Sched::RegPressure;
1076   if (!Itins->isEmpty() &&
1077       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1078     return Sched::ILP;
1079
1080   return Sched::RegPressure;
1081 }
1082
1083 //===----------------------------------------------------------------------===//
1084 // Lowering Code
1085 //===----------------------------------------------------------------------===//
1086
1087 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1088 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1089   switch (CC) {
1090   default: llvm_unreachable("Unknown condition code!");
1091   case ISD::SETNE:  return ARMCC::NE;
1092   case ISD::SETEQ:  return ARMCC::EQ;
1093   case ISD::SETGT:  return ARMCC::GT;
1094   case ISD::SETGE:  return ARMCC::GE;
1095   case ISD::SETLT:  return ARMCC::LT;
1096   case ISD::SETLE:  return ARMCC::LE;
1097   case ISD::SETUGT: return ARMCC::HI;
1098   case ISD::SETUGE: return ARMCC::HS;
1099   case ISD::SETULT: return ARMCC::LO;
1100   case ISD::SETULE: return ARMCC::LS;
1101   }
1102 }
1103
1104 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1105 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1106                         ARMCC::CondCodes &CondCode2) {
1107   CondCode2 = ARMCC::AL;
1108   switch (CC) {
1109   default: llvm_unreachable("Unknown FP condition!");
1110   case ISD::SETEQ:
1111   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1112   case ISD::SETGT:
1113   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1114   case ISD::SETGE:
1115   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1116   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1117   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1118   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1119   case ISD::SETO:   CondCode = ARMCC::VC; break;
1120   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1121   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1122   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1123   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1124   case ISD::SETLT:
1125   case ISD::SETULT: CondCode = ARMCC::LT; break;
1126   case ISD::SETLE:
1127   case ISD::SETULE: CondCode = ARMCC::LE; break;
1128   case ISD::SETNE:
1129   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1130   }
1131 }
1132
1133 //===----------------------------------------------------------------------===//
1134 //                      Calling Convention Implementation
1135 //===----------------------------------------------------------------------===//
1136
1137 #include "ARMGenCallingConv.inc"
1138
1139 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1140 /// given CallingConvention value.
1141 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1142                                                  bool Return,
1143                                                  bool isVarArg) const {
1144   switch (CC) {
1145   default:
1146     llvm_unreachable("Unsupported calling convention");
1147   case CallingConv::Fast:
1148     if (Subtarget->hasVFP2() && !isVarArg) {
1149       if (!Subtarget->isAAPCS_ABI())
1150         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1151       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1152       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1153     }
1154     // Fallthrough
1155   case CallingConv::C: {
1156     // Use target triple & subtarget features to do actual dispatch.
1157     if (!Subtarget->isAAPCS_ABI())
1158       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1159     else if (Subtarget->hasVFP2() &&
1160              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1161              !isVarArg)
1162       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1163     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1164   }
1165   case CallingConv::ARM_AAPCS_VFP:
1166     if (!isVarArg)
1167       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1168     // Fallthrough
1169   case CallingConv::ARM_AAPCS:
1170     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1171   case CallingConv::ARM_APCS:
1172     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1173   case CallingConv::GHC:
1174     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1175   }
1176 }
1177
1178 /// LowerCallResult - Lower the result values of a call into the
1179 /// appropriate copies out of appropriate physical registers.
1180 SDValue
1181 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1182                                    CallingConv::ID CallConv, bool isVarArg,
1183                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1184                                    DebugLoc dl, SelectionDAG &DAG,
1185                                    SmallVectorImpl<SDValue> &InVals) const {
1186
1187   // Assign locations to each value returned by this call.
1188   SmallVector<CCValAssign, 16> RVLocs;
1189   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1190                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1191   CCInfo.AnalyzeCallResult(Ins,
1192                            CCAssignFnForNode(CallConv, /* Return*/ true,
1193                                              isVarArg));
1194
1195   // Copy all of the result registers out of their specified physreg.
1196   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1197     CCValAssign VA = RVLocs[i];
1198
1199     SDValue Val;
1200     if (VA.needsCustom()) {
1201       // Handle f64 or half of a v2f64.
1202       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1203                                       InFlag);
1204       Chain = Lo.getValue(1);
1205       InFlag = Lo.getValue(2);
1206       VA = RVLocs[++i]; // skip ahead to next loc
1207       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1208                                       InFlag);
1209       Chain = Hi.getValue(1);
1210       InFlag = Hi.getValue(2);
1211       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1212
1213       if (VA.getLocVT() == MVT::v2f64) {
1214         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1215         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1216                           DAG.getConstant(0, MVT::i32));
1217
1218         VA = RVLocs[++i]; // skip ahead to next loc
1219         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1220         Chain = Lo.getValue(1);
1221         InFlag = Lo.getValue(2);
1222         VA = RVLocs[++i]; // skip ahead to next loc
1223         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1224         Chain = Hi.getValue(1);
1225         InFlag = Hi.getValue(2);
1226         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1227         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1228                           DAG.getConstant(1, MVT::i32));
1229       }
1230     } else {
1231       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1232                                InFlag);
1233       Chain = Val.getValue(1);
1234       InFlag = Val.getValue(2);
1235     }
1236
1237     switch (VA.getLocInfo()) {
1238     default: llvm_unreachable("Unknown loc info!");
1239     case CCValAssign::Full: break;
1240     case CCValAssign::BCvt:
1241       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1242       break;
1243     }
1244
1245     InVals.push_back(Val);
1246   }
1247
1248   return Chain;
1249 }
1250
1251 /// LowerMemOpCallTo - Store the argument to the stack.
1252 SDValue
1253 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1254                                     SDValue StackPtr, SDValue Arg,
1255                                     DebugLoc dl, SelectionDAG &DAG,
1256                                     const CCValAssign &VA,
1257                                     ISD::ArgFlagsTy Flags) const {
1258   unsigned LocMemOffset = VA.getLocMemOffset();
1259   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1260   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1261   return DAG.getStore(Chain, dl, Arg, PtrOff,
1262                       MachinePointerInfo::getStack(LocMemOffset),
1263                       false, false, 0);
1264 }
1265
1266 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1267                                          SDValue Chain, SDValue &Arg,
1268                                          RegsToPassVector &RegsToPass,
1269                                          CCValAssign &VA, CCValAssign &NextVA,
1270                                          SDValue &StackPtr,
1271                                          SmallVector<SDValue, 8> &MemOpChains,
1272                                          ISD::ArgFlagsTy Flags) const {
1273
1274   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1275                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1276   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1277
1278   if (NextVA.isRegLoc())
1279     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1280   else {
1281     assert(NextVA.isMemLoc());
1282     if (StackPtr.getNode() == 0)
1283       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1284
1285     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1286                                            dl, DAG, NextVA,
1287                                            Flags));
1288   }
1289 }
1290
1291 /// LowerCall - Lowering a call into a callseq_start <-
1292 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1293 /// nodes.
1294 SDValue
1295 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1296                              SmallVectorImpl<SDValue> &InVals) const {
1297   SelectionDAG &DAG                     = CLI.DAG;
1298   DebugLoc &dl                          = CLI.DL;
1299   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1300   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1301   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1302   SDValue Chain                         = CLI.Chain;
1303   SDValue Callee                        = CLI.Callee;
1304   bool &isTailCall                      = CLI.IsTailCall;
1305   CallingConv::ID CallConv              = CLI.CallConv;
1306   bool doesNotRet                       = CLI.DoesNotReturn;
1307   bool isVarArg                         = CLI.IsVarArg;
1308
1309   MachineFunction &MF = DAG.getMachineFunction();
1310   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1311   bool IsSibCall = false;
1312   // Disable tail calls if they're not supported.
1313   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1314     isTailCall = false;
1315   if (isTailCall) {
1316     // Check if it's really possible to do a tail call.
1317     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1318                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1319                                                    Outs, OutVals, Ins, DAG);
1320     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1321     // detected sibcalls.
1322     if (isTailCall) {
1323       ++NumTailCalls;
1324       IsSibCall = true;
1325     }
1326   }
1327
1328   // Analyze operands of the call, assigning locations to each operand.
1329   SmallVector<CCValAssign, 16> ArgLocs;
1330   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1331                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1332   CCInfo.AnalyzeCallOperands(Outs,
1333                              CCAssignFnForNode(CallConv, /* Return*/ false,
1334                                                isVarArg));
1335
1336   // Get a count of how many bytes are to be pushed on the stack.
1337   unsigned NumBytes = CCInfo.getNextStackOffset();
1338
1339   // For tail calls, memory operands are available in our caller's stack.
1340   if (IsSibCall)
1341     NumBytes = 0;
1342
1343   // Adjust the stack pointer for the new arguments...
1344   // These operations are automatically eliminated by the prolog/epilog pass
1345   if (!IsSibCall)
1346     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1347
1348   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1349
1350   RegsToPassVector RegsToPass;
1351   SmallVector<SDValue, 8> MemOpChains;
1352
1353   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1354   // of tail call optimization, arguments are handled later.
1355   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1356        i != e;
1357        ++i, ++realArgIdx) {
1358     CCValAssign &VA = ArgLocs[i];
1359     SDValue Arg = OutVals[realArgIdx];
1360     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1361     bool isByVal = Flags.isByVal();
1362
1363     // Promote the value if needed.
1364     switch (VA.getLocInfo()) {
1365     default: llvm_unreachable("Unknown loc info!");
1366     case CCValAssign::Full: break;
1367     case CCValAssign::SExt:
1368       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1369       break;
1370     case CCValAssign::ZExt:
1371       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1372       break;
1373     case CCValAssign::AExt:
1374       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1375       break;
1376     case CCValAssign::BCvt:
1377       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1378       break;
1379     }
1380
1381     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1382     if (VA.needsCustom()) {
1383       if (VA.getLocVT() == MVT::v2f64) {
1384         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1385                                   DAG.getConstant(0, MVT::i32));
1386         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1387                                   DAG.getConstant(1, MVT::i32));
1388
1389         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1390                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1391
1392         VA = ArgLocs[++i]; // skip ahead to next loc
1393         if (VA.isRegLoc()) {
1394           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1395                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1396         } else {
1397           assert(VA.isMemLoc());
1398
1399           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1400                                                  dl, DAG, VA, Flags));
1401         }
1402       } else {
1403         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1404                          StackPtr, MemOpChains, Flags);
1405       }
1406     } else if (VA.isRegLoc()) {
1407       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1408     } else if (isByVal) {
1409       assert(VA.isMemLoc());
1410       unsigned offset = 0;
1411
1412       // True if this byval aggregate will be split between registers
1413       // and memory.
1414       if (CCInfo.isFirstByValRegValid()) {
1415         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1416         unsigned int i, j;
1417         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1418           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1419           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1420           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1421                                      MachinePointerInfo(),
1422                                      false, false, false, 0);
1423           MemOpChains.push_back(Load.getValue(1));
1424           RegsToPass.push_back(std::make_pair(j, Load));
1425         }
1426         offset = ARM::R4 - CCInfo.getFirstByValReg();
1427         CCInfo.clearFirstByValReg();
1428       }
1429
1430       if (Flags.getByValSize() - 4*offset > 0) {
1431         unsigned LocMemOffset = VA.getLocMemOffset();
1432         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1433         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1434                                   StkPtrOff);
1435         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1436         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1437         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1438                                            MVT::i32);
1439         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1440
1441         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1442         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1443         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1444                                           Ops, array_lengthof(Ops)));
1445       }
1446     } else if (!IsSibCall) {
1447       assert(VA.isMemLoc());
1448
1449       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1450                                              dl, DAG, VA, Flags));
1451     }
1452   }
1453
1454   if (!MemOpChains.empty())
1455     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1456                         &MemOpChains[0], MemOpChains.size());
1457
1458   // Build a sequence of copy-to-reg nodes chained together with token chain
1459   // and flag operands which copy the outgoing args into the appropriate regs.
1460   SDValue InFlag;
1461   // Tail call byval lowering might overwrite argument registers so in case of
1462   // tail call optimization the copies to registers are lowered later.
1463   if (!isTailCall)
1464     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1465       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1466                                RegsToPass[i].second, InFlag);
1467       InFlag = Chain.getValue(1);
1468     }
1469
1470   // For tail calls lower the arguments to the 'real' stack slot.
1471   if (isTailCall) {
1472     // Force all the incoming stack arguments to be loaded from the stack
1473     // before any new outgoing arguments are stored to the stack, because the
1474     // outgoing stack slots may alias the incoming argument stack slots, and
1475     // the alias isn't otherwise explicit. This is slightly more conservative
1476     // than necessary, because it means that each store effectively depends
1477     // on every argument instead of just those arguments it would clobber.
1478
1479     // Do not flag preceding copytoreg stuff together with the following stuff.
1480     InFlag = SDValue();
1481     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1482       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1483                                RegsToPass[i].second, InFlag);
1484       InFlag = Chain.getValue(1);
1485     }
1486     InFlag =SDValue();
1487   }
1488
1489   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1490   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1491   // node so that legalize doesn't hack it.
1492   bool isDirect = false;
1493   bool isARMFunc = false;
1494   bool isLocalARMFunc = false;
1495   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1496
1497   if (EnableARMLongCalls) {
1498     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1499             && "long-calls with non-static relocation model!");
1500     // Handle a global address or an external symbol. If it's not one of
1501     // those, the target's already in a register, so we don't need to do
1502     // anything extra.
1503     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1504       const GlobalValue *GV = G->getGlobal();
1505       // Create a constant pool entry for the callee address
1506       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1507       ARMConstantPoolValue *CPV =
1508         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1509
1510       // Get the address of the callee into a register
1511       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1512       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1513       Callee = DAG.getLoad(getPointerTy(), dl,
1514                            DAG.getEntryNode(), CPAddr,
1515                            MachinePointerInfo::getConstantPool(),
1516                            false, false, false, 0);
1517     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1518       const char *Sym = S->getSymbol();
1519
1520       // Create a constant pool entry for the callee address
1521       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1522       ARMConstantPoolValue *CPV =
1523         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1524                                       ARMPCLabelIndex, 0);
1525       // Get the address of the callee into a register
1526       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1527       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1528       Callee = DAG.getLoad(getPointerTy(), dl,
1529                            DAG.getEntryNode(), CPAddr,
1530                            MachinePointerInfo::getConstantPool(),
1531                            false, false, false, 0);
1532     }
1533   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1534     const GlobalValue *GV = G->getGlobal();
1535     isDirect = true;
1536     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1537     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1538                    getTargetMachine().getRelocationModel() != Reloc::Static;
1539     isARMFunc = !Subtarget->isThumb() || isStub;
1540     // ARM call to a local ARM function is predicable.
1541     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1542     // tBX takes a register source operand.
1543     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1544       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1545       ARMConstantPoolValue *CPV =
1546         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1547       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1548       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1549       Callee = DAG.getLoad(getPointerTy(), dl,
1550                            DAG.getEntryNode(), CPAddr,
1551                            MachinePointerInfo::getConstantPool(),
1552                            false, false, false, 0);
1553       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1554       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1555                            getPointerTy(), Callee, PICLabel);
1556     } else {
1557       // On ELF targets for PIC code, direct calls should go through the PLT
1558       unsigned OpFlags = 0;
1559       if (Subtarget->isTargetELF() &&
1560                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1561         OpFlags = ARMII::MO_PLT;
1562       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1563     }
1564   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1565     isDirect = true;
1566     bool isStub = Subtarget->isTargetDarwin() &&
1567                   getTargetMachine().getRelocationModel() != Reloc::Static;
1568     isARMFunc = !Subtarget->isThumb() || isStub;
1569     // tBX takes a register source operand.
1570     const char *Sym = S->getSymbol();
1571     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1572       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1573       ARMConstantPoolValue *CPV =
1574         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1575                                       ARMPCLabelIndex, 4);
1576       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1577       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1578       Callee = DAG.getLoad(getPointerTy(), dl,
1579                            DAG.getEntryNode(), CPAddr,
1580                            MachinePointerInfo::getConstantPool(),
1581                            false, false, false, 0);
1582       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1583       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1584                            getPointerTy(), Callee, PICLabel);
1585     } else {
1586       unsigned OpFlags = 0;
1587       // On ELF targets for PIC code, direct calls should go through the PLT
1588       if (Subtarget->isTargetELF() &&
1589                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1590         OpFlags = ARMII::MO_PLT;
1591       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1592     }
1593   }
1594
1595   // FIXME: handle tail calls differently.
1596   unsigned CallOpc;
1597   bool HasMinSizeAttr = MF.getFunction()->getFnAttributes().
1598     hasAttribute(Attributes::MinSize);
1599   if (Subtarget->isThumb()) {
1600     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1601       CallOpc = ARMISD::CALL_NOLINK;
1602     else
1603       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1604   } else {
1605     if (!isDirect && !Subtarget->hasV5TOps())
1606       CallOpc = ARMISD::CALL_NOLINK;
1607     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1608                // Emit regular call when code size is the priority
1609                !HasMinSizeAttr)
1610       // "mov lr, pc; b _foo" to avoid confusing the RSP
1611       CallOpc = ARMISD::CALL_NOLINK;
1612     else
1613       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1614   }
1615
1616   std::vector<SDValue> Ops;
1617   Ops.push_back(Chain);
1618   Ops.push_back(Callee);
1619
1620   // Add argument registers to the end of the list so that they are known live
1621   // into the call.
1622   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1623     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1624                                   RegsToPass[i].second.getValueType()));
1625
1626   // Add a register mask operand representing the call-preserved registers.
1627   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1628   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1629   assert(Mask && "Missing call preserved mask for calling convention");
1630   Ops.push_back(DAG.getRegisterMask(Mask));
1631
1632   if (InFlag.getNode())
1633     Ops.push_back(InFlag);
1634
1635   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1636   if (isTailCall)
1637     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1638
1639   // Returns a chain and a flag for retval copy to use.
1640   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1641   InFlag = Chain.getValue(1);
1642
1643   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1644                              DAG.getIntPtrConstant(0, true), InFlag);
1645   if (!Ins.empty())
1646     InFlag = Chain.getValue(1);
1647
1648   // Handle result values, copying them out of physregs into vregs that we
1649   // return.
1650   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1651                          dl, DAG, InVals);
1652 }
1653
1654 /// HandleByVal - Every parameter *after* a byval parameter is passed
1655 /// on the stack.  Remember the next parameter register to allocate,
1656 /// and then confiscate the rest of the parameter registers to insure
1657 /// this.
1658 void
1659 ARMTargetLowering::HandleByVal(
1660     CCState *State, unsigned &size, unsigned Align) const {
1661   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1662   assert((State->getCallOrPrologue() == Prologue ||
1663           State->getCallOrPrologue() == Call) &&
1664          "unhandled ParmContext");
1665   if ((!State->isFirstByValRegValid()) &&
1666       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1667     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1668       unsigned AlignInRegs = Align / 4;
1669       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1670       for (unsigned i = 0; i < Waste; ++i)
1671         reg = State->AllocateReg(GPRArgRegs, 4);
1672     }
1673     if (reg != 0) {
1674       State->setFirstByValReg(reg);
1675       // At a call site, a byval parameter that is split between
1676       // registers and memory needs its size truncated here.  In a
1677       // function prologue, such byval parameters are reassembled in
1678       // memory, and are not truncated.
1679       if (State->getCallOrPrologue() == Call) {
1680         unsigned excess = 4 * (ARM::R4 - reg);
1681         assert(size >= excess && "expected larger existing stack allocation");
1682         size -= excess;
1683       }
1684     }
1685   }
1686   // Confiscate any remaining parameter registers to preclude their
1687   // assignment to subsequent parameters.
1688   while (State->AllocateReg(GPRArgRegs, 4))
1689     ;
1690 }
1691
1692 /// MatchingStackOffset - Return true if the given stack call argument is
1693 /// already available in the same position (relatively) of the caller's
1694 /// incoming argument stack.
1695 static
1696 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1697                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1698                          const TargetInstrInfo *TII) {
1699   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1700   int FI = INT_MAX;
1701   if (Arg.getOpcode() == ISD::CopyFromReg) {
1702     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1703     if (!TargetRegisterInfo::isVirtualRegister(VR))
1704       return false;
1705     MachineInstr *Def = MRI->getVRegDef(VR);
1706     if (!Def)
1707       return false;
1708     if (!Flags.isByVal()) {
1709       if (!TII->isLoadFromStackSlot(Def, FI))
1710         return false;
1711     } else {
1712       return false;
1713     }
1714   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1715     if (Flags.isByVal())
1716       // ByVal argument is passed in as a pointer but it's now being
1717       // dereferenced. e.g.
1718       // define @foo(%struct.X* %A) {
1719       //   tail call @bar(%struct.X* byval %A)
1720       // }
1721       return false;
1722     SDValue Ptr = Ld->getBasePtr();
1723     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1724     if (!FINode)
1725       return false;
1726     FI = FINode->getIndex();
1727   } else
1728     return false;
1729
1730   assert(FI != INT_MAX);
1731   if (!MFI->isFixedObjectIndex(FI))
1732     return false;
1733   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1734 }
1735
1736 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1737 /// for tail call optimization. Targets which want to do tail call
1738 /// optimization should implement this function.
1739 bool
1740 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1741                                                      CallingConv::ID CalleeCC,
1742                                                      bool isVarArg,
1743                                                      bool isCalleeStructRet,
1744                                                      bool isCallerStructRet,
1745                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1746                                     const SmallVectorImpl<SDValue> &OutVals,
1747                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1748                                                      SelectionDAG& DAG) const {
1749   const Function *CallerF = DAG.getMachineFunction().getFunction();
1750   CallingConv::ID CallerCC = CallerF->getCallingConv();
1751   bool CCMatch = CallerCC == CalleeCC;
1752
1753   // Look for obvious safe cases to perform tail call optimization that do not
1754   // require ABI changes. This is what gcc calls sibcall.
1755
1756   // Do not sibcall optimize vararg calls unless the call site is not passing
1757   // any arguments.
1758   if (isVarArg && !Outs.empty())
1759     return false;
1760
1761   // Also avoid sibcall optimization if either caller or callee uses struct
1762   // return semantics.
1763   if (isCalleeStructRet || isCallerStructRet)
1764     return false;
1765
1766   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1767   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1768   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1769   // support in the assembler and linker to be used. This would need to be
1770   // fixed to fully support tail calls in Thumb1.
1771   //
1772   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1773   // LR.  This means if we need to reload LR, it takes an extra instructions,
1774   // which outweighs the value of the tail call; but here we don't know yet
1775   // whether LR is going to be used.  Probably the right approach is to
1776   // generate the tail call here and turn it back into CALL/RET in
1777   // emitEpilogue if LR is used.
1778
1779   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1780   // but we need to make sure there are enough registers; the only valid
1781   // registers are the 4 used for parameters.  We don't currently do this
1782   // case.
1783   if (Subtarget->isThumb1Only())
1784     return false;
1785
1786   // If the calling conventions do not match, then we'd better make sure the
1787   // results are returned in the same way as what the caller expects.
1788   if (!CCMatch) {
1789     SmallVector<CCValAssign, 16> RVLocs1;
1790     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1791                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1792     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1793
1794     SmallVector<CCValAssign, 16> RVLocs2;
1795     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1796                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1797     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1798
1799     if (RVLocs1.size() != RVLocs2.size())
1800       return false;
1801     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1802       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1803         return false;
1804       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1805         return false;
1806       if (RVLocs1[i].isRegLoc()) {
1807         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1808           return false;
1809       } else {
1810         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1811           return false;
1812       }
1813     }
1814   }
1815
1816   // If Caller's vararg or byval argument has been split between registers and
1817   // stack, do not perform tail call, since part of the argument is in caller's
1818   // local frame.
1819   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1820                                       getInfo<ARMFunctionInfo>();
1821   if (AFI_Caller->getVarArgsRegSaveSize())
1822     return false;
1823
1824   // If the callee takes no arguments then go on to check the results of the
1825   // call.
1826   if (!Outs.empty()) {
1827     // Check if stack adjustment is needed. For now, do not do this if any
1828     // argument is passed on the stack.
1829     SmallVector<CCValAssign, 16> ArgLocs;
1830     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1831                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1832     CCInfo.AnalyzeCallOperands(Outs,
1833                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1834     if (CCInfo.getNextStackOffset()) {
1835       MachineFunction &MF = DAG.getMachineFunction();
1836
1837       // Check if the arguments are already laid out in the right way as
1838       // the caller's fixed stack objects.
1839       MachineFrameInfo *MFI = MF.getFrameInfo();
1840       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1841       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1842       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1843            i != e;
1844            ++i, ++realArgIdx) {
1845         CCValAssign &VA = ArgLocs[i];
1846         EVT RegVT = VA.getLocVT();
1847         SDValue Arg = OutVals[realArgIdx];
1848         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1849         if (VA.getLocInfo() == CCValAssign::Indirect)
1850           return false;
1851         if (VA.needsCustom()) {
1852           // f64 and vector types are split into multiple registers or
1853           // register/stack-slot combinations.  The types will not match
1854           // the registers; give up on memory f64 refs until we figure
1855           // out what to do about this.
1856           if (!VA.isRegLoc())
1857             return false;
1858           if (!ArgLocs[++i].isRegLoc())
1859             return false;
1860           if (RegVT == MVT::v2f64) {
1861             if (!ArgLocs[++i].isRegLoc())
1862               return false;
1863             if (!ArgLocs[++i].isRegLoc())
1864               return false;
1865           }
1866         } else if (!VA.isRegLoc()) {
1867           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1868                                    MFI, MRI, TII))
1869             return false;
1870         }
1871       }
1872     }
1873   }
1874
1875   return true;
1876 }
1877
1878 SDValue
1879 ARMTargetLowering::LowerReturn(SDValue Chain,
1880                                CallingConv::ID CallConv, bool isVarArg,
1881                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1882                                const SmallVectorImpl<SDValue> &OutVals,
1883                                DebugLoc dl, SelectionDAG &DAG) const {
1884
1885   // CCValAssign - represent the assignment of the return value to a location.
1886   SmallVector<CCValAssign, 16> RVLocs;
1887
1888   // CCState - Info about the registers and stack slots.
1889   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1890                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1891
1892   // Analyze outgoing return values.
1893   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1894                                                isVarArg));
1895
1896   // If this is the first return lowered for this function, add
1897   // the regs to the liveout set for the function.
1898   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1899     for (unsigned i = 0; i != RVLocs.size(); ++i)
1900       if (RVLocs[i].isRegLoc())
1901         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1902   }
1903
1904   SDValue Flag;
1905
1906   // Copy the result values into the output registers.
1907   for (unsigned i = 0, realRVLocIdx = 0;
1908        i != RVLocs.size();
1909        ++i, ++realRVLocIdx) {
1910     CCValAssign &VA = RVLocs[i];
1911     assert(VA.isRegLoc() && "Can only return in registers!");
1912
1913     SDValue Arg = OutVals[realRVLocIdx];
1914
1915     switch (VA.getLocInfo()) {
1916     default: llvm_unreachable("Unknown loc info!");
1917     case CCValAssign::Full: break;
1918     case CCValAssign::BCvt:
1919       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1920       break;
1921     }
1922
1923     if (VA.needsCustom()) {
1924       if (VA.getLocVT() == MVT::v2f64) {
1925         // Extract the first half and return it in two registers.
1926         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1927                                    DAG.getConstant(0, MVT::i32));
1928         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1929                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1930
1931         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1932         Flag = Chain.getValue(1);
1933         VA = RVLocs[++i]; // skip ahead to next loc
1934         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1935                                  HalfGPRs.getValue(1), Flag);
1936         Flag = Chain.getValue(1);
1937         VA = RVLocs[++i]; // skip ahead to next loc
1938
1939         // Extract the 2nd half and fall through to handle it as an f64 value.
1940         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1941                           DAG.getConstant(1, MVT::i32));
1942       }
1943       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1944       // available.
1945       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1946                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1947       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1948       Flag = Chain.getValue(1);
1949       VA = RVLocs[++i]; // skip ahead to next loc
1950       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1951                                Flag);
1952     } else
1953       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1954
1955     // Guarantee that all emitted copies are
1956     // stuck together, avoiding something bad.
1957     Flag = Chain.getValue(1);
1958   }
1959
1960   SDValue result;
1961   if (Flag.getNode())
1962     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1963   else // Return Void
1964     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1965
1966   return result;
1967 }
1968
1969 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1970   if (N->getNumValues() != 1)
1971     return false;
1972   if (!N->hasNUsesOfValue(1, 0))
1973     return false;
1974
1975   SDValue TCChain = Chain;
1976   SDNode *Copy = *N->use_begin();
1977   if (Copy->getOpcode() == ISD::CopyToReg) {
1978     // If the copy has a glue operand, we conservatively assume it isn't safe to
1979     // perform a tail call.
1980     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1981       return false;
1982     TCChain = Copy->getOperand(0);
1983   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1984     SDNode *VMov = Copy;
1985     // f64 returned in a pair of GPRs.
1986     SmallPtrSet<SDNode*, 2> Copies;
1987     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1988          UI != UE; ++UI) {
1989       if (UI->getOpcode() != ISD::CopyToReg)
1990         return false;
1991       Copies.insert(*UI);
1992     }
1993     if (Copies.size() > 2)
1994       return false;
1995
1996     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1997          UI != UE; ++UI) {
1998       SDValue UseChain = UI->getOperand(0);
1999       if (Copies.count(UseChain.getNode()))
2000         // Second CopyToReg
2001         Copy = *UI;
2002       else
2003         // First CopyToReg
2004         TCChain = UseChain;
2005     }
2006   } else if (Copy->getOpcode() == ISD::BITCAST) {
2007     // f32 returned in a single GPR.
2008     if (!Copy->hasOneUse())
2009       return false;
2010     Copy = *Copy->use_begin();
2011     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2012       return false;
2013     Chain = Copy->getOperand(0);
2014   } else {
2015     return false;
2016   }
2017
2018   bool HasRet = false;
2019   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2020        UI != UE; ++UI) {
2021     if (UI->getOpcode() != ARMISD::RET_FLAG)
2022       return false;
2023     HasRet = true;
2024   }
2025
2026   if (!HasRet)
2027     return false;
2028
2029   Chain = TCChain;
2030   return true;
2031 }
2032
2033 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2034   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2035     return false;
2036
2037   if (!CI->isTailCall())
2038     return false;
2039
2040   return !Subtarget->isThumb1Only();
2041 }
2042
2043 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2044 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2045 // one of the above mentioned nodes. It has to be wrapped because otherwise
2046 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2047 // be used to form addressing mode. These wrapped nodes will be selected
2048 // into MOVi.
2049 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2050   EVT PtrVT = Op.getValueType();
2051   // FIXME there is no actual debug info here
2052   DebugLoc dl = Op.getDebugLoc();
2053   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2054   SDValue Res;
2055   if (CP->isMachineConstantPoolEntry())
2056     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2057                                     CP->getAlignment());
2058   else
2059     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2060                                     CP->getAlignment());
2061   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2062 }
2063
2064 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2065   return MachineJumpTableInfo::EK_Inline;
2066 }
2067
2068 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2069                                              SelectionDAG &DAG) const {
2070   MachineFunction &MF = DAG.getMachineFunction();
2071   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2072   unsigned ARMPCLabelIndex = 0;
2073   DebugLoc DL = Op.getDebugLoc();
2074   EVT PtrVT = getPointerTy();
2075   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2076   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2077   SDValue CPAddr;
2078   if (RelocM == Reloc::Static) {
2079     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2080   } else {
2081     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2082     ARMPCLabelIndex = AFI->createPICLabelUId();
2083     ARMConstantPoolValue *CPV =
2084       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2085                                       ARMCP::CPBlockAddress, PCAdj);
2086     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2087   }
2088   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2089   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2090                                MachinePointerInfo::getConstantPool(),
2091                                false, false, false, 0);
2092   if (RelocM == Reloc::Static)
2093     return Result;
2094   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2095   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2096 }
2097
2098 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2099 SDValue
2100 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2101                                                  SelectionDAG &DAG) const {
2102   DebugLoc dl = GA->getDebugLoc();
2103   EVT PtrVT = getPointerTy();
2104   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2105   MachineFunction &MF = DAG.getMachineFunction();
2106   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2107   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2108   ARMConstantPoolValue *CPV =
2109     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2110                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2111   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2112   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2113   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2114                          MachinePointerInfo::getConstantPool(),
2115                          false, false, false, 0);
2116   SDValue Chain = Argument.getValue(1);
2117
2118   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2119   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2120
2121   // call __tls_get_addr.
2122   ArgListTy Args;
2123   ArgListEntry Entry;
2124   Entry.Node = Argument;
2125   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2126   Args.push_back(Entry);
2127   // FIXME: is there useful debug info available here?
2128   TargetLowering::CallLoweringInfo CLI(Chain,
2129                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2130                 false, false, false, false,
2131                 0, CallingConv::C, /*isTailCall=*/false,
2132                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2133                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2134   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2135   return CallResult.first;
2136 }
2137
2138 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2139 // "local exec" model.
2140 SDValue
2141 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2142                                         SelectionDAG &DAG,
2143                                         TLSModel::Model model) const {
2144   const GlobalValue *GV = GA->getGlobal();
2145   DebugLoc dl = GA->getDebugLoc();
2146   SDValue Offset;
2147   SDValue Chain = DAG.getEntryNode();
2148   EVT PtrVT = getPointerTy();
2149   // Get the Thread Pointer
2150   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2151
2152   if (model == TLSModel::InitialExec) {
2153     MachineFunction &MF = DAG.getMachineFunction();
2154     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2155     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2156     // Initial exec model.
2157     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2158     ARMConstantPoolValue *CPV =
2159       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2160                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2161                                       true);
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     Chain = Offset.getValue(1);
2168
2169     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2170     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2171
2172     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2173                          MachinePointerInfo::getConstantPool(),
2174                          false, false, false, 0);
2175   } else {
2176     // local exec model
2177     assert(model == TLSModel::LocalExec);
2178     ARMConstantPoolValue *CPV =
2179       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2180     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2181     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2182     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2183                          MachinePointerInfo::getConstantPool(),
2184                          false, false, false, 0);
2185   }
2186
2187   // The address of the thread local variable is the add of the thread
2188   // pointer with the offset of the variable.
2189   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2190 }
2191
2192 SDValue
2193 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2194   // TODO: implement the "local dynamic" model
2195   assert(Subtarget->isTargetELF() &&
2196          "TLS not implemented for non-ELF targets");
2197   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2198
2199   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2200
2201   switch (model) {
2202     case TLSModel::GeneralDynamic:
2203     case TLSModel::LocalDynamic:
2204       return LowerToTLSGeneralDynamicModel(GA, DAG);
2205     case TLSModel::InitialExec:
2206     case TLSModel::LocalExec:
2207       return LowerToTLSExecModels(GA, DAG, model);
2208   }
2209   llvm_unreachable("bogus TLS model");
2210 }
2211
2212 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2213                                                  SelectionDAG &DAG) const {
2214   EVT PtrVT = getPointerTy();
2215   DebugLoc dl = Op.getDebugLoc();
2216   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2217   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2218   if (RelocM == Reloc::PIC_) {
2219     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2220     ARMConstantPoolValue *CPV =
2221       ARMConstantPoolConstant::Create(GV,
2222                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2223     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2224     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2225     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2226                                  CPAddr,
2227                                  MachinePointerInfo::getConstantPool(),
2228                                  false, false, false, 0);
2229     SDValue Chain = Result.getValue(1);
2230     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2231     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2232     if (!UseGOTOFF)
2233       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2234                            MachinePointerInfo::getGOT(),
2235                            false, false, false, 0);
2236     return Result;
2237   }
2238
2239   // If we have T2 ops, we can materialize the address directly via movt/movw
2240   // pair. This is always cheaper.
2241   if (Subtarget->useMovt()) {
2242     ++NumMovwMovt;
2243     // FIXME: Once remat is capable of dealing with instructions with register
2244     // operands, expand this into two nodes.
2245     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2246                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2247   } else {
2248     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2249     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2250     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2251                        MachinePointerInfo::getConstantPool(),
2252                        false, false, false, 0);
2253   }
2254 }
2255
2256 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2257                                                     SelectionDAG &DAG) const {
2258   EVT PtrVT = getPointerTy();
2259   DebugLoc dl = Op.getDebugLoc();
2260   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2261   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2262   MachineFunction &MF = DAG.getMachineFunction();
2263   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2264
2265   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2266   // update ARMFastISel::ARMMaterializeGV.
2267   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2268     ++NumMovwMovt;
2269     // FIXME: Once remat is capable of dealing with instructions with register
2270     // operands, expand this into two nodes.
2271     if (RelocM == Reloc::Static)
2272       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2273                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2274
2275     unsigned Wrapper = (RelocM == Reloc::PIC_)
2276       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2277     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2278                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2279     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2280       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2281                            MachinePointerInfo::getGOT(),
2282                            false, false, false, 0);
2283     return Result;
2284   }
2285
2286   unsigned ARMPCLabelIndex = 0;
2287   SDValue CPAddr;
2288   if (RelocM == Reloc::Static) {
2289     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2290   } else {
2291     ARMPCLabelIndex = AFI->createPICLabelUId();
2292     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2293     ARMConstantPoolValue *CPV =
2294       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2295                                       PCAdj);
2296     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2297   }
2298   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2299
2300   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2301                                MachinePointerInfo::getConstantPool(),
2302                                false, false, false, 0);
2303   SDValue Chain = Result.getValue(1);
2304
2305   if (RelocM == Reloc::PIC_) {
2306     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2307     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2308   }
2309
2310   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2311     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2312                          false, false, false, 0);
2313
2314   return Result;
2315 }
2316
2317 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2318                                                     SelectionDAG &DAG) const {
2319   assert(Subtarget->isTargetELF() &&
2320          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2321   MachineFunction &MF = DAG.getMachineFunction();
2322   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2323   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2324   EVT PtrVT = getPointerTy();
2325   DebugLoc dl = Op.getDebugLoc();
2326   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2327   ARMConstantPoolValue *CPV =
2328     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2329                                   ARMPCLabelIndex, PCAdj);
2330   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2331   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2332   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2333                                MachinePointerInfo::getConstantPool(),
2334                                false, false, false, 0);
2335   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2336   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2337 }
2338
2339 SDValue
2340 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2341   DebugLoc dl = Op.getDebugLoc();
2342   SDValue Val = DAG.getConstant(0, MVT::i32);
2343   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2344                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2345                      Op.getOperand(1), Val);
2346 }
2347
2348 SDValue
2349 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2350   DebugLoc dl = Op.getDebugLoc();
2351   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2352                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2353 }
2354
2355 SDValue
2356 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2357                                           const ARMSubtarget *Subtarget) const {
2358   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2359   DebugLoc dl = Op.getDebugLoc();
2360   switch (IntNo) {
2361   default: return SDValue();    // Don't custom lower most intrinsics.
2362   case Intrinsic::arm_thread_pointer: {
2363     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2364     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2365   }
2366   case Intrinsic::eh_sjlj_lsda: {
2367     MachineFunction &MF = DAG.getMachineFunction();
2368     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2369     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2370     EVT PtrVT = getPointerTy();
2371     DebugLoc dl = Op.getDebugLoc();
2372     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2373     SDValue CPAddr;
2374     unsigned PCAdj = (RelocM != Reloc::PIC_)
2375       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2376     ARMConstantPoolValue *CPV =
2377       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2378                                       ARMCP::CPLSDA, PCAdj);
2379     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2380     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2381     SDValue Result =
2382       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2383                   MachinePointerInfo::getConstantPool(),
2384                   false, false, false, 0);
2385
2386     if (RelocM == Reloc::PIC_) {
2387       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2388       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2389     }
2390     return Result;
2391   }
2392   case Intrinsic::arm_neon_vmulls:
2393   case Intrinsic::arm_neon_vmullu: {
2394     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2395       ? ARMISD::VMULLs : ARMISD::VMULLu;
2396     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2397                        Op.getOperand(1), Op.getOperand(2));
2398   }
2399   }
2400 }
2401
2402 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2403                                const ARMSubtarget *Subtarget) {
2404   DebugLoc dl = Op.getDebugLoc();
2405   if (!Subtarget->hasDataBarrier()) {
2406     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2407     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2408     // here.
2409     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2410            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2411     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2412                        DAG.getConstant(0, MVT::i32));
2413   }
2414
2415   SDValue Op5 = Op.getOperand(5);
2416   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2417   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2418   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2419   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2420
2421   ARM_MB::MemBOpt DMBOpt;
2422   if (isDeviceBarrier)
2423     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2424   else
2425     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2426   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2427                      DAG.getConstant(DMBOpt, MVT::i32));
2428 }
2429
2430
2431 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2432                                  const ARMSubtarget *Subtarget) {
2433   // FIXME: handle "fence singlethread" more efficiently.
2434   DebugLoc dl = Op.getDebugLoc();
2435   if (!Subtarget->hasDataBarrier()) {
2436     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2437     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2438     // here.
2439     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2440            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2441     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2442                        DAG.getConstant(0, MVT::i32));
2443   }
2444
2445   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2446                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2447 }
2448
2449 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2450                              const ARMSubtarget *Subtarget) {
2451   // ARM pre v5TE and Thumb1 does not have preload instructions.
2452   if (!(Subtarget->isThumb2() ||
2453         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2454     // Just preserve the chain.
2455     return Op.getOperand(0);
2456
2457   DebugLoc dl = Op.getDebugLoc();
2458   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2459   if (!isRead &&
2460       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2461     // ARMv7 with MP extension has PLDW.
2462     return Op.getOperand(0);
2463
2464   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2465   if (Subtarget->isThumb()) {
2466     // Invert the bits.
2467     isRead = ~isRead & 1;
2468     isData = ~isData & 1;
2469   }
2470
2471   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2472                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2473                      DAG.getConstant(isData, MVT::i32));
2474 }
2475
2476 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2477   MachineFunction &MF = DAG.getMachineFunction();
2478   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2479
2480   // vastart just stores the address of the VarArgsFrameIndex slot into the
2481   // memory location argument.
2482   DebugLoc dl = Op.getDebugLoc();
2483   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2484   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2485   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2486   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2487                       MachinePointerInfo(SV), false, false, 0);
2488 }
2489
2490 SDValue
2491 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2492                                         SDValue &Root, SelectionDAG &DAG,
2493                                         DebugLoc dl) const {
2494   MachineFunction &MF = DAG.getMachineFunction();
2495   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2496
2497   const TargetRegisterClass *RC;
2498   if (AFI->isThumb1OnlyFunction())
2499     RC = &ARM::tGPRRegClass;
2500   else
2501     RC = &ARM::GPRRegClass;
2502
2503   // Transform the arguments stored in physical registers into virtual ones.
2504   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2505   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2506
2507   SDValue ArgValue2;
2508   if (NextVA.isMemLoc()) {
2509     MachineFrameInfo *MFI = MF.getFrameInfo();
2510     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2511
2512     // Create load node to retrieve arguments from the stack.
2513     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2514     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2515                             MachinePointerInfo::getFixedStack(FI),
2516                             false, false, false, 0);
2517   } else {
2518     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2519     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2520   }
2521
2522   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2523 }
2524
2525 void
2526 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2527                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2528   const {
2529   unsigned NumGPRs;
2530   if (CCInfo.isFirstByValRegValid())
2531     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2532   else {
2533     unsigned int firstUnalloced;
2534     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2535                                                 sizeof(GPRArgRegs) /
2536                                                 sizeof(GPRArgRegs[0]));
2537     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2538   }
2539
2540   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2541   VARegSize = NumGPRs * 4;
2542   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2543 }
2544
2545 // The remaining GPRs hold either the beginning of variable-argument
2546 // data, or the beginning of an aggregate passed by value (usuall
2547 // byval).  Either way, we allocate stack slots adjacent to the data
2548 // provided by our caller, and store the unallocated registers there.
2549 // If this is a variadic function, the va_list pointer will begin with
2550 // these values; otherwise, this reassembles a (byval) structure that
2551 // was split between registers and memory.
2552 void
2553 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2554                                         DebugLoc dl, SDValue &Chain,
2555                                         const Value *OrigArg,
2556                                         unsigned OffsetFromOrigArg,
2557                                         unsigned ArgOffset,
2558                                         bool ForceMutable) const {
2559   MachineFunction &MF = DAG.getMachineFunction();
2560   MachineFrameInfo *MFI = MF.getFrameInfo();
2561   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2562   unsigned firstRegToSaveIndex;
2563   if (CCInfo.isFirstByValRegValid())
2564     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2565   else {
2566     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2567       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2568   }
2569
2570   unsigned VARegSize, VARegSaveSize;
2571   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2572   if (VARegSaveSize) {
2573     // If this function is vararg, store any remaining integer argument regs
2574     // to their spots on the stack so that they may be loaded by deferencing
2575     // the result of va_next.
2576     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2577     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2578                                                      ArgOffset + VARegSaveSize
2579                                                      - VARegSize,
2580                                                      false));
2581     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2582                                     getPointerTy());
2583
2584     SmallVector<SDValue, 4> MemOps;
2585     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2586       const TargetRegisterClass *RC;
2587       if (AFI->isThumb1OnlyFunction())
2588         RC = &ARM::tGPRRegClass;
2589       else
2590         RC = &ARM::GPRRegClass;
2591
2592       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2593       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2594       SDValue Store =
2595         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2596                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2597                      false, false, 0);
2598       MemOps.push_back(Store);
2599       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2600                         DAG.getConstant(4, getPointerTy()));
2601     }
2602     if (!MemOps.empty())
2603       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2604                           &MemOps[0], MemOps.size());
2605   } else
2606     // This will point to the next argument passed via stack.
2607     AFI->setVarArgsFrameIndex(
2608         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2609 }
2610
2611 SDValue
2612 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2613                                         CallingConv::ID CallConv, bool isVarArg,
2614                                         const SmallVectorImpl<ISD::InputArg>
2615                                           &Ins,
2616                                         DebugLoc dl, SelectionDAG &DAG,
2617                                         SmallVectorImpl<SDValue> &InVals)
2618                                           const {
2619   MachineFunction &MF = DAG.getMachineFunction();
2620   MachineFrameInfo *MFI = MF.getFrameInfo();
2621
2622   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2623
2624   // Assign locations to all of the incoming arguments.
2625   SmallVector<CCValAssign, 16> ArgLocs;
2626   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2627                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2628   CCInfo.AnalyzeFormalArguments(Ins,
2629                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2630                                                   isVarArg));
2631   
2632   SmallVector<SDValue, 16> ArgValues;
2633   int lastInsIndex = -1;
2634   SDValue ArgValue;
2635   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2636   unsigned CurArgIdx = 0;
2637   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2638     CCValAssign &VA = ArgLocs[i];
2639     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2640     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2641     // Arguments stored in registers.
2642     if (VA.isRegLoc()) {
2643       EVT RegVT = VA.getLocVT();
2644
2645       if (VA.needsCustom()) {
2646         // f64 and vector types are split up into multiple registers or
2647         // combinations of registers and stack slots.
2648         if (VA.getLocVT() == MVT::v2f64) {
2649           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2650                                                    Chain, DAG, dl);
2651           VA = ArgLocs[++i]; // skip ahead to next loc
2652           SDValue ArgValue2;
2653           if (VA.isMemLoc()) {
2654             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2655             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2656             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2657                                     MachinePointerInfo::getFixedStack(FI),
2658                                     false, false, false, 0);
2659           } else {
2660             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2661                                              Chain, DAG, dl);
2662           }
2663           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2664           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2665                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2666           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2667                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2668         } else
2669           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2670
2671       } else {
2672         const TargetRegisterClass *RC;
2673
2674         if (RegVT == MVT::f32)
2675           RC = &ARM::SPRRegClass;
2676         else if (RegVT == MVT::f64)
2677           RC = &ARM::DPRRegClass;
2678         else if (RegVT == MVT::v2f64)
2679           RC = &ARM::QPRRegClass;
2680         else if (RegVT == MVT::i32)
2681           RC = AFI->isThumb1OnlyFunction() ?
2682             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2683             (const TargetRegisterClass*)&ARM::GPRRegClass;
2684         else
2685           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2686
2687         // Transform the arguments in physical registers into virtual ones.
2688         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2689         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2690       }
2691
2692       // If this is an 8 or 16-bit value, it is really passed promoted
2693       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2694       // truncate to the right size.
2695       switch (VA.getLocInfo()) {
2696       default: llvm_unreachable("Unknown loc info!");
2697       case CCValAssign::Full: break;
2698       case CCValAssign::BCvt:
2699         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2700         break;
2701       case CCValAssign::SExt:
2702         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2703                                DAG.getValueType(VA.getValVT()));
2704         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2705         break;
2706       case CCValAssign::ZExt:
2707         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2708                                DAG.getValueType(VA.getValVT()));
2709         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2710         break;
2711       }
2712
2713       InVals.push_back(ArgValue);
2714
2715     } else { // VA.isRegLoc()
2716
2717       // sanity check
2718       assert(VA.isMemLoc());
2719       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2720
2721       int index = ArgLocs[i].getValNo();
2722
2723       // Some Ins[] entries become multiple ArgLoc[] entries.
2724       // Process them only once.
2725       if (index != lastInsIndex)
2726         {
2727           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2728           // FIXME: For now, all byval parameter objects are marked mutable.
2729           // This can be changed with more analysis.
2730           // In case of tail call optimization mark all arguments mutable.
2731           // Since they could be overwritten by lowering of arguments in case of
2732           // a tail call.
2733           if (Flags.isByVal()) {
2734             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2735             if (!AFI->getVarArgsFrameIndex()) {
2736               VarArgStyleRegisters(CCInfo, DAG,
2737                                    dl, Chain, CurOrigArg,
2738                                    Ins[VA.getValNo()].PartOffset,
2739                                    VA.getLocMemOffset(),
2740                                    true /*force mutable frames*/);
2741               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2742               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2743             } else {
2744               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2745                                               VA.getLocMemOffset(), false);
2746               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2747             }
2748           } else {
2749             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2750                                             VA.getLocMemOffset(), true);
2751
2752             // Create load nodes to retrieve arguments from the stack.
2753             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2754             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2755                                          MachinePointerInfo::getFixedStack(FI),
2756                                          false, false, false, 0));
2757           }
2758           lastInsIndex = index;
2759         }
2760     }
2761   }
2762
2763   // varargs
2764   if (isVarArg)
2765     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2766                          CCInfo.getNextStackOffset());
2767
2768   return Chain;
2769 }
2770
2771 /// isFloatingPointZero - Return true if this is +0.0.
2772 static bool isFloatingPointZero(SDValue Op) {
2773   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2774     return CFP->getValueAPF().isPosZero();
2775   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2776     // Maybe this has already been legalized into the constant pool?
2777     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2778       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2779       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2780         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2781           return CFP->getValueAPF().isPosZero();
2782     }
2783   }
2784   return false;
2785 }
2786
2787 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2788 /// the given operands.
2789 SDValue
2790 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2791                              SDValue &ARMcc, SelectionDAG &DAG,
2792                              DebugLoc dl) const {
2793   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2794     unsigned C = RHSC->getZExtValue();
2795     if (!isLegalICmpImmediate(C)) {
2796       // Constant does not fit, try adjusting it by one?
2797       switch (CC) {
2798       default: break;
2799       case ISD::SETLT:
2800       case ISD::SETGE:
2801         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2802           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2803           RHS = DAG.getConstant(C-1, MVT::i32);
2804         }
2805         break;
2806       case ISD::SETULT:
2807       case ISD::SETUGE:
2808         if (C != 0 && isLegalICmpImmediate(C-1)) {
2809           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2810           RHS = DAG.getConstant(C-1, MVT::i32);
2811         }
2812         break;
2813       case ISD::SETLE:
2814       case ISD::SETGT:
2815         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2816           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2817           RHS = DAG.getConstant(C+1, MVT::i32);
2818         }
2819         break;
2820       case ISD::SETULE:
2821       case ISD::SETUGT:
2822         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2823           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2824           RHS = DAG.getConstant(C+1, MVT::i32);
2825         }
2826         break;
2827       }
2828     }
2829   }
2830
2831   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2832   ARMISD::NodeType CompareType;
2833   switch (CondCode) {
2834   default:
2835     CompareType = ARMISD::CMP;
2836     break;
2837   case ARMCC::EQ:
2838   case ARMCC::NE:
2839     // Uses only Z Flag
2840     CompareType = ARMISD::CMPZ;
2841     break;
2842   }
2843   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2844   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2845 }
2846
2847 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2848 SDValue
2849 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2850                              DebugLoc dl) const {
2851   SDValue Cmp;
2852   if (!isFloatingPointZero(RHS))
2853     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2854   else
2855     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2856   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2857 }
2858
2859 /// duplicateCmp - Glue values can have only one use, so this function
2860 /// duplicates a comparison node.
2861 SDValue
2862 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2863   unsigned Opc = Cmp.getOpcode();
2864   DebugLoc DL = Cmp.getDebugLoc();
2865   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2866     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2867
2868   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2869   Cmp = Cmp.getOperand(0);
2870   Opc = Cmp.getOpcode();
2871   if (Opc == ARMISD::CMPFP)
2872     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2873   else {
2874     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2875     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2876   }
2877   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2878 }
2879
2880 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2881   SDValue Cond = Op.getOperand(0);
2882   SDValue SelectTrue = Op.getOperand(1);
2883   SDValue SelectFalse = Op.getOperand(2);
2884   DebugLoc dl = Op.getDebugLoc();
2885
2886   // Convert:
2887   //
2888   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2889   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2890   //
2891   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2892     const ConstantSDNode *CMOVTrue =
2893       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2894     const ConstantSDNode *CMOVFalse =
2895       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2896
2897     if (CMOVTrue && CMOVFalse) {
2898       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2899       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2900
2901       SDValue True;
2902       SDValue False;
2903       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2904         True = SelectTrue;
2905         False = SelectFalse;
2906       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2907         True = SelectFalse;
2908         False = SelectTrue;
2909       }
2910
2911       if (True.getNode() && False.getNode()) {
2912         EVT VT = Op.getValueType();
2913         SDValue ARMcc = Cond.getOperand(2);
2914         SDValue CCR = Cond.getOperand(3);
2915         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2916         assert(True.getValueType() == VT);
2917         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2918       }
2919     }
2920   }
2921
2922   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2923   // undefined bits before doing a full-word comparison with zero.
2924   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2925                      DAG.getConstant(1, Cond.getValueType()));
2926
2927   return DAG.getSelectCC(dl, Cond,
2928                          DAG.getConstant(0, Cond.getValueType()),
2929                          SelectTrue, SelectFalse, ISD::SETNE);
2930 }
2931
2932 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2933   EVT VT = Op.getValueType();
2934   SDValue LHS = Op.getOperand(0);
2935   SDValue RHS = Op.getOperand(1);
2936   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2937   SDValue TrueVal = Op.getOperand(2);
2938   SDValue FalseVal = Op.getOperand(3);
2939   DebugLoc dl = Op.getDebugLoc();
2940
2941   if (LHS.getValueType() == MVT::i32) {
2942     SDValue ARMcc;
2943     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2944     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2945     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2946   }
2947
2948   ARMCC::CondCodes CondCode, CondCode2;
2949   FPCCToARMCC(CC, CondCode, CondCode2);
2950
2951   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2952   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2953   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2954   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2955                                ARMcc, CCR, Cmp);
2956   if (CondCode2 != ARMCC::AL) {
2957     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2958     // FIXME: Needs another CMP because flag can have but one use.
2959     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2960     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2961                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2962   }
2963   return Result;
2964 }
2965
2966 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2967 /// to morph to an integer compare sequence.
2968 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2969                            const ARMSubtarget *Subtarget) {
2970   SDNode *N = Op.getNode();
2971   if (!N->hasOneUse())
2972     // Otherwise it requires moving the value from fp to integer registers.
2973     return false;
2974   if (!N->getNumValues())
2975     return false;
2976   EVT VT = Op.getValueType();
2977   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2978     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2979     // vmrs are very slow, e.g. cortex-a8.
2980     return false;
2981
2982   if (isFloatingPointZero(Op)) {
2983     SeenZero = true;
2984     return true;
2985   }
2986   return ISD::isNormalLoad(N);
2987 }
2988
2989 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2990   if (isFloatingPointZero(Op))
2991     return DAG.getConstant(0, MVT::i32);
2992
2993   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2994     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2995                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2996                        Ld->isVolatile(), Ld->isNonTemporal(),
2997                        Ld->isInvariant(), Ld->getAlignment());
2998
2999   llvm_unreachable("Unknown VFP cmp argument!");
3000 }
3001
3002 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3003                            SDValue &RetVal1, SDValue &RetVal2) {
3004   if (isFloatingPointZero(Op)) {
3005     RetVal1 = DAG.getConstant(0, MVT::i32);
3006     RetVal2 = DAG.getConstant(0, MVT::i32);
3007     return;
3008   }
3009
3010   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3011     SDValue Ptr = Ld->getBasePtr();
3012     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3013                           Ld->getChain(), Ptr,
3014                           Ld->getPointerInfo(),
3015                           Ld->isVolatile(), Ld->isNonTemporal(),
3016                           Ld->isInvariant(), Ld->getAlignment());
3017
3018     EVT PtrType = Ptr.getValueType();
3019     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3020     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3021                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3022     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3023                           Ld->getChain(), NewPtr,
3024                           Ld->getPointerInfo().getWithOffset(4),
3025                           Ld->isVolatile(), Ld->isNonTemporal(),
3026                           Ld->isInvariant(), NewAlign);
3027     return;
3028   }
3029
3030   llvm_unreachable("Unknown VFP cmp argument!");
3031 }
3032
3033 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3034 /// f32 and even f64 comparisons to integer ones.
3035 SDValue
3036 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3037   SDValue Chain = Op.getOperand(0);
3038   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3039   SDValue LHS = Op.getOperand(2);
3040   SDValue RHS = Op.getOperand(3);
3041   SDValue Dest = Op.getOperand(4);
3042   DebugLoc dl = Op.getDebugLoc();
3043
3044   bool LHSSeenZero = false;
3045   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3046   bool RHSSeenZero = false;
3047   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3048   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3049     // If unsafe fp math optimization is enabled and there are no other uses of
3050     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3051     // to an integer comparison.
3052     if (CC == ISD::SETOEQ)
3053       CC = ISD::SETEQ;
3054     else if (CC == ISD::SETUNE)
3055       CC = ISD::SETNE;
3056
3057     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3058     SDValue ARMcc;
3059     if (LHS.getValueType() == MVT::f32) {
3060       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3061                         bitcastf32Toi32(LHS, DAG), Mask);
3062       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3063                         bitcastf32Toi32(RHS, DAG), Mask);
3064       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3065       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3066       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3067                          Chain, Dest, ARMcc, CCR, Cmp);
3068     }
3069
3070     SDValue LHS1, LHS2;
3071     SDValue RHS1, RHS2;
3072     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3073     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3074     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3075     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3076     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3077     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3078     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3079     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3080     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3081   }
3082
3083   return SDValue();
3084 }
3085
3086 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3087   SDValue Chain = Op.getOperand(0);
3088   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3089   SDValue LHS = Op.getOperand(2);
3090   SDValue RHS = Op.getOperand(3);
3091   SDValue Dest = Op.getOperand(4);
3092   DebugLoc dl = Op.getDebugLoc();
3093
3094   if (LHS.getValueType() == MVT::i32) {
3095     SDValue ARMcc;
3096     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3097     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3098     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3099                        Chain, Dest, ARMcc, CCR, Cmp);
3100   }
3101
3102   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3103
3104   if (getTargetMachine().Options.UnsafeFPMath &&
3105       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3106        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3107     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3108     if (Result.getNode())
3109       return Result;
3110   }
3111
3112   ARMCC::CondCodes CondCode, CondCode2;
3113   FPCCToARMCC(CC, CondCode, CondCode2);
3114
3115   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3116   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3117   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3118   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3119   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3120   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3121   if (CondCode2 != ARMCC::AL) {
3122     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3123     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3124     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3125   }
3126   return Res;
3127 }
3128
3129 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3130   SDValue Chain = Op.getOperand(0);
3131   SDValue Table = Op.getOperand(1);
3132   SDValue Index = Op.getOperand(2);
3133   DebugLoc dl = Op.getDebugLoc();
3134
3135   EVT PTy = getPointerTy();
3136   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3137   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3138   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3139   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3140   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3141   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3142   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3143   if (Subtarget->isThumb2()) {
3144     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3145     // which does another jump to the destination. This also makes it easier
3146     // to translate it to TBB / TBH later.
3147     // FIXME: This might not work if the function is extremely large.
3148     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3149                        Addr, Op.getOperand(2), JTI, UId);
3150   }
3151   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3152     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3153                        MachinePointerInfo::getJumpTable(),
3154                        false, false, false, 0);
3155     Chain = Addr.getValue(1);
3156     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3157     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3158   } else {
3159     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3160                        MachinePointerInfo::getJumpTable(),
3161                        false, false, false, 0);
3162     Chain = Addr.getValue(1);
3163     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3164   }
3165 }
3166
3167 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3168   EVT VT = Op.getValueType();
3169   DebugLoc dl = Op.getDebugLoc();
3170
3171   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3172     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3173       return Op;
3174     return DAG.UnrollVectorOp(Op.getNode());
3175   }
3176
3177   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3178          "Invalid type for custom lowering!");
3179   if (VT != MVT::v4i16)
3180     return DAG.UnrollVectorOp(Op.getNode());
3181
3182   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3183   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3184 }
3185
3186 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3187   EVT VT = Op.getValueType();
3188   if (VT.isVector())
3189     return LowerVectorFP_TO_INT(Op, DAG);
3190
3191   DebugLoc dl = Op.getDebugLoc();
3192   unsigned Opc;
3193
3194   switch (Op.getOpcode()) {
3195   default: llvm_unreachable("Invalid opcode!");
3196   case ISD::FP_TO_SINT:
3197     Opc = ARMISD::FTOSI;
3198     break;
3199   case ISD::FP_TO_UINT:
3200     Opc = ARMISD::FTOUI;
3201     break;
3202   }
3203   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3204   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3205 }
3206
3207 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3208   EVT VT = Op.getValueType();
3209   DebugLoc dl = Op.getDebugLoc();
3210
3211   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3212     if (VT.getVectorElementType() == MVT::f32)
3213       return Op;
3214     return DAG.UnrollVectorOp(Op.getNode());
3215   }
3216
3217   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3218          "Invalid type for custom lowering!");
3219   if (VT != MVT::v4f32)
3220     return DAG.UnrollVectorOp(Op.getNode());
3221
3222   unsigned CastOpc;
3223   unsigned Opc;
3224   switch (Op.getOpcode()) {
3225   default: llvm_unreachable("Invalid opcode!");
3226   case ISD::SINT_TO_FP:
3227     CastOpc = ISD::SIGN_EXTEND;
3228     Opc = ISD::SINT_TO_FP;
3229     break;
3230   case ISD::UINT_TO_FP:
3231     CastOpc = ISD::ZERO_EXTEND;
3232     Opc = ISD::UINT_TO_FP;
3233     break;
3234   }
3235
3236   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3237   return DAG.getNode(Opc, dl, VT, Op);
3238 }
3239
3240 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3241   EVT VT = Op.getValueType();
3242   if (VT.isVector())
3243     return LowerVectorINT_TO_FP(Op, DAG);
3244
3245   DebugLoc dl = Op.getDebugLoc();
3246   unsigned Opc;
3247
3248   switch (Op.getOpcode()) {
3249   default: llvm_unreachable("Invalid opcode!");
3250   case ISD::SINT_TO_FP:
3251     Opc = ARMISD::SITOF;
3252     break;
3253   case ISD::UINT_TO_FP:
3254     Opc = ARMISD::UITOF;
3255     break;
3256   }
3257
3258   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3259   return DAG.getNode(Opc, dl, VT, Op);
3260 }
3261
3262 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3263   // Implement fcopysign with a fabs and a conditional fneg.
3264   SDValue Tmp0 = Op.getOperand(0);
3265   SDValue Tmp1 = Op.getOperand(1);
3266   DebugLoc dl = Op.getDebugLoc();
3267   EVT VT = Op.getValueType();
3268   EVT SrcVT = Tmp1.getValueType();
3269   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3270     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3271   bool UseNEON = !InGPR && Subtarget->hasNEON();
3272
3273   if (UseNEON) {
3274     // Use VBSL to copy the sign bit.
3275     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3276     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3277                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3278     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3279     if (VT == MVT::f64)
3280       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3281                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3282                          DAG.getConstant(32, MVT::i32));
3283     else /*if (VT == MVT::f32)*/
3284       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3285     if (SrcVT == MVT::f32) {
3286       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3287       if (VT == MVT::f64)
3288         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3289                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3290                            DAG.getConstant(32, MVT::i32));
3291     } else if (VT == MVT::f32)
3292       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3293                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3294                          DAG.getConstant(32, MVT::i32));
3295     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3296     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3297
3298     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3299                                             MVT::i32);
3300     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3301     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3302                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3303
3304     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3305                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3306                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3307     if (VT == MVT::f32) {
3308       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3309       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3310                         DAG.getConstant(0, MVT::i32));
3311     } else {
3312       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3313     }
3314
3315     return Res;
3316   }
3317
3318   // Bitcast operand 1 to i32.
3319   if (SrcVT == MVT::f64)
3320     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3321                        &Tmp1, 1).getValue(1);
3322   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3323
3324   // Or in the signbit with integer operations.
3325   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3326   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3327   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3328   if (VT == MVT::f32) {
3329     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3330                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3331     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3332                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3333   }
3334
3335   // f64: Or the high part with signbit and then combine two parts.
3336   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3337                      &Tmp0, 1);
3338   SDValue Lo = Tmp0.getValue(0);
3339   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3340   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3341   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3342 }
3343
3344 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3345   MachineFunction &MF = DAG.getMachineFunction();
3346   MachineFrameInfo *MFI = MF.getFrameInfo();
3347   MFI->setReturnAddressIsTaken(true);
3348
3349   EVT VT = Op.getValueType();
3350   DebugLoc dl = Op.getDebugLoc();
3351   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3352   if (Depth) {
3353     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3354     SDValue Offset = DAG.getConstant(4, MVT::i32);
3355     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3356                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3357                        MachinePointerInfo(), false, false, false, 0);
3358   }
3359
3360   // Return LR, which contains the return address. Mark it an implicit live-in.
3361   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3362   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3363 }
3364
3365 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3366   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3367   MFI->setFrameAddressIsTaken(true);
3368
3369   EVT VT = Op.getValueType();
3370   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3371   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3372   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3373     ? ARM::R7 : ARM::R11;
3374   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3375   while (Depth--)
3376     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3377                             MachinePointerInfo(),
3378                             false, false, false, 0);
3379   return FrameAddr;
3380 }
3381
3382 /// ExpandBITCAST - If the target supports VFP, this function is called to
3383 /// expand a bit convert where either the source or destination type is i64 to
3384 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3385 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3386 /// vectors), since the legalizer won't know what to do with that.
3387 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3389   DebugLoc dl = N->getDebugLoc();
3390   SDValue Op = N->getOperand(0);
3391
3392   // This function is only supposed to be called for i64 types, either as the
3393   // source or destination of the bit convert.
3394   EVT SrcVT = Op.getValueType();
3395   EVT DstVT = N->getValueType(0);
3396   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3397          "ExpandBITCAST called for non-i64 type");
3398
3399   // Turn i64->f64 into VMOVDRR.
3400   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3401     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3402                              DAG.getConstant(0, MVT::i32));
3403     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3404                              DAG.getConstant(1, MVT::i32));
3405     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3406                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3407   }
3408
3409   // Turn f64->i64 into VMOVRRD.
3410   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3411     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3412                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3413     // Merge the pieces into a single i64 value.
3414     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3415   }
3416
3417   return SDValue();
3418 }
3419
3420 /// getZeroVector - Returns a vector of specified type with all zero elements.
3421 /// Zero vectors are used to represent vector negation and in those cases
3422 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3423 /// not support i64 elements, so sometimes the zero vectors will need to be
3424 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3425 /// zero vector.
3426 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3427   assert(VT.isVector() && "Expected a vector type");
3428   // The canonical modified immediate encoding of a zero vector is....0!
3429   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3430   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3431   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3432   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3433 }
3434
3435 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3436 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3437 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3438                                                 SelectionDAG &DAG) const {
3439   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3440   EVT VT = Op.getValueType();
3441   unsigned VTBits = VT.getSizeInBits();
3442   DebugLoc dl = Op.getDebugLoc();
3443   SDValue ShOpLo = Op.getOperand(0);
3444   SDValue ShOpHi = Op.getOperand(1);
3445   SDValue ShAmt  = Op.getOperand(2);
3446   SDValue ARMcc;
3447   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3448
3449   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3450
3451   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3452                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3453   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3454   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3455                                    DAG.getConstant(VTBits, MVT::i32));
3456   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3457   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3458   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3459
3460   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3461   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3462                           ARMcc, DAG, dl);
3463   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3464   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3465                            CCR, Cmp);
3466
3467   SDValue Ops[2] = { Lo, Hi };
3468   return DAG.getMergeValues(Ops, 2, dl);
3469 }
3470
3471 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3472 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3473 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3474                                                SelectionDAG &DAG) const {
3475   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3476   EVT VT = Op.getValueType();
3477   unsigned VTBits = VT.getSizeInBits();
3478   DebugLoc dl = Op.getDebugLoc();
3479   SDValue ShOpLo = Op.getOperand(0);
3480   SDValue ShOpHi = Op.getOperand(1);
3481   SDValue ShAmt  = Op.getOperand(2);
3482   SDValue ARMcc;
3483
3484   assert(Op.getOpcode() == ISD::SHL_PARTS);
3485   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3486                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3487   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3488   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3489                                    DAG.getConstant(VTBits, MVT::i32));
3490   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3491   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3492
3493   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3494   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3495   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3496                           ARMcc, DAG, dl);
3497   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3498   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3499                            CCR, Cmp);
3500
3501   SDValue Ops[2] = { Lo, Hi };
3502   return DAG.getMergeValues(Ops, 2, dl);
3503 }
3504
3505 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3506                                             SelectionDAG &DAG) const {
3507   // The rounding mode is in bits 23:22 of the FPSCR.
3508   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3509   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3510   // so that the shift + and get folded into a bitfield extract.
3511   DebugLoc dl = Op.getDebugLoc();
3512   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3513                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3514                                               MVT::i32));
3515   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3516                                   DAG.getConstant(1U << 22, MVT::i32));
3517   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3518                               DAG.getConstant(22, MVT::i32));
3519   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3520                      DAG.getConstant(3, MVT::i32));
3521 }
3522
3523 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3524                          const ARMSubtarget *ST) {
3525   EVT VT = N->getValueType(0);
3526   DebugLoc dl = N->getDebugLoc();
3527
3528   if (!ST->hasV6T2Ops())
3529     return SDValue();
3530
3531   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3532   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3533 }
3534
3535 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3536                           const ARMSubtarget *ST) {
3537   EVT VT = N->getValueType(0);
3538   DebugLoc dl = N->getDebugLoc();
3539
3540   if (!VT.isVector())
3541     return SDValue();
3542
3543   // Lower vector shifts on NEON to use VSHL.
3544   assert(ST->hasNEON() && "unexpected vector shift");
3545
3546   // Left shifts translate directly to the vshiftu intrinsic.
3547   if (N->getOpcode() == ISD::SHL)
3548     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3549                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3550                        N->getOperand(0), N->getOperand(1));
3551
3552   assert((N->getOpcode() == ISD::SRA ||
3553           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3554
3555   // NEON uses the same intrinsics for both left and right shifts.  For
3556   // right shifts, the shift amounts are negative, so negate the vector of
3557   // shift amounts.
3558   EVT ShiftVT = N->getOperand(1).getValueType();
3559   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3560                                      getZeroVector(ShiftVT, DAG, dl),
3561                                      N->getOperand(1));
3562   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3563                              Intrinsic::arm_neon_vshifts :
3564                              Intrinsic::arm_neon_vshiftu);
3565   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3566                      DAG.getConstant(vshiftInt, MVT::i32),
3567                      N->getOperand(0), NegatedCount);
3568 }
3569
3570 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3571                                 const ARMSubtarget *ST) {
3572   EVT VT = N->getValueType(0);
3573   DebugLoc dl = N->getDebugLoc();
3574
3575   // We can get here for a node like i32 = ISD::SHL i32, i64
3576   if (VT != MVT::i64)
3577     return SDValue();
3578
3579   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3580          "Unknown shift to lower!");
3581
3582   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3583   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3584       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3585     return SDValue();
3586
3587   // If we are in thumb mode, we don't have RRX.
3588   if (ST->isThumb1Only()) return SDValue();
3589
3590   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3591   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3592                            DAG.getConstant(0, MVT::i32));
3593   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3594                            DAG.getConstant(1, MVT::i32));
3595
3596   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3597   // captures the result into a carry flag.
3598   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3599   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3600
3601   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3602   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3603
3604   // Merge the pieces into a single i64 value.
3605  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3606 }
3607
3608 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3609   SDValue TmpOp0, TmpOp1;
3610   bool Invert = false;
3611   bool Swap = false;
3612   unsigned Opc = 0;
3613
3614   SDValue Op0 = Op.getOperand(0);
3615   SDValue Op1 = Op.getOperand(1);
3616   SDValue CC = Op.getOperand(2);
3617   EVT VT = Op.getValueType();
3618   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3619   DebugLoc dl = Op.getDebugLoc();
3620
3621   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3622     switch (SetCCOpcode) {
3623     default: llvm_unreachable("Illegal FP comparison");
3624     case ISD::SETUNE:
3625     case ISD::SETNE:  Invert = true; // Fallthrough
3626     case ISD::SETOEQ:
3627     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3628     case ISD::SETOLT:
3629     case ISD::SETLT: Swap = true; // Fallthrough
3630     case ISD::SETOGT:
3631     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3632     case ISD::SETOLE:
3633     case ISD::SETLE:  Swap = true; // Fallthrough
3634     case ISD::SETOGE:
3635     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3636     case ISD::SETUGE: Swap = true; // Fallthrough
3637     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3638     case ISD::SETUGT: Swap = true; // Fallthrough
3639     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3640     case ISD::SETUEQ: Invert = true; // Fallthrough
3641     case ISD::SETONE:
3642       // Expand this to (OLT | OGT).
3643       TmpOp0 = Op0;
3644       TmpOp1 = Op1;
3645       Opc = ISD::OR;
3646       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3647       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3648       break;
3649     case ISD::SETUO: Invert = true; // Fallthrough
3650     case ISD::SETO:
3651       // Expand this to (OLT | OGE).
3652       TmpOp0 = Op0;
3653       TmpOp1 = Op1;
3654       Opc = ISD::OR;
3655       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3656       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3657       break;
3658     }
3659   } else {
3660     // Integer comparisons.
3661     switch (SetCCOpcode) {
3662     default: llvm_unreachable("Illegal integer comparison");
3663     case ISD::SETNE:  Invert = true;
3664     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3665     case ISD::SETLT:  Swap = true;
3666     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3667     case ISD::SETLE:  Swap = true;
3668     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3669     case ISD::SETULT: Swap = true;
3670     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3671     case ISD::SETULE: Swap = true;
3672     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3673     }
3674
3675     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3676     if (Opc == ARMISD::VCEQ) {
3677
3678       SDValue AndOp;
3679       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3680         AndOp = Op0;
3681       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3682         AndOp = Op1;
3683
3684       // Ignore bitconvert.
3685       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3686         AndOp = AndOp.getOperand(0);
3687
3688       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3689         Opc = ARMISD::VTST;
3690         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3691         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3692         Invert = !Invert;
3693       }
3694     }
3695   }
3696
3697   if (Swap)
3698     std::swap(Op0, Op1);
3699
3700   // If one of the operands is a constant vector zero, attempt to fold the
3701   // comparison to a specialized compare-against-zero form.
3702   SDValue SingleOp;
3703   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3704     SingleOp = Op0;
3705   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3706     if (Opc == ARMISD::VCGE)
3707       Opc = ARMISD::VCLEZ;
3708     else if (Opc == ARMISD::VCGT)
3709       Opc = ARMISD::VCLTZ;
3710     SingleOp = Op1;
3711   }
3712
3713   SDValue Result;
3714   if (SingleOp.getNode()) {
3715     switch (Opc) {
3716     case ARMISD::VCEQ:
3717       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3718     case ARMISD::VCGE:
3719       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3720     case ARMISD::VCLEZ:
3721       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3722     case ARMISD::VCGT:
3723       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3724     case ARMISD::VCLTZ:
3725       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3726     default:
3727       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3728     }
3729   } else {
3730      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3731   }
3732
3733   if (Invert)
3734     Result = DAG.getNOT(dl, Result, VT);
3735
3736   return Result;
3737 }
3738
3739 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3740 /// valid vector constant for a NEON instruction with a "modified immediate"
3741 /// operand (e.g., VMOV).  If so, return the encoded value.
3742 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3743                                  unsigned SplatBitSize, SelectionDAG &DAG,
3744                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3745   unsigned OpCmode, Imm;
3746
3747   // SplatBitSize is set to the smallest size that splats the vector, so a
3748   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3749   // immediate instructions others than VMOV do not support the 8-bit encoding
3750   // of a zero vector, and the default encoding of zero is supposed to be the
3751   // 32-bit version.
3752   if (SplatBits == 0)
3753     SplatBitSize = 32;
3754
3755   switch (SplatBitSize) {
3756   case 8:
3757     if (type != VMOVModImm)
3758       return SDValue();
3759     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3760     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3761     OpCmode = 0xe;
3762     Imm = SplatBits;
3763     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3764     break;
3765
3766   case 16:
3767     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3768     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3769     if ((SplatBits & ~0xff) == 0) {
3770       // Value = 0x00nn: Op=x, Cmode=100x.
3771       OpCmode = 0x8;
3772       Imm = SplatBits;
3773       break;
3774     }
3775     if ((SplatBits & ~0xff00) == 0) {
3776       // Value = 0xnn00: Op=x, Cmode=101x.
3777       OpCmode = 0xa;
3778       Imm = SplatBits >> 8;
3779       break;
3780     }
3781     return SDValue();
3782
3783   case 32:
3784     // NEON's 32-bit VMOV supports splat values where:
3785     // * only one byte is nonzero, or
3786     // * the least significant byte is 0xff and the second byte is nonzero, or
3787     // * the least significant 2 bytes are 0xff and the third is nonzero.
3788     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3789     if ((SplatBits & ~0xff) == 0) {
3790       // Value = 0x000000nn: Op=x, Cmode=000x.
3791       OpCmode = 0;
3792       Imm = SplatBits;
3793       break;
3794     }
3795     if ((SplatBits & ~0xff00) == 0) {
3796       // Value = 0x0000nn00: Op=x, Cmode=001x.
3797       OpCmode = 0x2;
3798       Imm = SplatBits >> 8;
3799       break;
3800     }
3801     if ((SplatBits & ~0xff0000) == 0) {
3802       // Value = 0x00nn0000: Op=x, Cmode=010x.
3803       OpCmode = 0x4;
3804       Imm = SplatBits >> 16;
3805       break;
3806     }
3807     if ((SplatBits & ~0xff000000) == 0) {
3808       // Value = 0xnn000000: Op=x, Cmode=011x.
3809       OpCmode = 0x6;
3810       Imm = SplatBits >> 24;
3811       break;
3812     }
3813
3814     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3815     if (type == OtherModImm) return SDValue();
3816
3817     if ((SplatBits & ~0xffff) == 0 &&
3818         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3819       // Value = 0x0000nnff: Op=x, Cmode=1100.
3820       OpCmode = 0xc;
3821       Imm = SplatBits >> 8;
3822       SplatBits |= 0xff;
3823       break;
3824     }
3825
3826     if ((SplatBits & ~0xffffff) == 0 &&
3827         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3828       // Value = 0x00nnffff: Op=x, Cmode=1101.
3829       OpCmode = 0xd;
3830       Imm = SplatBits >> 16;
3831       SplatBits |= 0xffff;
3832       break;
3833     }
3834
3835     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3836     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3837     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3838     // and fall through here to test for a valid 64-bit splat.  But, then the
3839     // caller would also need to check and handle the change in size.
3840     return SDValue();
3841
3842   case 64: {
3843     if (type != VMOVModImm)
3844       return SDValue();
3845     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3846     uint64_t BitMask = 0xff;
3847     uint64_t Val = 0;
3848     unsigned ImmMask = 1;
3849     Imm = 0;
3850     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3851       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3852         Val |= BitMask;
3853         Imm |= ImmMask;
3854       } else if ((SplatBits & BitMask) != 0) {
3855         return SDValue();
3856       }
3857       BitMask <<= 8;
3858       ImmMask <<= 1;
3859     }
3860     // Op=1, Cmode=1110.
3861     OpCmode = 0x1e;
3862     SplatBits = Val;
3863     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3864     break;
3865   }
3866
3867   default:
3868     llvm_unreachable("unexpected size for isNEONModifiedImm");
3869   }
3870
3871   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3872   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3873 }
3874
3875 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3876                                            const ARMSubtarget *ST) const {
3877   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3878     return SDValue();
3879
3880   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3881   assert(Op.getValueType() == MVT::f32 &&
3882          "ConstantFP custom lowering should only occur for f32.");
3883
3884   // Try splatting with a VMOV.f32...
3885   APFloat FPVal = CFP->getValueAPF();
3886   int ImmVal = ARM_AM::getFP32Imm(FPVal);
3887   if (ImmVal != -1) {
3888     DebugLoc DL = Op.getDebugLoc();
3889     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3890     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3891                                       NewVal);
3892     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3893                        DAG.getConstant(0, MVT::i32));
3894   }
3895
3896   // If that fails, try a VMOV.i32
3897   EVT VMovVT;
3898   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3899   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3900                                      VMOVModImm);
3901   if (NewVal != SDValue()) {
3902     DebugLoc DL = Op.getDebugLoc();
3903     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3904                                       NewVal);
3905     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3906                                        VecConstant);
3907     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3908                        DAG.getConstant(0, MVT::i32));
3909   }
3910
3911   // Finally, try a VMVN.i32
3912   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3913                              VMVNModImm);
3914   if (NewVal != SDValue()) {
3915     DebugLoc DL = Op.getDebugLoc();
3916     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3917     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3918                                        VecConstant);
3919     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3920                        DAG.getConstant(0, MVT::i32));
3921   }
3922
3923   return SDValue();
3924 }
3925
3926 // check if an VEXT instruction can handle the shuffle mask when the
3927 // vector sources of the shuffle are the same.
3928 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3929   unsigned NumElts = VT.getVectorNumElements();
3930
3931   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3932   if (M[0] < 0)
3933     return false;
3934
3935   Imm = M[0];
3936
3937   // If this is a VEXT shuffle, the immediate value is the index of the first
3938   // element.  The other shuffle indices must be the successive elements after
3939   // the first one.
3940   unsigned ExpectedElt = Imm;
3941   for (unsigned i = 1; i < NumElts; ++i) {
3942     // Increment the expected index.  If it wraps around, just follow it
3943     // back to index zero and keep going.
3944     ++ExpectedElt;
3945     if (ExpectedElt == NumElts)
3946       ExpectedElt = 0;
3947
3948     if (M[i] < 0) continue; // ignore UNDEF indices
3949     if (ExpectedElt != static_cast<unsigned>(M[i]))
3950       return false;
3951   }
3952
3953   return true;
3954 }
3955
3956
3957 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3958                        bool &ReverseVEXT, unsigned &Imm) {
3959   unsigned NumElts = VT.getVectorNumElements();
3960   ReverseVEXT = false;
3961
3962   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3963   if (M[0] < 0)
3964     return false;
3965
3966   Imm = M[0];
3967
3968   // If this is a VEXT shuffle, the immediate value is the index of the first
3969   // element.  The other shuffle indices must be the successive elements after
3970   // the first one.
3971   unsigned ExpectedElt = Imm;
3972   for (unsigned i = 1; i < NumElts; ++i) {
3973     // Increment the expected index.  If it wraps around, it may still be
3974     // a VEXT but the source vectors must be swapped.
3975     ExpectedElt += 1;
3976     if (ExpectedElt == NumElts * 2) {
3977       ExpectedElt = 0;
3978       ReverseVEXT = true;
3979     }
3980
3981     if (M[i] < 0) continue; // ignore UNDEF indices
3982     if (ExpectedElt != static_cast<unsigned>(M[i]))
3983       return false;
3984   }
3985
3986   // Adjust the index value if the source operands will be swapped.
3987   if (ReverseVEXT)
3988     Imm -= NumElts;
3989
3990   return true;
3991 }
3992
3993 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3994 /// instruction with the specified blocksize.  (The order of the elements
3995 /// within each block of the vector is reversed.)
3996 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3997   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3998          "Only possible block sizes for VREV are: 16, 32, 64");
3999
4000   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4001   if (EltSz == 64)
4002     return false;
4003
4004   unsigned NumElts = VT.getVectorNumElements();
4005   unsigned BlockElts = M[0] + 1;
4006   // If the first shuffle index is UNDEF, be optimistic.
4007   if (M[0] < 0)
4008     BlockElts = BlockSize / EltSz;
4009
4010   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4011     return false;
4012
4013   for (unsigned i = 0; i < NumElts; ++i) {
4014     if (M[i] < 0) continue; // ignore UNDEF indices
4015     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4016       return false;
4017   }
4018
4019   return true;
4020 }
4021
4022 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4023   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4024   // range, then 0 is placed into the resulting vector. So pretty much any mask
4025   // of 8 elements can work here.
4026   return VT == MVT::v8i8 && M.size() == 8;
4027 }
4028
4029 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4030   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4031   if (EltSz == 64)
4032     return false;
4033
4034   unsigned NumElts = VT.getVectorNumElements();
4035   WhichResult = (M[0] == 0 ? 0 : 1);
4036   for (unsigned i = 0; i < NumElts; i += 2) {
4037     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4038         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4039       return false;
4040   }
4041   return true;
4042 }
4043
4044 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4045 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4046 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4047 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4048   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4049   if (EltSz == 64)
4050     return false;
4051
4052   unsigned NumElts = VT.getVectorNumElements();
4053   WhichResult = (M[0] == 0 ? 0 : 1);
4054   for (unsigned i = 0; i < NumElts; i += 2) {
4055     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4056         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4057       return false;
4058   }
4059   return true;
4060 }
4061
4062 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4063   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4064   if (EltSz == 64)
4065     return false;
4066
4067   unsigned NumElts = VT.getVectorNumElements();
4068   WhichResult = (M[0] == 0 ? 0 : 1);
4069   for (unsigned i = 0; i != NumElts; ++i) {
4070     if (M[i] < 0) continue; // ignore UNDEF indices
4071     if ((unsigned) M[i] != 2 * i + WhichResult)
4072       return false;
4073   }
4074
4075   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4076   if (VT.is64BitVector() && EltSz == 32)
4077     return false;
4078
4079   return true;
4080 }
4081
4082 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4083 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4084 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4085 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4086   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4087   if (EltSz == 64)
4088     return false;
4089
4090   unsigned Half = VT.getVectorNumElements() / 2;
4091   WhichResult = (M[0] == 0 ? 0 : 1);
4092   for (unsigned j = 0; j != 2; ++j) {
4093     unsigned Idx = WhichResult;
4094     for (unsigned i = 0; i != Half; ++i) {
4095       int MIdx = M[i + j * Half];
4096       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4097         return false;
4098       Idx += 2;
4099     }
4100   }
4101
4102   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4103   if (VT.is64BitVector() && EltSz == 32)
4104     return false;
4105
4106   return true;
4107 }
4108
4109 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4110   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4111   if (EltSz == 64)
4112     return false;
4113
4114   unsigned NumElts = VT.getVectorNumElements();
4115   WhichResult = (M[0] == 0 ? 0 : 1);
4116   unsigned Idx = WhichResult * NumElts / 2;
4117   for (unsigned i = 0; i != NumElts; i += 2) {
4118     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4119         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4120       return false;
4121     Idx += 1;
4122   }
4123
4124   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4125   if (VT.is64BitVector() && EltSz == 32)
4126     return false;
4127
4128   return true;
4129 }
4130
4131 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4132 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4133 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4134 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4135   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4136   if (EltSz == 64)
4137     return false;
4138
4139   unsigned NumElts = VT.getVectorNumElements();
4140   WhichResult = (M[0] == 0 ? 0 : 1);
4141   unsigned Idx = WhichResult * NumElts / 2;
4142   for (unsigned i = 0; i != NumElts; i += 2) {
4143     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4144         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4145       return false;
4146     Idx += 1;
4147   }
4148
4149   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4150   if (VT.is64BitVector() && EltSz == 32)
4151     return false;
4152
4153   return true;
4154 }
4155
4156 // If N is an integer constant that can be moved into a register in one
4157 // instruction, return an SDValue of such a constant (will become a MOV
4158 // instruction).  Otherwise return null.
4159 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4160                                      const ARMSubtarget *ST, DebugLoc dl) {
4161   uint64_t Val;
4162   if (!isa<ConstantSDNode>(N))
4163     return SDValue();
4164   Val = cast<ConstantSDNode>(N)->getZExtValue();
4165
4166   if (ST->isThumb1Only()) {
4167     if (Val <= 255 || ~Val <= 255)
4168       return DAG.getConstant(Val, MVT::i32);
4169   } else {
4170     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4171       return DAG.getConstant(Val, MVT::i32);
4172   }
4173   return SDValue();
4174 }
4175
4176 // If this is a case we can't handle, return null and let the default
4177 // expansion code take care of it.
4178 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4179                                              const ARMSubtarget *ST) const {
4180   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4181   DebugLoc dl = Op.getDebugLoc();
4182   EVT VT = Op.getValueType();
4183
4184   APInt SplatBits, SplatUndef;
4185   unsigned SplatBitSize;
4186   bool HasAnyUndefs;
4187   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4188     if (SplatBitSize <= 64) {
4189       // Check if an immediate VMOV works.
4190       EVT VmovVT;
4191       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4192                                       SplatUndef.getZExtValue(), SplatBitSize,
4193                                       DAG, VmovVT, VT.is128BitVector(),
4194                                       VMOVModImm);
4195       if (Val.getNode()) {
4196         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4197         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4198       }
4199
4200       // Try an immediate VMVN.
4201       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4202       Val = isNEONModifiedImm(NegatedImm,
4203                                       SplatUndef.getZExtValue(), SplatBitSize,
4204                                       DAG, VmovVT, VT.is128BitVector(),
4205                                       VMVNModImm);
4206       if (Val.getNode()) {
4207         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4208         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4209       }
4210
4211       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4212       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4213         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4214         if (ImmVal != -1) {
4215           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4216           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4217         }
4218       }
4219     }
4220   }
4221
4222   // Scan through the operands to see if only one value is used.
4223   //
4224   // As an optimisation, even if more than one value is used it may be more
4225   // profitable to splat with one value then change some lanes.
4226   //
4227   // Heuristically we decide to do this if the vector has a "dominant" value,
4228   // defined as splatted to more than half of the lanes.
4229   unsigned NumElts = VT.getVectorNumElements();
4230   bool isOnlyLowElement = true;
4231   bool usesOnlyOneValue = true;
4232   bool hasDominantValue = false;
4233   bool isConstant = true;
4234
4235   // Map of the number of times a particular SDValue appears in the
4236   // element list.
4237   DenseMap<SDValue, unsigned> ValueCounts;
4238   SDValue Value;
4239   for (unsigned i = 0; i < NumElts; ++i) {
4240     SDValue V = Op.getOperand(i);
4241     if (V.getOpcode() == ISD::UNDEF)
4242       continue;
4243     if (i > 0)
4244       isOnlyLowElement = false;
4245     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4246       isConstant = false;
4247
4248     ValueCounts.insert(std::make_pair(V, 0));
4249     unsigned &Count = ValueCounts[V];
4250     
4251     // Is this value dominant? (takes up more than half of the lanes)
4252     if (++Count > (NumElts / 2)) {
4253       hasDominantValue = true;
4254       Value = V;
4255     }
4256   }
4257   if (ValueCounts.size() != 1)
4258     usesOnlyOneValue = false;
4259   if (!Value.getNode() && ValueCounts.size() > 0)
4260     Value = ValueCounts.begin()->first;
4261
4262   if (ValueCounts.size() == 0)
4263     return DAG.getUNDEF(VT);
4264
4265   if (isOnlyLowElement)
4266     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4267
4268   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4269
4270   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4271   // i32 and try again.
4272   if (hasDominantValue && EltSize <= 32) {
4273     if (!isConstant) {
4274       SDValue N;
4275
4276       // If we are VDUPing a value that comes directly from a vector, that will
4277       // cause an unnecessary move to and from a GPR, where instead we could
4278       // just use VDUPLANE.
4279       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4280         // We need to create a new undef vector to use for the VDUPLANE if the
4281         // size of the vector from which we get the value is different than the
4282         // size of the vector that we need to create. We will insert the element
4283         // such that the register coalescer will remove unnecessary copies.
4284         if (VT != Value->getOperand(0).getValueType()) {
4285           ConstantSDNode *constIndex;
4286           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4287           assert(constIndex && "The index is not a constant!");
4288           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4289                              VT.getVectorNumElements();
4290           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4291                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4292                         Value, DAG.getConstant(index, MVT::i32)),
4293                            DAG.getConstant(index, MVT::i32));
4294         } else {
4295           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4296                         Value->getOperand(0), Value->getOperand(1));
4297         }
4298       }
4299       else
4300         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4301
4302       if (!usesOnlyOneValue) {
4303         // The dominant value was splatted as 'N', but we now have to insert
4304         // all differing elements.
4305         for (unsigned I = 0; I < NumElts; ++I) {
4306           if (Op.getOperand(I) == Value)
4307             continue;
4308           SmallVector<SDValue, 3> Ops;
4309           Ops.push_back(N);
4310           Ops.push_back(Op.getOperand(I));
4311           Ops.push_back(DAG.getConstant(I, MVT::i32));
4312           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4313         }
4314       }
4315       return N;
4316     }
4317     if (VT.getVectorElementType().isFloatingPoint()) {
4318       SmallVector<SDValue, 8> Ops;
4319       for (unsigned i = 0; i < NumElts; ++i)
4320         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4321                                   Op.getOperand(i)));
4322       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4323       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4324       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4325       if (Val.getNode())
4326         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4327     }
4328     if (usesOnlyOneValue) {
4329       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4330       if (isConstant && Val.getNode())
4331         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4332     }
4333   }
4334
4335   // If all elements are constants and the case above didn't get hit, fall back
4336   // to the default expansion, which will generate a load from the constant
4337   // pool.
4338   if (isConstant)
4339     return SDValue();
4340
4341   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4342   if (NumElts >= 4) {
4343     SDValue shuffle = ReconstructShuffle(Op, DAG);
4344     if (shuffle != SDValue())
4345       return shuffle;
4346   }
4347
4348   // Vectors with 32- or 64-bit elements can be built by directly assigning
4349   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4350   // will be legalized.
4351   if (EltSize >= 32) {
4352     // Do the expansion with floating-point types, since that is what the VFP
4353     // registers are defined to use, and since i64 is not legal.
4354     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4355     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4356     SmallVector<SDValue, 8> Ops;
4357     for (unsigned i = 0; i < NumElts; ++i)
4358       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4359     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4360     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4361   }
4362
4363   return SDValue();
4364 }
4365
4366 // Gather data to see if the operation can be modelled as a
4367 // shuffle in combination with VEXTs.
4368 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4369                                               SelectionDAG &DAG) const {
4370   DebugLoc dl = Op.getDebugLoc();
4371   EVT VT = Op.getValueType();
4372   unsigned NumElts = VT.getVectorNumElements();
4373
4374   SmallVector<SDValue, 2> SourceVecs;
4375   SmallVector<unsigned, 2> MinElts;
4376   SmallVector<unsigned, 2> MaxElts;
4377
4378   for (unsigned i = 0; i < NumElts; ++i) {
4379     SDValue V = Op.getOperand(i);
4380     if (V.getOpcode() == ISD::UNDEF)
4381       continue;
4382     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4383       // A shuffle can only come from building a vector from various
4384       // elements of other vectors.
4385       return SDValue();
4386     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4387                VT.getVectorElementType()) {
4388       // This code doesn't know how to handle shuffles where the vector
4389       // element types do not match (this happens because type legalization
4390       // promotes the return type of EXTRACT_VECTOR_ELT).
4391       // FIXME: It might be appropriate to extend this code to handle
4392       // mismatched types.
4393       return SDValue();
4394     }
4395
4396     // Record this extraction against the appropriate vector if possible...
4397     SDValue SourceVec = V.getOperand(0);
4398     // If the element number isn't a constant, we can't effectively
4399     // analyze what's going on.
4400     if (!isa<ConstantSDNode>(V.getOperand(1)))
4401       return SDValue();
4402     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4403     bool FoundSource = false;
4404     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4405       if (SourceVecs[j] == SourceVec) {
4406         if (MinElts[j] > EltNo)
4407           MinElts[j] = EltNo;
4408         if (MaxElts[j] < EltNo)
4409           MaxElts[j] = EltNo;
4410         FoundSource = true;
4411         break;
4412       }
4413     }
4414
4415     // Or record a new source if not...
4416     if (!FoundSource) {
4417       SourceVecs.push_back(SourceVec);
4418       MinElts.push_back(EltNo);
4419       MaxElts.push_back(EltNo);
4420     }
4421   }
4422
4423   // Currently only do something sane when at most two source vectors
4424   // involved.
4425   if (SourceVecs.size() > 2)
4426     return SDValue();
4427
4428   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4429   int VEXTOffsets[2] = {0, 0};
4430
4431   // This loop extracts the usage patterns of the source vectors
4432   // and prepares appropriate SDValues for a shuffle if possible.
4433   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4434     if (SourceVecs[i].getValueType() == VT) {
4435       // No VEXT necessary
4436       ShuffleSrcs[i] = SourceVecs[i];
4437       VEXTOffsets[i] = 0;
4438       continue;
4439     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4440       // It probably isn't worth padding out a smaller vector just to
4441       // break it down again in a shuffle.
4442       return SDValue();
4443     }
4444
4445     // Since only 64-bit and 128-bit vectors are legal on ARM and
4446     // we've eliminated the other cases...
4447     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4448            "unexpected vector sizes in ReconstructShuffle");
4449
4450     if (MaxElts[i] - MinElts[i] >= NumElts) {
4451       // Span too large for a VEXT to cope
4452       return SDValue();
4453     }
4454
4455     if (MinElts[i] >= NumElts) {
4456       // The extraction can just take the second half
4457       VEXTOffsets[i] = NumElts;
4458       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4459                                    SourceVecs[i],
4460                                    DAG.getIntPtrConstant(NumElts));
4461     } else if (MaxElts[i] < NumElts) {
4462       // The extraction can just take the first half
4463       VEXTOffsets[i] = 0;
4464       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4465                                    SourceVecs[i],
4466                                    DAG.getIntPtrConstant(0));
4467     } else {
4468       // An actual VEXT is needed
4469       VEXTOffsets[i] = MinElts[i];
4470       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4471                                      SourceVecs[i],
4472                                      DAG.getIntPtrConstant(0));
4473       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4474                                      SourceVecs[i],
4475                                      DAG.getIntPtrConstant(NumElts));
4476       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4477                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4478     }
4479   }
4480
4481   SmallVector<int, 8> Mask;
4482
4483   for (unsigned i = 0; i < NumElts; ++i) {
4484     SDValue Entry = Op.getOperand(i);
4485     if (Entry.getOpcode() == ISD::UNDEF) {
4486       Mask.push_back(-1);
4487       continue;
4488     }
4489
4490     SDValue ExtractVec = Entry.getOperand(0);
4491     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4492                                           .getOperand(1))->getSExtValue();
4493     if (ExtractVec == SourceVecs[0]) {
4494       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4495     } else {
4496       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4497     }
4498   }
4499
4500   // Final check before we try to produce nonsense...
4501   if (isShuffleMaskLegal(Mask, VT))
4502     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4503                                 &Mask[0]);
4504
4505   return SDValue();
4506 }
4507
4508 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4509 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4510 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4511 /// are assumed to be legal.
4512 bool
4513 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4514                                       EVT VT) const {
4515   if (VT.getVectorNumElements() == 4 &&
4516       (VT.is128BitVector() || VT.is64BitVector())) {
4517     unsigned PFIndexes[4];
4518     for (unsigned i = 0; i != 4; ++i) {
4519       if (M[i] < 0)
4520         PFIndexes[i] = 8;
4521       else
4522         PFIndexes[i] = M[i];
4523     }
4524
4525     // Compute the index in the perfect shuffle table.
4526     unsigned PFTableIndex =
4527       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4528     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4529     unsigned Cost = (PFEntry >> 30);
4530
4531     if (Cost <= 4)
4532       return true;
4533   }
4534
4535   bool ReverseVEXT;
4536   unsigned Imm, WhichResult;
4537
4538   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4539   return (EltSize >= 32 ||
4540           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4541           isVREVMask(M, VT, 64) ||
4542           isVREVMask(M, VT, 32) ||
4543           isVREVMask(M, VT, 16) ||
4544           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4545           isVTBLMask(M, VT) ||
4546           isVTRNMask(M, VT, WhichResult) ||
4547           isVUZPMask(M, VT, WhichResult) ||
4548           isVZIPMask(M, VT, WhichResult) ||
4549           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4550           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4551           isVZIP_v_undef_Mask(M, VT, WhichResult));
4552 }
4553
4554 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4555 /// the specified operations to build the shuffle.
4556 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4557                                       SDValue RHS, SelectionDAG &DAG,
4558                                       DebugLoc dl) {
4559   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4560   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4561   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4562
4563   enum {
4564     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4565     OP_VREV,
4566     OP_VDUP0,
4567     OP_VDUP1,
4568     OP_VDUP2,
4569     OP_VDUP3,
4570     OP_VEXT1,
4571     OP_VEXT2,
4572     OP_VEXT3,
4573     OP_VUZPL, // VUZP, left result
4574     OP_VUZPR, // VUZP, right result
4575     OP_VZIPL, // VZIP, left result
4576     OP_VZIPR, // VZIP, right result
4577     OP_VTRNL, // VTRN, left result
4578     OP_VTRNR  // VTRN, right result
4579   };
4580
4581   if (OpNum == OP_COPY) {
4582     if (LHSID == (1*9+2)*9+3) return LHS;
4583     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4584     return RHS;
4585   }
4586
4587   SDValue OpLHS, OpRHS;
4588   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4589   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4590   EVT VT = OpLHS.getValueType();
4591
4592   switch (OpNum) {
4593   default: llvm_unreachable("Unknown shuffle opcode!");
4594   case OP_VREV:
4595     // VREV divides the vector in half and swaps within the half.
4596     if (VT.getVectorElementType() == MVT::i32 ||
4597         VT.getVectorElementType() == MVT::f32)
4598       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4599     // vrev <4 x i16> -> VREV32
4600     if (VT.getVectorElementType() == MVT::i16)
4601       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4602     // vrev <4 x i8> -> VREV16
4603     assert(VT.getVectorElementType() == MVT::i8);
4604     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4605   case OP_VDUP0:
4606   case OP_VDUP1:
4607   case OP_VDUP2:
4608   case OP_VDUP3:
4609     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4610                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4611   case OP_VEXT1:
4612   case OP_VEXT2:
4613   case OP_VEXT3:
4614     return DAG.getNode(ARMISD::VEXT, dl, VT,
4615                        OpLHS, OpRHS,
4616                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4617   case OP_VUZPL:
4618   case OP_VUZPR:
4619     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4620                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4621   case OP_VZIPL:
4622   case OP_VZIPR:
4623     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4624                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4625   case OP_VTRNL:
4626   case OP_VTRNR:
4627     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4628                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4629   }
4630 }
4631
4632 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4633                                        ArrayRef<int> ShuffleMask,
4634                                        SelectionDAG &DAG) {
4635   // Check to see if we can use the VTBL instruction.
4636   SDValue V1 = Op.getOperand(0);
4637   SDValue V2 = Op.getOperand(1);
4638   DebugLoc DL = Op.getDebugLoc();
4639
4640   SmallVector<SDValue, 8> VTBLMask;
4641   for (ArrayRef<int>::iterator
4642          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4643     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4644
4645   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4646     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4647                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4648                                    &VTBLMask[0], 8));
4649
4650   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4651                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4652                                  &VTBLMask[0], 8));
4653 }
4654
4655 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4656   SDValue V1 = Op.getOperand(0);
4657   SDValue V2 = Op.getOperand(1);
4658   DebugLoc dl = Op.getDebugLoc();
4659   EVT VT = Op.getValueType();
4660   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4661
4662   // Convert shuffles that are directly supported on NEON to target-specific
4663   // DAG nodes, instead of keeping them as shuffles and matching them again
4664   // during code selection.  This is more efficient and avoids the possibility
4665   // of inconsistencies between legalization and selection.
4666   // FIXME: floating-point vectors should be canonicalized to integer vectors
4667   // of the same time so that they get CSEd properly.
4668   ArrayRef<int> ShuffleMask = SVN->getMask();
4669
4670   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4671   if (EltSize <= 32) {
4672     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4673       int Lane = SVN->getSplatIndex();
4674       // If this is undef splat, generate it via "just" vdup, if possible.
4675       if (Lane == -1) Lane = 0;
4676
4677       // Test if V1 is a SCALAR_TO_VECTOR.
4678       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4679         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4680       }
4681       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4682       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4683       // reaches it).
4684       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4685           !isa<ConstantSDNode>(V1.getOperand(0))) {
4686         bool IsScalarToVector = true;
4687         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4688           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4689             IsScalarToVector = false;
4690             break;
4691           }
4692         if (IsScalarToVector)
4693           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4694       }
4695       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4696                          DAG.getConstant(Lane, MVT::i32));
4697     }
4698
4699     bool ReverseVEXT;
4700     unsigned Imm;
4701     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4702       if (ReverseVEXT)
4703         std::swap(V1, V2);
4704       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4705                          DAG.getConstant(Imm, MVT::i32));
4706     }
4707
4708     if (isVREVMask(ShuffleMask, VT, 64))
4709       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4710     if (isVREVMask(ShuffleMask, VT, 32))
4711       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4712     if (isVREVMask(ShuffleMask, VT, 16))
4713       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4714
4715     if (V2->getOpcode() == ISD::UNDEF &&
4716         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4717       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4718                          DAG.getConstant(Imm, MVT::i32));
4719     }
4720
4721     // Check for Neon shuffles that modify both input vectors in place.
4722     // If both results are used, i.e., if there are two shuffles with the same
4723     // source operands and with masks corresponding to both results of one of
4724     // these operations, DAG memoization will ensure that a single node is
4725     // used for both shuffles.
4726     unsigned WhichResult;
4727     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4728       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4729                          V1, V2).getValue(WhichResult);
4730     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4731       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4732                          V1, V2).getValue(WhichResult);
4733     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4734       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4735                          V1, V2).getValue(WhichResult);
4736
4737     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4738       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4739                          V1, V1).getValue(WhichResult);
4740     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4741       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4742                          V1, V1).getValue(WhichResult);
4743     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4744       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4745                          V1, V1).getValue(WhichResult);
4746   }
4747
4748   // If the shuffle is not directly supported and it has 4 elements, use
4749   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4750   unsigned NumElts = VT.getVectorNumElements();
4751   if (NumElts == 4) {
4752     unsigned PFIndexes[4];
4753     for (unsigned i = 0; i != 4; ++i) {
4754       if (ShuffleMask[i] < 0)
4755         PFIndexes[i] = 8;
4756       else
4757         PFIndexes[i] = ShuffleMask[i];
4758     }
4759
4760     // Compute the index in the perfect shuffle table.
4761     unsigned PFTableIndex =
4762       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4763     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4764     unsigned Cost = (PFEntry >> 30);
4765
4766     if (Cost <= 4)
4767       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4768   }
4769
4770   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4771   if (EltSize >= 32) {
4772     // Do the expansion with floating-point types, since that is what the VFP
4773     // registers are defined to use, and since i64 is not legal.
4774     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4775     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4776     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4777     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4778     SmallVector<SDValue, 8> Ops;
4779     for (unsigned i = 0; i < NumElts; ++i) {
4780       if (ShuffleMask[i] < 0)
4781         Ops.push_back(DAG.getUNDEF(EltVT));
4782       else
4783         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4784                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4785                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4786                                                   MVT::i32)));
4787     }
4788     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4789     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4790   }
4791
4792   if (VT == MVT::v8i8) {
4793     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4794     if (NewOp.getNode())
4795       return NewOp;
4796   }
4797
4798   return SDValue();
4799 }
4800
4801 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4802   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4803   SDValue Lane = Op.getOperand(2);
4804   if (!isa<ConstantSDNode>(Lane))
4805     return SDValue();
4806
4807   return Op;
4808 }
4809
4810 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4811   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4812   SDValue Lane = Op.getOperand(1);
4813   if (!isa<ConstantSDNode>(Lane))
4814     return SDValue();
4815
4816   SDValue Vec = Op.getOperand(0);
4817   if (Op.getValueType() == MVT::i32 &&
4818       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4819     DebugLoc dl = Op.getDebugLoc();
4820     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4821   }
4822
4823   return Op;
4824 }
4825
4826 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4827   // The only time a CONCAT_VECTORS operation can have legal types is when
4828   // two 64-bit vectors are concatenated to a 128-bit vector.
4829   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4830          "unexpected CONCAT_VECTORS");
4831   DebugLoc dl = Op.getDebugLoc();
4832   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4833   SDValue Op0 = Op.getOperand(0);
4834   SDValue Op1 = Op.getOperand(1);
4835   if (Op0.getOpcode() != ISD::UNDEF)
4836     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4837                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4838                       DAG.getIntPtrConstant(0));
4839   if (Op1.getOpcode() != ISD::UNDEF)
4840     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4841                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4842                       DAG.getIntPtrConstant(1));
4843   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4844 }
4845
4846 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4847 /// element has been zero/sign-extended, depending on the isSigned parameter,
4848 /// from an integer type half its size.
4849 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4850                                    bool isSigned) {
4851   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4852   EVT VT = N->getValueType(0);
4853   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4854     SDNode *BVN = N->getOperand(0).getNode();
4855     if (BVN->getValueType(0) != MVT::v4i32 ||
4856         BVN->getOpcode() != ISD::BUILD_VECTOR)
4857       return false;
4858     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4859     unsigned HiElt = 1 - LoElt;
4860     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4861     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4862     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4863     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4864     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4865       return false;
4866     if (isSigned) {
4867       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4868           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4869         return true;
4870     } else {
4871       if (Hi0->isNullValue() && Hi1->isNullValue())
4872         return true;
4873     }
4874     return false;
4875   }
4876
4877   if (N->getOpcode() != ISD::BUILD_VECTOR)
4878     return false;
4879
4880   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4881     SDNode *Elt = N->getOperand(i).getNode();
4882     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4883       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4884       unsigned HalfSize = EltSize / 2;
4885       if (isSigned) {
4886         if (!isIntN(HalfSize, C->getSExtValue()))
4887           return false;
4888       } else {
4889         if (!isUIntN(HalfSize, C->getZExtValue()))
4890           return false;
4891       }
4892       continue;
4893     }
4894     return false;
4895   }
4896
4897   return true;
4898 }
4899
4900 /// isSignExtended - Check if a node is a vector value that is sign-extended
4901 /// or a constant BUILD_VECTOR with sign-extended elements.
4902 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4903   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4904     return true;
4905   if (isExtendedBUILD_VECTOR(N, DAG, true))
4906     return true;
4907   return false;
4908 }
4909
4910 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4911 /// or a constant BUILD_VECTOR with zero-extended elements.
4912 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4913   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4914     return true;
4915   if (isExtendedBUILD_VECTOR(N, DAG, false))
4916     return true;
4917   return false;
4918 }
4919
4920 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4921 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4922 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4923   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4924     return N->getOperand(0);
4925   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4926     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4927                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4928                        LD->isNonTemporal(), LD->isInvariant(),
4929                        LD->getAlignment());
4930   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4931   // have been legalized as a BITCAST from v4i32.
4932   if (N->getOpcode() == ISD::BITCAST) {
4933     SDNode *BVN = N->getOperand(0).getNode();
4934     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4935            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4936     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4937     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4938                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4939   }
4940   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4941   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4942   EVT VT = N->getValueType(0);
4943   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4944   unsigned NumElts = VT.getVectorNumElements();
4945   MVT TruncVT = MVT::getIntegerVT(EltSize);
4946   SmallVector<SDValue, 8> Ops;
4947   for (unsigned i = 0; i != NumElts; ++i) {
4948     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4949     const APInt &CInt = C->getAPIntValue();
4950     // Element types smaller than 32 bits are not legal, so use i32 elements.
4951     // The values are implicitly truncated so sext vs. zext doesn't matter.
4952     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4953   }
4954   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4955                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4956 }
4957
4958 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4959   unsigned Opcode = N->getOpcode();
4960   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4961     SDNode *N0 = N->getOperand(0).getNode();
4962     SDNode *N1 = N->getOperand(1).getNode();
4963     return N0->hasOneUse() && N1->hasOneUse() &&
4964       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4965   }
4966   return false;
4967 }
4968
4969 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4970   unsigned Opcode = N->getOpcode();
4971   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4972     SDNode *N0 = N->getOperand(0).getNode();
4973     SDNode *N1 = N->getOperand(1).getNode();
4974     return N0->hasOneUse() && N1->hasOneUse() &&
4975       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4976   }
4977   return false;
4978 }
4979
4980 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4981   // Multiplications are only custom-lowered for 128-bit vectors so that
4982   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4983   EVT VT = Op.getValueType();
4984   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4985   SDNode *N0 = Op.getOperand(0).getNode();
4986   SDNode *N1 = Op.getOperand(1).getNode();
4987   unsigned NewOpc = 0;
4988   bool isMLA = false;
4989   bool isN0SExt = isSignExtended(N0, DAG);
4990   bool isN1SExt = isSignExtended(N1, DAG);
4991   if (isN0SExt && isN1SExt)
4992     NewOpc = ARMISD::VMULLs;
4993   else {
4994     bool isN0ZExt = isZeroExtended(N0, DAG);
4995     bool isN1ZExt = isZeroExtended(N1, DAG);
4996     if (isN0ZExt && isN1ZExt)
4997       NewOpc = ARMISD::VMULLu;
4998     else if (isN1SExt || isN1ZExt) {
4999       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5000       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5001       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5002         NewOpc = ARMISD::VMULLs;
5003         isMLA = true;
5004       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5005         NewOpc = ARMISD::VMULLu;
5006         isMLA = true;
5007       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5008         std::swap(N0, N1);
5009         NewOpc = ARMISD::VMULLu;
5010         isMLA = true;
5011       }
5012     }
5013
5014     if (!NewOpc) {
5015       if (VT == MVT::v2i64)
5016         // Fall through to expand this.  It is not legal.
5017         return SDValue();
5018       else
5019         // Other vector multiplications are legal.
5020         return Op;
5021     }
5022   }
5023
5024   // Legalize to a VMULL instruction.
5025   DebugLoc DL = Op.getDebugLoc();
5026   SDValue Op0;
5027   SDValue Op1 = SkipExtension(N1, DAG);
5028   if (!isMLA) {
5029     Op0 = SkipExtension(N0, DAG);
5030     assert(Op0.getValueType().is64BitVector() &&
5031            Op1.getValueType().is64BitVector() &&
5032            "unexpected types for extended operands to VMULL");
5033     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5034   }
5035
5036   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5037   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5038   //   vmull q0, d4, d6
5039   //   vmlal q0, d5, d6
5040   // is faster than
5041   //   vaddl q0, d4, d5
5042   //   vmovl q1, d6
5043   //   vmul  q0, q0, q1
5044   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
5045   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
5046   EVT Op1VT = Op1.getValueType();
5047   return DAG.getNode(N0->getOpcode(), DL, VT,
5048                      DAG.getNode(NewOpc, DL, VT,
5049                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5050                      DAG.getNode(NewOpc, DL, VT,
5051                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5052 }
5053
5054 static SDValue
5055 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5056   // Convert to float
5057   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5058   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5059   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5060   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5061   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5062   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5063   // Get reciprocal estimate.
5064   // float4 recip = vrecpeq_f32(yf);
5065   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5066                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5067   // Because char has a smaller range than uchar, we can actually get away
5068   // without any newton steps.  This requires that we use a weird bias
5069   // of 0xb000, however (again, this has been exhaustively tested).
5070   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5071   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5072   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5073   Y = DAG.getConstant(0xb000, MVT::i32);
5074   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5075   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5076   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5077   // Convert back to short.
5078   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5079   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5080   return X;
5081 }
5082
5083 static SDValue
5084 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5085   SDValue N2;
5086   // Convert to float.
5087   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5088   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5089   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5090   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5091   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5092   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5093
5094   // Use reciprocal estimate and one refinement step.
5095   // float4 recip = vrecpeq_f32(yf);
5096   // recip *= vrecpsq_f32(yf, recip);
5097   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5098                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5099   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5100                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5101                    N1, N2);
5102   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5103   // Because short has a smaller range than ushort, we can actually get away
5104   // with only a single newton step.  This requires that we use a weird bias
5105   // of 89, however (again, this has been exhaustively tested).
5106   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5107   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5108   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5109   N1 = DAG.getConstant(0x89, MVT::i32);
5110   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5111   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5112   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5113   // Convert back to integer and return.
5114   // return vmovn_s32(vcvt_s32_f32(result));
5115   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5116   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5117   return N0;
5118 }
5119
5120 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5121   EVT VT = Op.getValueType();
5122   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5123          "unexpected type for custom-lowering ISD::SDIV");
5124
5125   DebugLoc dl = Op.getDebugLoc();
5126   SDValue N0 = Op.getOperand(0);
5127   SDValue N1 = Op.getOperand(1);
5128   SDValue N2, N3;
5129
5130   if (VT == MVT::v8i8) {
5131     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5132     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5133
5134     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5135                      DAG.getIntPtrConstant(4));
5136     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5137                      DAG.getIntPtrConstant(4));
5138     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5139                      DAG.getIntPtrConstant(0));
5140     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5141                      DAG.getIntPtrConstant(0));
5142
5143     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5144     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5145
5146     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5147     N0 = LowerCONCAT_VECTORS(N0, DAG);
5148
5149     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5150     return N0;
5151   }
5152   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5153 }
5154
5155 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5156   EVT VT = Op.getValueType();
5157   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5158          "unexpected type for custom-lowering ISD::UDIV");
5159
5160   DebugLoc dl = Op.getDebugLoc();
5161   SDValue N0 = Op.getOperand(0);
5162   SDValue N1 = Op.getOperand(1);
5163   SDValue N2, N3;
5164
5165   if (VT == MVT::v8i8) {
5166     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5167     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5168
5169     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5170                      DAG.getIntPtrConstant(4));
5171     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5172                      DAG.getIntPtrConstant(4));
5173     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5174                      DAG.getIntPtrConstant(0));
5175     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5176                      DAG.getIntPtrConstant(0));
5177
5178     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5179     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5180
5181     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5182     N0 = LowerCONCAT_VECTORS(N0, DAG);
5183
5184     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5185                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5186                      N0);
5187     return N0;
5188   }
5189
5190   // v4i16 sdiv ... Convert to float.
5191   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5192   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5193   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5194   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5195   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5196   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5197
5198   // Use reciprocal estimate and two refinement steps.
5199   // float4 recip = vrecpeq_f32(yf);
5200   // recip *= vrecpsq_f32(yf, recip);
5201   // recip *= vrecpsq_f32(yf, recip);
5202   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5203                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5204   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5205                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5206                    BN1, N2);
5207   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5208   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5209                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5210                    BN1, N2);
5211   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5212   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5213   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5214   // and that it will never cause us to return an answer too large).
5215   // float4 result = as_float4(as_int4(xf*recip) + 2);
5216   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5217   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5218   N1 = DAG.getConstant(2, MVT::i32);
5219   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5220   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5221   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5222   // Convert back to integer and return.
5223   // return vmovn_u32(vcvt_s32_f32(result));
5224   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5225   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5226   return N0;
5227 }
5228
5229 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5230   EVT VT = Op.getNode()->getValueType(0);
5231   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5232
5233   unsigned Opc;
5234   bool ExtraOp = false;
5235   switch (Op.getOpcode()) {
5236   default: llvm_unreachable("Invalid code");
5237   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5238   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5239   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5240   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5241   }
5242
5243   if (!ExtraOp)
5244     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5245                        Op.getOperand(1));
5246   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5247                      Op.getOperand(1), Op.getOperand(2));
5248 }
5249
5250 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5251   // Monotonic load/store is legal for all targets
5252   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5253     return Op;
5254
5255   // Aquire/Release load/store is not legal for targets without a
5256   // dmb or equivalent available.
5257   return SDValue();
5258 }
5259
5260
5261 static void
5262 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5263                     SelectionDAG &DAG, unsigned NewOp) {
5264   DebugLoc dl = Node->getDebugLoc();
5265   assert (Node->getValueType(0) == MVT::i64 &&
5266           "Only know how to expand i64 atomics");
5267
5268   SmallVector<SDValue, 6> Ops;
5269   Ops.push_back(Node->getOperand(0)); // Chain
5270   Ops.push_back(Node->getOperand(1)); // Ptr
5271   // Low part of Val1
5272   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5273                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5274   // High part of Val1
5275   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5276                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5277   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5278     // High part of Val1
5279     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5280                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5281     // High part of Val2
5282     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5283                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5284   }
5285   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5286   SDValue Result =
5287     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5288                             cast<MemSDNode>(Node)->getMemOperand());
5289   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5290   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5291   Results.push_back(Result.getValue(2));
5292 }
5293
5294 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5295   switch (Op.getOpcode()) {
5296   default: llvm_unreachable("Don't know how to custom lower this!");
5297   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5298   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5299   case ISD::GlobalAddress:
5300     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5301       LowerGlobalAddressELF(Op, DAG);
5302   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5303   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5304   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5305   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5306   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5307   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5308   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5309   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5310   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5311   case ISD::SINT_TO_FP:
5312   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5313   case ISD::FP_TO_SINT:
5314   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5315   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5316   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5317   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5318   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5319   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5320   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5321   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5322                                                                Subtarget);
5323   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5324   case ISD::SHL:
5325   case ISD::SRL:
5326   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5327   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5328   case ISD::SRL_PARTS:
5329   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5330   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5331   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5332   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5333   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5334   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5335   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5336   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5337   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5338   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5339   case ISD::MUL:           return LowerMUL(Op, DAG);
5340   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5341   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5342   case ISD::ADDC:
5343   case ISD::ADDE:
5344   case ISD::SUBC:
5345   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5346   case ISD::ATOMIC_LOAD:
5347   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5348   }
5349 }
5350
5351 /// ReplaceNodeResults - Replace the results of node with an illegal result
5352 /// type with new values built out of custom code.
5353 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5354                                            SmallVectorImpl<SDValue>&Results,
5355                                            SelectionDAG &DAG) const {
5356   SDValue Res;
5357   switch (N->getOpcode()) {
5358   default:
5359     llvm_unreachable("Don't know how to custom expand this!");
5360   case ISD::BITCAST:
5361     Res = ExpandBITCAST(N, DAG);
5362     break;
5363   case ISD::SRL:
5364   case ISD::SRA:
5365     Res = Expand64BitShift(N, DAG, Subtarget);
5366     break;
5367   case ISD::ATOMIC_LOAD_ADD:
5368     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5369     return;
5370   case ISD::ATOMIC_LOAD_AND:
5371     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5372     return;
5373   case ISD::ATOMIC_LOAD_NAND:
5374     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5375     return;
5376   case ISD::ATOMIC_LOAD_OR:
5377     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5378     return;
5379   case ISD::ATOMIC_LOAD_SUB:
5380     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5381     return;
5382   case ISD::ATOMIC_LOAD_XOR:
5383     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5384     return;
5385   case ISD::ATOMIC_SWAP:
5386     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5387     return;
5388   case ISD::ATOMIC_CMP_SWAP:
5389     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5390     return;
5391   }
5392   if (Res.getNode())
5393     Results.push_back(Res);
5394 }
5395
5396 //===----------------------------------------------------------------------===//
5397 //                           ARM Scheduler Hooks
5398 //===----------------------------------------------------------------------===//
5399
5400 MachineBasicBlock *
5401 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5402                                      MachineBasicBlock *BB,
5403                                      unsigned Size) const {
5404   unsigned dest    = MI->getOperand(0).getReg();
5405   unsigned ptr     = MI->getOperand(1).getReg();
5406   unsigned oldval  = MI->getOperand(2).getReg();
5407   unsigned newval  = MI->getOperand(3).getReg();
5408   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5409   DebugLoc dl = MI->getDebugLoc();
5410   bool isThumb2 = Subtarget->isThumb2();
5411
5412   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5413   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5414     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5415     (const TargetRegisterClass*)&ARM::GPRRegClass);
5416
5417   if (isThumb2) {
5418     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5419     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5420     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5421   }
5422
5423   unsigned ldrOpc, strOpc;
5424   switch (Size) {
5425   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5426   case 1:
5427     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5428     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5429     break;
5430   case 2:
5431     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5432     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5433     break;
5434   case 4:
5435     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5436     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5437     break;
5438   }
5439
5440   MachineFunction *MF = BB->getParent();
5441   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5442   MachineFunction::iterator It = BB;
5443   ++It; // insert the new blocks after the current block
5444
5445   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5446   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5447   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5448   MF->insert(It, loop1MBB);
5449   MF->insert(It, loop2MBB);
5450   MF->insert(It, exitMBB);
5451
5452   // Transfer the remainder of BB and its successor edges to exitMBB.
5453   exitMBB->splice(exitMBB->begin(), BB,
5454                   llvm::next(MachineBasicBlock::iterator(MI)),
5455                   BB->end());
5456   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5457
5458   //  thisMBB:
5459   //   ...
5460   //   fallthrough --> loop1MBB
5461   BB->addSuccessor(loop1MBB);
5462
5463   // loop1MBB:
5464   //   ldrex dest, [ptr]
5465   //   cmp dest, oldval
5466   //   bne exitMBB
5467   BB = loop1MBB;
5468   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5469   if (ldrOpc == ARM::t2LDREX)
5470     MIB.addImm(0);
5471   AddDefaultPred(MIB);
5472   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5473                  .addReg(dest).addReg(oldval));
5474   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5475     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5476   BB->addSuccessor(loop2MBB);
5477   BB->addSuccessor(exitMBB);
5478
5479   // loop2MBB:
5480   //   strex scratch, newval, [ptr]
5481   //   cmp scratch, #0
5482   //   bne loop1MBB
5483   BB = loop2MBB;
5484   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5485   if (strOpc == ARM::t2STREX)
5486     MIB.addImm(0);
5487   AddDefaultPred(MIB);
5488   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5489                  .addReg(scratch).addImm(0));
5490   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5491     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5492   BB->addSuccessor(loop1MBB);
5493   BB->addSuccessor(exitMBB);
5494
5495   //  exitMBB:
5496   //   ...
5497   BB = exitMBB;
5498
5499   MI->eraseFromParent();   // The instruction is gone now.
5500
5501   return BB;
5502 }
5503
5504 MachineBasicBlock *
5505 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5506                                     unsigned Size, unsigned BinOpcode) const {
5507   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5508   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5509
5510   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5511   MachineFunction *MF = BB->getParent();
5512   MachineFunction::iterator It = BB;
5513   ++It;
5514
5515   unsigned dest = MI->getOperand(0).getReg();
5516   unsigned ptr = MI->getOperand(1).getReg();
5517   unsigned incr = MI->getOperand(2).getReg();
5518   DebugLoc dl = MI->getDebugLoc();
5519   bool isThumb2 = Subtarget->isThumb2();
5520
5521   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5522   if (isThumb2) {
5523     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5524     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5525   }
5526
5527   unsigned ldrOpc, strOpc;
5528   switch (Size) {
5529   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5530   case 1:
5531     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5532     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5533     break;
5534   case 2:
5535     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5536     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5537     break;
5538   case 4:
5539     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5540     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5541     break;
5542   }
5543
5544   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5545   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5546   MF->insert(It, loopMBB);
5547   MF->insert(It, exitMBB);
5548
5549   // Transfer the remainder of BB and its successor edges to exitMBB.
5550   exitMBB->splice(exitMBB->begin(), BB,
5551                   llvm::next(MachineBasicBlock::iterator(MI)),
5552                   BB->end());
5553   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5554
5555   const TargetRegisterClass *TRC = isThumb2 ?
5556     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5557     (const TargetRegisterClass*)&ARM::GPRRegClass;
5558   unsigned scratch = MRI.createVirtualRegister(TRC);
5559   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5560
5561   //  thisMBB:
5562   //   ...
5563   //   fallthrough --> loopMBB
5564   BB->addSuccessor(loopMBB);
5565
5566   //  loopMBB:
5567   //   ldrex dest, ptr
5568   //   <binop> scratch2, dest, incr
5569   //   strex scratch, scratch2, ptr
5570   //   cmp scratch, #0
5571   //   bne- loopMBB
5572   //   fallthrough --> exitMBB
5573   BB = loopMBB;
5574   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5575   if (ldrOpc == ARM::t2LDREX)
5576     MIB.addImm(0);
5577   AddDefaultPred(MIB);
5578   if (BinOpcode) {
5579     // operand order needs to go the other way for NAND
5580     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5581       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5582                      addReg(incr).addReg(dest)).addReg(0);
5583     else
5584       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5585                      addReg(dest).addReg(incr)).addReg(0);
5586   }
5587
5588   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5589   if (strOpc == ARM::t2STREX)
5590     MIB.addImm(0);
5591   AddDefaultPred(MIB);
5592   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5593                  .addReg(scratch).addImm(0));
5594   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5595     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5596
5597   BB->addSuccessor(loopMBB);
5598   BB->addSuccessor(exitMBB);
5599
5600   //  exitMBB:
5601   //   ...
5602   BB = exitMBB;
5603
5604   MI->eraseFromParent();   // The instruction is gone now.
5605
5606   return BB;
5607 }
5608
5609 MachineBasicBlock *
5610 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5611                                           MachineBasicBlock *BB,
5612                                           unsigned Size,
5613                                           bool signExtend,
5614                                           ARMCC::CondCodes Cond) const {
5615   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5616
5617   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5618   MachineFunction *MF = BB->getParent();
5619   MachineFunction::iterator It = BB;
5620   ++It;
5621
5622   unsigned dest = MI->getOperand(0).getReg();
5623   unsigned ptr = MI->getOperand(1).getReg();
5624   unsigned incr = MI->getOperand(2).getReg();
5625   unsigned oldval = dest;
5626   DebugLoc dl = MI->getDebugLoc();
5627   bool isThumb2 = Subtarget->isThumb2();
5628
5629   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5630   if (isThumb2) {
5631     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5632     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5633   }
5634
5635   unsigned ldrOpc, strOpc, extendOpc;
5636   switch (Size) {
5637   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5638   case 1:
5639     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5640     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5641     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5642     break;
5643   case 2:
5644     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5645     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5646     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5647     break;
5648   case 4:
5649     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5650     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5651     extendOpc = 0;
5652     break;
5653   }
5654
5655   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5656   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5657   MF->insert(It, loopMBB);
5658   MF->insert(It, exitMBB);
5659
5660   // Transfer the remainder of BB and its successor edges to exitMBB.
5661   exitMBB->splice(exitMBB->begin(), BB,
5662                   llvm::next(MachineBasicBlock::iterator(MI)),
5663                   BB->end());
5664   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5665
5666   const TargetRegisterClass *TRC = isThumb2 ?
5667     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5668     (const TargetRegisterClass*)&ARM::GPRRegClass;
5669   unsigned scratch = MRI.createVirtualRegister(TRC);
5670   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5671
5672   //  thisMBB:
5673   //   ...
5674   //   fallthrough --> loopMBB
5675   BB->addSuccessor(loopMBB);
5676
5677   //  loopMBB:
5678   //   ldrex dest, ptr
5679   //   (sign extend dest, if required)
5680   //   cmp dest, incr
5681   //   cmov.cond scratch2, incr, dest
5682   //   strex scratch, scratch2, ptr
5683   //   cmp scratch, #0
5684   //   bne- loopMBB
5685   //   fallthrough --> exitMBB
5686   BB = loopMBB;
5687   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5688   if (ldrOpc == ARM::t2LDREX)
5689     MIB.addImm(0);
5690   AddDefaultPred(MIB);
5691
5692   // Sign extend the value, if necessary.
5693   if (signExtend && extendOpc) {
5694     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5695     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5696                      .addReg(dest)
5697                      .addImm(0));
5698   }
5699
5700   // Build compare and cmov instructions.
5701   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5702                  .addReg(oldval).addReg(incr));
5703   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5704          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5705
5706   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5707   if (strOpc == ARM::t2STREX)
5708     MIB.addImm(0);
5709   AddDefaultPred(MIB);
5710   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5711                  .addReg(scratch).addImm(0));
5712   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5713     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5714
5715   BB->addSuccessor(loopMBB);
5716   BB->addSuccessor(exitMBB);
5717
5718   //  exitMBB:
5719   //   ...
5720   BB = exitMBB;
5721
5722   MI->eraseFromParent();   // The instruction is gone now.
5723
5724   return BB;
5725 }
5726
5727 MachineBasicBlock *
5728 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5729                                       unsigned Op1, unsigned Op2,
5730                                       bool NeedsCarry, bool IsCmpxchg) const {
5731   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5732   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5733
5734   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5735   MachineFunction *MF = BB->getParent();
5736   MachineFunction::iterator It = BB;
5737   ++It;
5738
5739   unsigned destlo = MI->getOperand(0).getReg();
5740   unsigned desthi = MI->getOperand(1).getReg();
5741   unsigned ptr = MI->getOperand(2).getReg();
5742   unsigned vallo = MI->getOperand(3).getReg();
5743   unsigned valhi = MI->getOperand(4).getReg();
5744   DebugLoc dl = MI->getDebugLoc();
5745   bool isThumb2 = Subtarget->isThumb2();
5746
5747   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5748   if (isThumb2) {
5749     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5750     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5751     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5752   }
5753
5754   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5755   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5756
5757   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5758   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5759   if (IsCmpxchg) {
5760     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5761     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5762   }
5763   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5764   MF->insert(It, loopMBB);
5765   if (IsCmpxchg) {
5766     MF->insert(It, contBB);
5767     MF->insert(It, cont2BB);
5768   }
5769   MF->insert(It, exitMBB);
5770
5771   // Transfer the remainder of BB and its successor edges to exitMBB.
5772   exitMBB->splice(exitMBB->begin(), BB,
5773                   llvm::next(MachineBasicBlock::iterator(MI)),
5774                   BB->end());
5775   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5776
5777   const TargetRegisterClass *TRC = isThumb2 ?
5778     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5779     (const TargetRegisterClass*)&ARM::GPRRegClass;
5780   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5781
5782   //  thisMBB:
5783   //   ...
5784   //   fallthrough --> loopMBB
5785   BB->addSuccessor(loopMBB);
5786
5787   //  loopMBB:
5788   //   ldrexd r2, r3, ptr
5789   //   <binopa> r0, r2, incr
5790   //   <binopb> r1, r3, incr
5791   //   strexd storesuccess, r0, r1, ptr
5792   //   cmp storesuccess, #0
5793   //   bne- loopMBB
5794   //   fallthrough --> exitMBB
5795   //
5796   // Note that the registers are explicitly specified because there is not any
5797   // way to force the register allocator to allocate a register pair.
5798   //
5799   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5800   // need to properly enforce the restriction that the two output registers
5801   // for ldrexd must be different.
5802   BB = loopMBB;
5803   // Load
5804   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5805                  .addReg(ARM::R2, RegState::Define)
5806                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5807   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5808   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5809   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5810
5811   if (IsCmpxchg) {
5812     // Add early exit
5813     for (unsigned i = 0; i < 2; i++) {
5814       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5815                                                          ARM::CMPrr))
5816                      .addReg(i == 0 ? destlo : desthi)
5817                      .addReg(i == 0 ? vallo : valhi));
5818       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5819         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5820       BB->addSuccessor(exitMBB);
5821       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5822       BB = (i == 0 ? contBB : cont2BB);
5823     }
5824
5825     // Copy to physregs for strexd
5826     unsigned setlo = MI->getOperand(5).getReg();
5827     unsigned sethi = MI->getOperand(6).getReg();
5828     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5829     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5830   } else if (Op1) {
5831     // Perform binary operation
5832     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5833                    .addReg(destlo).addReg(vallo))
5834         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5835     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5836                    .addReg(desthi).addReg(valhi)).addReg(0);
5837   } else {
5838     // Copy to physregs for strexd
5839     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5840     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5841   }
5842
5843   // Store
5844   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5845                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5846   // Cmp+jump
5847   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5848                  .addReg(storesuccess).addImm(0));
5849   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5850     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5851
5852   BB->addSuccessor(loopMBB);
5853   BB->addSuccessor(exitMBB);
5854
5855   //  exitMBB:
5856   //   ...
5857   BB = exitMBB;
5858
5859   MI->eraseFromParent();   // The instruction is gone now.
5860
5861   return BB;
5862 }
5863
5864 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5865 /// registers the function context.
5866 void ARMTargetLowering::
5867 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5868                        MachineBasicBlock *DispatchBB, int FI) const {
5869   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5870   DebugLoc dl = MI->getDebugLoc();
5871   MachineFunction *MF = MBB->getParent();
5872   MachineRegisterInfo *MRI = &MF->getRegInfo();
5873   MachineConstantPool *MCP = MF->getConstantPool();
5874   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5875   const Function *F = MF->getFunction();
5876
5877   bool isThumb = Subtarget->isThumb();
5878   bool isThumb2 = Subtarget->isThumb2();
5879
5880   unsigned PCLabelId = AFI->createPICLabelUId();
5881   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5882   ARMConstantPoolValue *CPV =
5883     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5884   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5885
5886   const TargetRegisterClass *TRC = isThumb ?
5887     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5888     (const TargetRegisterClass*)&ARM::GPRRegClass;
5889
5890   // Grab constant pool and fixed stack memory operands.
5891   MachineMemOperand *CPMMO =
5892     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5893                              MachineMemOperand::MOLoad, 4, 4);
5894
5895   MachineMemOperand *FIMMOSt =
5896     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5897                              MachineMemOperand::MOStore, 4, 4);
5898
5899   // Load the address of the dispatch MBB into the jump buffer.
5900   if (isThumb2) {
5901     // Incoming value: jbuf
5902     //   ldr.n  r5, LCPI1_1
5903     //   orr    r5, r5, #1
5904     //   add    r5, pc
5905     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5906     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5907     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5908                    .addConstantPoolIndex(CPI)
5909                    .addMemOperand(CPMMO));
5910     // Set the low bit because of thumb mode.
5911     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5912     AddDefaultCC(
5913       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5914                      .addReg(NewVReg1, RegState::Kill)
5915                      .addImm(0x01)));
5916     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5917     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5918       .addReg(NewVReg2, RegState::Kill)
5919       .addImm(PCLabelId);
5920     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5921                    .addReg(NewVReg3, RegState::Kill)
5922                    .addFrameIndex(FI)
5923                    .addImm(36)  // &jbuf[1] :: pc
5924                    .addMemOperand(FIMMOSt));
5925   } else if (isThumb) {
5926     // Incoming value: jbuf
5927     //   ldr.n  r1, LCPI1_4
5928     //   add    r1, pc
5929     //   mov    r2, #1
5930     //   orrs   r1, r2
5931     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5932     //   str    r1, [r2]
5933     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5934     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5935                    .addConstantPoolIndex(CPI)
5936                    .addMemOperand(CPMMO));
5937     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5938     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5939       .addReg(NewVReg1, RegState::Kill)
5940       .addImm(PCLabelId);
5941     // Set the low bit because of thumb mode.
5942     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5943     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5944                    .addReg(ARM::CPSR, RegState::Define)
5945                    .addImm(1));
5946     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5947     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5948                    .addReg(ARM::CPSR, RegState::Define)
5949                    .addReg(NewVReg2, RegState::Kill)
5950                    .addReg(NewVReg3, RegState::Kill));
5951     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5952     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5953                    .addFrameIndex(FI)
5954                    .addImm(36)); // &jbuf[1] :: pc
5955     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5956                    .addReg(NewVReg4, RegState::Kill)
5957                    .addReg(NewVReg5, RegState::Kill)
5958                    .addImm(0)
5959                    .addMemOperand(FIMMOSt));
5960   } else {
5961     // Incoming value: jbuf
5962     //   ldr  r1, LCPI1_1
5963     //   add  r1, pc, r1
5964     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5965     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5966     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5967                    .addConstantPoolIndex(CPI)
5968                    .addImm(0)
5969                    .addMemOperand(CPMMO));
5970     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5971     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5972                    .addReg(NewVReg1, RegState::Kill)
5973                    .addImm(PCLabelId));
5974     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5975                    .addReg(NewVReg2, RegState::Kill)
5976                    .addFrameIndex(FI)
5977                    .addImm(36)  // &jbuf[1] :: pc
5978                    .addMemOperand(FIMMOSt));
5979   }
5980 }
5981
5982 MachineBasicBlock *ARMTargetLowering::
5983 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5984   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5985   DebugLoc dl = MI->getDebugLoc();
5986   MachineFunction *MF = MBB->getParent();
5987   MachineRegisterInfo *MRI = &MF->getRegInfo();
5988   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5989   MachineFrameInfo *MFI = MF->getFrameInfo();
5990   int FI = MFI->getFunctionContextIndex();
5991
5992   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5993     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5994     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5995
5996   // Get a mapping of the call site numbers to all of the landing pads they're
5997   // associated with.
5998   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5999   unsigned MaxCSNum = 0;
6000   MachineModuleInfo &MMI = MF->getMMI();
6001   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6002        ++BB) {
6003     if (!BB->isLandingPad()) continue;
6004
6005     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6006     // pad.
6007     for (MachineBasicBlock::iterator
6008            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6009       if (!II->isEHLabel()) continue;
6010
6011       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6012       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6013
6014       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6015       for (SmallVectorImpl<unsigned>::iterator
6016              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6017            CSI != CSE; ++CSI) {
6018         CallSiteNumToLPad[*CSI].push_back(BB);
6019         MaxCSNum = std::max(MaxCSNum, *CSI);
6020       }
6021       break;
6022     }
6023   }
6024
6025   // Get an ordered list of the machine basic blocks for the jump table.
6026   std::vector<MachineBasicBlock*> LPadList;
6027   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6028   LPadList.reserve(CallSiteNumToLPad.size());
6029   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6030     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6031     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6032            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6033       LPadList.push_back(*II);
6034       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6035     }
6036   }
6037
6038   assert(!LPadList.empty() &&
6039          "No landing pad destinations for the dispatch jump table!");
6040
6041   // Create the jump table and associated information.
6042   MachineJumpTableInfo *JTI =
6043     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6044   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6045   unsigned UId = AFI->createJumpTableUId();
6046
6047   // Create the MBBs for the dispatch code.
6048
6049   // Shove the dispatch's address into the return slot in the function context.
6050   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6051   DispatchBB->setIsLandingPad();
6052
6053   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6054   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6055   DispatchBB->addSuccessor(TrapBB);
6056
6057   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6058   DispatchBB->addSuccessor(DispContBB);
6059
6060   // Insert and MBBs.
6061   MF->insert(MF->end(), DispatchBB);
6062   MF->insert(MF->end(), DispContBB);
6063   MF->insert(MF->end(), TrapBB);
6064
6065   // Insert code into the entry block that creates and registers the function
6066   // context.
6067   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6068
6069   MachineMemOperand *FIMMOLd =
6070     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6071                              MachineMemOperand::MOLoad |
6072                              MachineMemOperand::MOVolatile, 4, 4);
6073
6074   MachineInstrBuilder MIB;
6075   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6076
6077   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6078   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6079
6080   // Add a register mask with no preserved registers.  This results in all
6081   // registers being marked as clobbered.
6082   MIB.addRegMask(RI.getNoPreservedMask());
6083
6084   unsigned NumLPads = LPadList.size();
6085   if (Subtarget->isThumb2()) {
6086     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6087     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6088                    .addFrameIndex(FI)
6089                    .addImm(4)
6090                    .addMemOperand(FIMMOLd));
6091
6092     if (NumLPads < 256) {
6093       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6094                      .addReg(NewVReg1)
6095                      .addImm(LPadList.size()));
6096     } else {
6097       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6098       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6099                      .addImm(NumLPads & 0xFFFF));
6100
6101       unsigned VReg2 = VReg1;
6102       if ((NumLPads & 0xFFFF0000) != 0) {
6103         VReg2 = MRI->createVirtualRegister(TRC);
6104         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6105                        .addReg(VReg1)
6106                        .addImm(NumLPads >> 16));
6107       }
6108
6109       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6110                      .addReg(NewVReg1)
6111                      .addReg(VReg2));
6112     }
6113
6114     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6115       .addMBB(TrapBB)
6116       .addImm(ARMCC::HI)
6117       .addReg(ARM::CPSR);
6118
6119     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6120     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6121                    .addJumpTableIndex(MJTI)
6122                    .addImm(UId));
6123
6124     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6125     AddDefaultCC(
6126       AddDefaultPred(
6127         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6128         .addReg(NewVReg3, RegState::Kill)
6129         .addReg(NewVReg1)
6130         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6131
6132     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6133       .addReg(NewVReg4, RegState::Kill)
6134       .addReg(NewVReg1)
6135       .addJumpTableIndex(MJTI)
6136       .addImm(UId);
6137   } else if (Subtarget->isThumb()) {
6138     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6139     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6140                    .addFrameIndex(FI)
6141                    .addImm(1)
6142                    .addMemOperand(FIMMOLd));
6143
6144     if (NumLPads < 256) {
6145       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6146                      .addReg(NewVReg1)
6147                      .addImm(NumLPads));
6148     } else {
6149       MachineConstantPool *ConstantPool = MF->getConstantPool();
6150       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6151       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6152
6153       // MachineConstantPool wants an explicit alignment.
6154       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6155       if (Align == 0)
6156         Align = getDataLayout()->getTypeAllocSize(C->getType());
6157       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6158
6159       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6160       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6161                      .addReg(VReg1, RegState::Define)
6162                      .addConstantPoolIndex(Idx));
6163       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6164                      .addReg(NewVReg1)
6165                      .addReg(VReg1));
6166     }
6167
6168     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6169       .addMBB(TrapBB)
6170       .addImm(ARMCC::HI)
6171       .addReg(ARM::CPSR);
6172
6173     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6174     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6175                    .addReg(ARM::CPSR, RegState::Define)
6176                    .addReg(NewVReg1)
6177                    .addImm(2));
6178
6179     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6180     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6181                    .addJumpTableIndex(MJTI)
6182                    .addImm(UId));
6183
6184     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6185     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6186                    .addReg(ARM::CPSR, RegState::Define)
6187                    .addReg(NewVReg2, RegState::Kill)
6188                    .addReg(NewVReg3));
6189
6190     MachineMemOperand *JTMMOLd =
6191       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6192                                MachineMemOperand::MOLoad, 4, 4);
6193
6194     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6195     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6196                    .addReg(NewVReg4, RegState::Kill)
6197                    .addImm(0)
6198                    .addMemOperand(JTMMOLd));
6199
6200     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6201     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6202                    .addReg(ARM::CPSR, RegState::Define)
6203                    .addReg(NewVReg5, RegState::Kill)
6204                    .addReg(NewVReg3));
6205
6206     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6207       .addReg(NewVReg6, RegState::Kill)
6208       .addJumpTableIndex(MJTI)
6209       .addImm(UId);
6210   } else {
6211     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6212     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6213                    .addFrameIndex(FI)
6214                    .addImm(4)
6215                    .addMemOperand(FIMMOLd));
6216
6217     if (NumLPads < 256) {
6218       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6219                      .addReg(NewVReg1)
6220                      .addImm(NumLPads));
6221     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6222       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6223       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6224                      .addImm(NumLPads & 0xFFFF));
6225
6226       unsigned VReg2 = VReg1;
6227       if ((NumLPads & 0xFFFF0000) != 0) {
6228         VReg2 = MRI->createVirtualRegister(TRC);
6229         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6230                        .addReg(VReg1)
6231                        .addImm(NumLPads >> 16));
6232       }
6233
6234       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6235                      .addReg(NewVReg1)
6236                      .addReg(VReg2));
6237     } else {
6238       MachineConstantPool *ConstantPool = MF->getConstantPool();
6239       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6240       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6241
6242       // MachineConstantPool wants an explicit alignment.
6243       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6244       if (Align == 0)
6245         Align = getDataLayout()->getTypeAllocSize(C->getType());
6246       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6247
6248       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6249       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6250                      .addReg(VReg1, RegState::Define)
6251                      .addConstantPoolIndex(Idx)
6252                      .addImm(0));
6253       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6254                      .addReg(NewVReg1)
6255                      .addReg(VReg1, RegState::Kill));
6256     }
6257
6258     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6259       .addMBB(TrapBB)
6260       .addImm(ARMCC::HI)
6261       .addReg(ARM::CPSR);
6262
6263     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6264     AddDefaultCC(
6265       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6266                      .addReg(NewVReg1)
6267                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6268     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6269     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6270                    .addJumpTableIndex(MJTI)
6271                    .addImm(UId));
6272
6273     MachineMemOperand *JTMMOLd =
6274       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6275                                MachineMemOperand::MOLoad, 4, 4);
6276     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6277     AddDefaultPred(
6278       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6279       .addReg(NewVReg3, RegState::Kill)
6280       .addReg(NewVReg4)
6281       .addImm(0)
6282       .addMemOperand(JTMMOLd));
6283
6284     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6285       .addReg(NewVReg5, RegState::Kill)
6286       .addReg(NewVReg4)
6287       .addJumpTableIndex(MJTI)
6288       .addImm(UId);
6289   }
6290
6291   // Add the jump table entries as successors to the MBB.
6292   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6293   for (std::vector<MachineBasicBlock*>::iterator
6294          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6295     MachineBasicBlock *CurMBB = *I;
6296     if (SeenMBBs.insert(CurMBB))
6297       DispContBB->addSuccessor(CurMBB);
6298   }
6299
6300   // N.B. the order the invoke BBs are processed in doesn't matter here.
6301   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6302   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6303   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6304          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6305     MachineBasicBlock *BB = *I;
6306
6307     // Remove the landing pad successor from the invoke block and replace it
6308     // with the new dispatch block.
6309     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6310                                                   BB->succ_end());
6311     while (!Successors.empty()) {
6312       MachineBasicBlock *SMBB = Successors.pop_back_val();
6313       if (SMBB->isLandingPad()) {
6314         BB->removeSuccessor(SMBB);
6315         MBBLPads.push_back(SMBB);
6316       }
6317     }
6318
6319     BB->addSuccessor(DispatchBB);
6320
6321     // Find the invoke call and mark all of the callee-saved registers as
6322     // 'implicit defined' so that they're spilled. This prevents code from
6323     // moving instructions to before the EH block, where they will never be
6324     // executed.
6325     for (MachineBasicBlock::reverse_iterator
6326            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6327       if (!II->isCall()) continue;
6328
6329       DenseMap<unsigned, bool> DefRegs;
6330       for (MachineInstr::mop_iterator
6331              OI = II->operands_begin(), OE = II->operands_end();
6332            OI != OE; ++OI) {
6333         if (!OI->isReg()) continue;
6334         DefRegs[OI->getReg()] = true;
6335       }
6336
6337       MachineInstrBuilder MIB(&*II);
6338
6339       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6340         unsigned Reg = SavedRegs[i];
6341         if (Subtarget->isThumb2() &&
6342             !ARM::tGPRRegClass.contains(Reg) &&
6343             !ARM::hGPRRegClass.contains(Reg))
6344           continue;
6345         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6346           continue;
6347         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6348           continue;
6349         if (!DefRegs[Reg])
6350           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6351       }
6352
6353       break;
6354     }
6355   }
6356
6357   // Mark all former landing pads as non-landing pads. The dispatch is the only
6358   // landing pad now.
6359   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6360          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6361     (*I)->setIsLandingPad(false);
6362
6363   // The instruction is gone now.
6364   MI->eraseFromParent();
6365
6366   return MBB;
6367 }
6368
6369 static
6370 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6371   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6372        E = MBB->succ_end(); I != E; ++I)
6373     if (*I != Succ)
6374       return *I;
6375   llvm_unreachable("Expecting a BB with two successors!");
6376 }
6377
6378 MachineBasicBlock *ARMTargetLowering::
6379 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6380   // This pseudo instruction has 3 operands: dst, src, size
6381   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6382   // Otherwise, we will generate unrolled scalar copies.
6383   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6384   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6385   MachineFunction::iterator It = BB;
6386   ++It;
6387
6388   unsigned dest = MI->getOperand(0).getReg();
6389   unsigned src = MI->getOperand(1).getReg();
6390   unsigned SizeVal = MI->getOperand(2).getImm();
6391   unsigned Align = MI->getOperand(3).getImm();
6392   DebugLoc dl = MI->getDebugLoc();
6393
6394   bool isThumb2 = Subtarget->isThumb2();
6395   MachineFunction *MF = BB->getParent();
6396   MachineRegisterInfo &MRI = MF->getRegInfo();
6397   unsigned ldrOpc, strOpc, UnitSize = 0;
6398
6399   const TargetRegisterClass *TRC = isThumb2 ?
6400     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6401     (const TargetRegisterClass*)&ARM::GPRRegClass;
6402   const TargetRegisterClass *TRC_Vec = 0;
6403
6404   if (Align & 1) {
6405     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6406     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6407     UnitSize = 1;
6408   } else if (Align & 2) {
6409     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6410     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6411     UnitSize = 2;
6412   } else {
6413     // Check whether we can use NEON instructions.
6414     if (!MF->getFunction()->getFnAttributes().
6415           hasAttribute(Attributes::NoImplicitFloat) &&
6416         Subtarget->hasNEON()) {
6417       if ((Align % 16 == 0) && SizeVal >= 16) {
6418         ldrOpc = ARM::VLD1q32wb_fixed;
6419         strOpc = ARM::VST1q32wb_fixed;
6420         UnitSize = 16;
6421         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6422       }
6423       else if ((Align % 8 == 0) && SizeVal >= 8) {
6424         ldrOpc = ARM::VLD1d32wb_fixed;
6425         strOpc = ARM::VST1d32wb_fixed;
6426         UnitSize = 8;
6427         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6428       }
6429     }
6430     // Can't use NEON instructions.
6431     if (UnitSize == 0) {
6432       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6433       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6434       UnitSize = 4;
6435     }
6436   }
6437
6438   unsigned BytesLeft = SizeVal % UnitSize;
6439   unsigned LoopSize = SizeVal - BytesLeft;
6440
6441   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6442     // Use LDR and STR to copy.
6443     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6444     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6445     unsigned srcIn = src;
6446     unsigned destIn = dest;
6447     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6448       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6449       unsigned srcOut = MRI.createVirtualRegister(TRC);
6450       unsigned destOut = MRI.createVirtualRegister(TRC);
6451       if (UnitSize >= 8) {
6452         AddDefaultPred(BuildMI(*BB, MI, dl,
6453           TII->get(ldrOpc), scratch)
6454           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6455
6456         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6457           .addReg(destIn).addImm(0).addReg(scratch));
6458       } else if (isThumb2) {
6459         AddDefaultPred(BuildMI(*BB, MI, dl,
6460           TII->get(ldrOpc), scratch)
6461           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6462
6463         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6464           .addReg(scratch).addReg(destIn)
6465           .addImm(UnitSize));
6466       } else {
6467         AddDefaultPred(BuildMI(*BB, MI, dl,
6468           TII->get(ldrOpc), scratch)
6469           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6470           .addImm(UnitSize));
6471
6472         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6473           .addReg(scratch).addReg(destIn)
6474           .addReg(0).addImm(UnitSize));
6475       }
6476       srcIn = srcOut;
6477       destIn = destOut;
6478     }
6479
6480     // Handle the leftover bytes with LDRB and STRB.
6481     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6482     // [destOut] = STRB_POST(scratch, destIn, 1)
6483     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6484     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6485     for (unsigned i = 0; i < BytesLeft; i++) {
6486       unsigned scratch = MRI.createVirtualRegister(TRC);
6487       unsigned srcOut = MRI.createVirtualRegister(TRC);
6488       unsigned destOut = MRI.createVirtualRegister(TRC);
6489       if (isThumb2) {
6490         AddDefaultPred(BuildMI(*BB, MI, dl,
6491           TII->get(ldrOpc),scratch)
6492           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6493
6494         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6495           .addReg(scratch).addReg(destIn)
6496           .addReg(0).addImm(1));
6497       } else {
6498         AddDefaultPred(BuildMI(*BB, MI, dl,
6499           TII->get(ldrOpc),scratch)
6500           .addReg(srcOut, RegState::Define).addReg(srcIn)
6501           .addReg(0).addImm(1));
6502
6503         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6504           .addReg(scratch).addReg(destIn)
6505           .addReg(0).addImm(1));
6506       }
6507       srcIn = srcOut;
6508       destIn = destOut;
6509     }
6510     MI->eraseFromParent();   // The instruction is gone now.
6511     return BB;
6512   }
6513
6514   // Expand the pseudo op to a loop.
6515   // thisMBB:
6516   //   ...
6517   //   movw varEnd, # --> with thumb2
6518   //   movt varEnd, #
6519   //   ldrcp varEnd, idx --> without thumb2
6520   //   fallthrough --> loopMBB
6521   // loopMBB:
6522   //   PHI varPhi, varEnd, varLoop
6523   //   PHI srcPhi, src, srcLoop
6524   //   PHI destPhi, dst, destLoop
6525   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6526   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6527   //   subs varLoop, varPhi, #UnitSize
6528   //   bne loopMBB
6529   //   fallthrough --> exitMBB
6530   // exitMBB:
6531   //   epilogue to handle left-over bytes
6532   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6533   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6534   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6535   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6536   MF->insert(It, loopMBB);
6537   MF->insert(It, exitMBB);
6538
6539   // Transfer the remainder of BB and its successor edges to exitMBB.
6540   exitMBB->splice(exitMBB->begin(), BB,
6541                   llvm::next(MachineBasicBlock::iterator(MI)),
6542                   BB->end());
6543   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6544
6545   // Load an immediate to varEnd.
6546   unsigned varEnd = MRI.createVirtualRegister(TRC);
6547   if (isThumb2) {
6548     unsigned VReg1 = varEnd;
6549     if ((LoopSize & 0xFFFF0000) != 0)
6550       VReg1 = MRI.createVirtualRegister(TRC);
6551     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6552                    .addImm(LoopSize & 0xFFFF));
6553
6554     if ((LoopSize & 0xFFFF0000) != 0)
6555       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6556                      .addReg(VReg1)
6557                      .addImm(LoopSize >> 16));
6558   } else {
6559     MachineConstantPool *ConstantPool = MF->getConstantPool();
6560     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6561     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6562
6563     // MachineConstantPool wants an explicit alignment.
6564     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6565     if (Align == 0)
6566       Align = getDataLayout()->getTypeAllocSize(C->getType());
6567     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6568
6569     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6570                    .addReg(varEnd, RegState::Define)
6571                    .addConstantPoolIndex(Idx)
6572                    .addImm(0));
6573   }
6574   BB->addSuccessor(loopMBB);
6575
6576   // Generate the loop body:
6577   //   varPhi = PHI(varLoop, varEnd)
6578   //   srcPhi = PHI(srcLoop, src)
6579   //   destPhi = PHI(destLoop, dst)
6580   MachineBasicBlock *entryBB = BB;
6581   BB = loopMBB;
6582   unsigned varLoop = MRI.createVirtualRegister(TRC);
6583   unsigned varPhi = MRI.createVirtualRegister(TRC);
6584   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6585   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6586   unsigned destLoop = MRI.createVirtualRegister(TRC);
6587   unsigned destPhi = MRI.createVirtualRegister(TRC);
6588
6589   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6590     .addReg(varLoop).addMBB(loopMBB)
6591     .addReg(varEnd).addMBB(entryBB);
6592   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6593     .addReg(srcLoop).addMBB(loopMBB)
6594     .addReg(src).addMBB(entryBB);
6595   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6596     .addReg(destLoop).addMBB(loopMBB)
6597     .addReg(dest).addMBB(entryBB);
6598
6599   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6600   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6601   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6602   if (UnitSize >= 8) {
6603     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6604       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6605
6606     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6607       .addReg(destPhi).addImm(0).addReg(scratch));
6608   } else if (isThumb2) {
6609     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6610       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6611
6612     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6613       .addReg(scratch).addReg(destPhi)
6614       .addImm(UnitSize));
6615   } else {
6616     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6617       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6618       .addImm(UnitSize));
6619
6620     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6621       .addReg(scratch).addReg(destPhi)
6622       .addReg(0).addImm(UnitSize));
6623   }
6624
6625   // Decrement loop variable by UnitSize.
6626   MachineInstrBuilder MIB = BuildMI(BB, dl,
6627     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6628   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6629   MIB->getOperand(5).setReg(ARM::CPSR);
6630   MIB->getOperand(5).setIsDef(true);
6631
6632   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6633     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6634
6635   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6636   BB->addSuccessor(loopMBB);
6637   BB->addSuccessor(exitMBB);
6638
6639   // Add epilogue to handle BytesLeft.
6640   BB = exitMBB;
6641   MachineInstr *StartOfExit = exitMBB->begin();
6642   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6643   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6644
6645   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6646   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6647   unsigned srcIn = srcLoop;
6648   unsigned destIn = destLoop;
6649   for (unsigned i = 0; i < BytesLeft; i++) {
6650     unsigned scratch = MRI.createVirtualRegister(TRC);
6651     unsigned srcOut = MRI.createVirtualRegister(TRC);
6652     unsigned destOut = MRI.createVirtualRegister(TRC);
6653     if (isThumb2) {
6654       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6655         TII->get(ldrOpc),scratch)
6656         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6657
6658       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6659         .addReg(scratch).addReg(destIn)
6660         .addImm(1));
6661     } else {
6662       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6663         TII->get(ldrOpc),scratch)
6664         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6665
6666       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6667         .addReg(scratch).addReg(destIn)
6668         .addReg(0).addImm(1));
6669     }
6670     srcIn = srcOut;
6671     destIn = destOut;
6672   }
6673
6674   MI->eraseFromParent();   // The instruction is gone now.
6675   return BB;
6676 }
6677
6678 MachineBasicBlock *
6679 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6680                                                MachineBasicBlock *BB) const {
6681   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6682   DebugLoc dl = MI->getDebugLoc();
6683   bool isThumb2 = Subtarget->isThumb2();
6684   switch (MI->getOpcode()) {
6685   default: {
6686     MI->dump();
6687     llvm_unreachable("Unexpected instr type to insert");
6688   }
6689   // The Thumb2 pre-indexed stores have the same MI operands, they just
6690   // define them differently in the .td files from the isel patterns, so
6691   // they need pseudos.
6692   case ARM::t2STR_preidx:
6693     MI->setDesc(TII->get(ARM::t2STR_PRE));
6694     return BB;
6695   case ARM::t2STRB_preidx:
6696     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6697     return BB;
6698   case ARM::t2STRH_preidx:
6699     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6700     return BB;
6701
6702   case ARM::STRi_preidx:
6703   case ARM::STRBi_preidx: {
6704     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6705       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6706     // Decode the offset.
6707     unsigned Offset = MI->getOperand(4).getImm();
6708     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6709     Offset = ARM_AM::getAM2Offset(Offset);
6710     if (isSub)
6711       Offset = -Offset;
6712
6713     MachineMemOperand *MMO = *MI->memoperands_begin();
6714     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6715       .addOperand(MI->getOperand(0))  // Rn_wb
6716       .addOperand(MI->getOperand(1))  // Rt
6717       .addOperand(MI->getOperand(2))  // Rn
6718       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6719       .addOperand(MI->getOperand(5))  // pred
6720       .addOperand(MI->getOperand(6))
6721       .addMemOperand(MMO);
6722     MI->eraseFromParent();
6723     return BB;
6724   }
6725   case ARM::STRr_preidx:
6726   case ARM::STRBr_preidx:
6727   case ARM::STRH_preidx: {
6728     unsigned NewOpc;
6729     switch (MI->getOpcode()) {
6730     default: llvm_unreachable("unexpected opcode!");
6731     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6732     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6733     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6734     }
6735     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6736     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6737       MIB.addOperand(MI->getOperand(i));
6738     MI->eraseFromParent();
6739     return BB;
6740   }
6741   case ARM::ATOMIC_LOAD_ADD_I8:
6742      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6743   case ARM::ATOMIC_LOAD_ADD_I16:
6744      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6745   case ARM::ATOMIC_LOAD_ADD_I32:
6746      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6747
6748   case ARM::ATOMIC_LOAD_AND_I8:
6749      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6750   case ARM::ATOMIC_LOAD_AND_I16:
6751      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6752   case ARM::ATOMIC_LOAD_AND_I32:
6753      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6754
6755   case ARM::ATOMIC_LOAD_OR_I8:
6756      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6757   case ARM::ATOMIC_LOAD_OR_I16:
6758      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6759   case ARM::ATOMIC_LOAD_OR_I32:
6760      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6761
6762   case ARM::ATOMIC_LOAD_XOR_I8:
6763      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6764   case ARM::ATOMIC_LOAD_XOR_I16:
6765      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6766   case ARM::ATOMIC_LOAD_XOR_I32:
6767      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6768
6769   case ARM::ATOMIC_LOAD_NAND_I8:
6770      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6771   case ARM::ATOMIC_LOAD_NAND_I16:
6772      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6773   case ARM::ATOMIC_LOAD_NAND_I32:
6774      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6775
6776   case ARM::ATOMIC_LOAD_SUB_I8:
6777      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6778   case ARM::ATOMIC_LOAD_SUB_I16:
6779      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6780   case ARM::ATOMIC_LOAD_SUB_I32:
6781      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6782
6783   case ARM::ATOMIC_LOAD_MIN_I8:
6784      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6785   case ARM::ATOMIC_LOAD_MIN_I16:
6786      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6787   case ARM::ATOMIC_LOAD_MIN_I32:
6788      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6789
6790   case ARM::ATOMIC_LOAD_MAX_I8:
6791      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6792   case ARM::ATOMIC_LOAD_MAX_I16:
6793      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6794   case ARM::ATOMIC_LOAD_MAX_I32:
6795      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6796
6797   case ARM::ATOMIC_LOAD_UMIN_I8:
6798      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6799   case ARM::ATOMIC_LOAD_UMIN_I16:
6800      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6801   case ARM::ATOMIC_LOAD_UMIN_I32:
6802      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6803
6804   case ARM::ATOMIC_LOAD_UMAX_I8:
6805      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6806   case ARM::ATOMIC_LOAD_UMAX_I16:
6807      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6808   case ARM::ATOMIC_LOAD_UMAX_I32:
6809      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6810
6811   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6812   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6813   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6814
6815   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6816   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6817   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6818
6819
6820   case ARM::ATOMADD6432:
6821     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6822                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6823                               /*NeedsCarry*/ true);
6824   case ARM::ATOMSUB6432:
6825     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6826                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6827                               /*NeedsCarry*/ true);
6828   case ARM::ATOMOR6432:
6829     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6830                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6831   case ARM::ATOMXOR6432:
6832     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6833                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6834   case ARM::ATOMAND6432:
6835     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6836                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6837   case ARM::ATOMSWAP6432:
6838     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6839   case ARM::ATOMCMPXCHG6432:
6840     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6841                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6842                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6843
6844   case ARM::tMOVCCr_pseudo: {
6845     // To "insert" a SELECT_CC instruction, we actually have to insert the
6846     // diamond control-flow pattern.  The incoming instruction knows the
6847     // destination vreg to set, the condition code register to branch on, the
6848     // true/false values to select between, and a branch opcode to use.
6849     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6850     MachineFunction::iterator It = BB;
6851     ++It;
6852
6853     //  thisMBB:
6854     //  ...
6855     //   TrueVal = ...
6856     //   cmpTY ccX, r1, r2
6857     //   bCC copy1MBB
6858     //   fallthrough --> copy0MBB
6859     MachineBasicBlock *thisMBB  = BB;
6860     MachineFunction *F = BB->getParent();
6861     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6862     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6863     F->insert(It, copy0MBB);
6864     F->insert(It, sinkMBB);
6865
6866     // Transfer the remainder of BB and its successor edges to sinkMBB.
6867     sinkMBB->splice(sinkMBB->begin(), BB,
6868                     llvm::next(MachineBasicBlock::iterator(MI)),
6869                     BB->end());
6870     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6871
6872     BB->addSuccessor(copy0MBB);
6873     BB->addSuccessor(sinkMBB);
6874
6875     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6876       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6877
6878     //  copy0MBB:
6879     //   %FalseValue = ...
6880     //   # fallthrough to sinkMBB
6881     BB = copy0MBB;
6882
6883     // Update machine-CFG edges
6884     BB->addSuccessor(sinkMBB);
6885
6886     //  sinkMBB:
6887     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6888     //  ...
6889     BB = sinkMBB;
6890     BuildMI(*BB, BB->begin(), dl,
6891             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6892       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6893       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6894
6895     MI->eraseFromParent();   // The pseudo instruction is gone now.
6896     return BB;
6897   }
6898
6899   case ARM::BCCi64:
6900   case ARM::BCCZi64: {
6901     // If there is an unconditional branch to the other successor, remove it.
6902     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6903
6904     // Compare both parts that make up the double comparison separately for
6905     // equality.
6906     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6907
6908     unsigned LHS1 = MI->getOperand(1).getReg();
6909     unsigned LHS2 = MI->getOperand(2).getReg();
6910     if (RHSisZero) {
6911       AddDefaultPred(BuildMI(BB, dl,
6912                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6913                      .addReg(LHS1).addImm(0));
6914       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6915         .addReg(LHS2).addImm(0)
6916         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6917     } else {
6918       unsigned RHS1 = MI->getOperand(3).getReg();
6919       unsigned RHS2 = MI->getOperand(4).getReg();
6920       AddDefaultPred(BuildMI(BB, dl,
6921                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6922                      .addReg(LHS1).addReg(RHS1));
6923       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6924         .addReg(LHS2).addReg(RHS2)
6925         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6926     }
6927
6928     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6929     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6930     if (MI->getOperand(0).getImm() == ARMCC::NE)
6931       std::swap(destMBB, exitMBB);
6932
6933     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6934       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6935     if (isThumb2)
6936       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6937     else
6938       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6939
6940     MI->eraseFromParent();   // The pseudo instruction is gone now.
6941     return BB;
6942   }
6943
6944   case ARM::Int_eh_sjlj_setjmp:
6945   case ARM::Int_eh_sjlj_setjmp_nofp:
6946   case ARM::tInt_eh_sjlj_setjmp:
6947   case ARM::t2Int_eh_sjlj_setjmp:
6948   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6949     EmitSjLjDispatchBlock(MI, BB);
6950     return BB;
6951
6952   case ARM::ABS:
6953   case ARM::t2ABS: {
6954     // To insert an ABS instruction, we have to insert the
6955     // diamond control-flow pattern.  The incoming instruction knows the
6956     // source vreg to test against 0, the destination vreg to set,
6957     // the condition code register to branch on, the
6958     // true/false values to select between, and a branch opcode to use.
6959     // It transforms
6960     //     V1 = ABS V0
6961     // into
6962     //     V2 = MOVS V0
6963     //     BCC                      (branch to SinkBB if V0 >= 0)
6964     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6965     //     SinkBB: V1 = PHI(V2, V3)
6966     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6967     MachineFunction::iterator BBI = BB;
6968     ++BBI;
6969     MachineFunction *Fn = BB->getParent();
6970     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6971     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6972     Fn->insert(BBI, RSBBB);
6973     Fn->insert(BBI, SinkBB);
6974
6975     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6976     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6977     bool isThumb2 = Subtarget->isThumb2();
6978     MachineRegisterInfo &MRI = Fn->getRegInfo();
6979     // In Thumb mode S must not be specified if source register is the SP or
6980     // PC and if destination register is the SP, so restrict register class
6981     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6982       (const TargetRegisterClass*)&ARM::rGPRRegClass :
6983       (const TargetRegisterClass*)&ARM::GPRRegClass);
6984
6985     // Transfer the remainder of BB and its successor edges to sinkMBB.
6986     SinkBB->splice(SinkBB->begin(), BB,
6987       llvm::next(MachineBasicBlock::iterator(MI)),
6988       BB->end());
6989     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6990
6991     BB->addSuccessor(RSBBB);
6992     BB->addSuccessor(SinkBB);
6993
6994     // fall through to SinkMBB
6995     RSBBB->addSuccessor(SinkBB);
6996
6997     // insert a cmp at the end of BB
6998     AddDefaultPred(BuildMI(BB, dl,
6999                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7000                    .addReg(ABSSrcReg).addImm(0));
7001
7002     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7003     BuildMI(BB, dl,
7004       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7005       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7006
7007     // insert rsbri in RSBBB
7008     // Note: BCC and rsbri will be converted into predicated rsbmi
7009     // by if-conversion pass
7010     BuildMI(*RSBBB, RSBBB->begin(), dl,
7011       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7012       .addReg(ABSSrcReg, RegState::Kill)
7013       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7014
7015     // insert PHI in SinkBB,
7016     // reuse ABSDstReg to not change uses of ABS instruction
7017     BuildMI(*SinkBB, SinkBB->begin(), dl,
7018       TII->get(ARM::PHI), ABSDstReg)
7019       .addReg(NewRsbDstReg).addMBB(RSBBB)
7020       .addReg(ABSSrcReg).addMBB(BB);
7021
7022     // remove ABS instruction
7023     MI->eraseFromParent();
7024
7025     // return last added BB
7026     return SinkBB;
7027   }
7028   case ARM::COPY_STRUCT_BYVAL_I32:
7029     ++NumLoopByVals;
7030     return EmitStructByval(MI, BB);
7031   }
7032 }
7033
7034 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7035                                                       SDNode *Node) const {
7036   if (!MI->hasPostISelHook()) {
7037     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7038            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7039     return;
7040   }
7041
7042   const MCInstrDesc *MCID = &MI->getDesc();
7043   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7044   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7045   // operand is still set to noreg. If needed, set the optional operand's
7046   // register to CPSR, and remove the redundant implicit def.
7047   //
7048   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7049
7050   // Rename pseudo opcodes.
7051   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7052   if (NewOpc) {
7053     const ARMBaseInstrInfo *TII =
7054       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7055     MCID = &TII->get(NewOpc);
7056
7057     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7058            "converted opcode should be the same except for cc_out");
7059
7060     MI->setDesc(*MCID);
7061
7062     // Add the optional cc_out operand
7063     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7064   }
7065   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7066
7067   // Any ARM instruction that sets the 's' bit should specify an optional
7068   // "cc_out" operand in the last operand position.
7069   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7070     assert(!NewOpc && "Optional cc_out operand required");
7071     return;
7072   }
7073   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7074   // since we already have an optional CPSR def.
7075   bool definesCPSR = false;
7076   bool deadCPSR = false;
7077   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7078        i != e; ++i) {
7079     const MachineOperand &MO = MI->getOperand(i);
7080     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7081       definesCPSR = true;
7082       if (MO.isDead())
7083         deadCPSR = true;
7084       MI->RemoveOperand(i);
7085       break;
7086     }
7087   }
7088   if (!definesCPSR) {
7089     assert(!NewOpc && "Optional cc_out operand required");
7090     return;
7091   }
7092   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7093   if (deadCPSR) {
7094     assert(!MI->getOperand(ccOutIdx).getReg() &&
7095            "expect uninitialized optional cc_out operand");
7096     return;
7097   }
7098
7099   // If this instruction was defined with an optional CPSR def and its dag node
7100   // had a live implicit CPSR def, then activate the optional CPSR def.
7101   MachineOperand &MO = MI->getOperand(ccOutIdx);
7102   MO.setReg(ARM::CPSR);
7103   MO.setIsDef(true);
7104 }
7105
7106 //===----------------------------------------------------------------------===//
7107 //                           ARM Optimization Hooks
7108 //===----------------------------------------------------------------------===//
7109
7110 // Helper function that checks if N is a null or all ones constant.
7111 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7112   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7113   if (!C)
7114     return false;
7115   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7116 }
7117
7118 // Return true if N is conditionally 0 or all ones.
7119 // Detects these expressions where cc is an i1 value:
7120 //
7121 //   (select cc 0, y)   [AllOnes=0]
7122 //   (select cc y, 0)   [AllOnes=0]
7123 //   (zext cc)          [AllOnes=0]
7124 //   (sext cc)          [AllOnes=0/1]
7125 //   (select cc -1, y)  [AllOnes=1]
7126 //   (select cc y, -1)  [AllOnes=1]
7127 //
7128 // Invert is set when N is the null/all ones constant when CC is false.
7129 // OtherOp is set to the alternative value of N.
7130 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7131                                        SDValue &CC, bool &Invert,
7132                                        SDValue &OtherOp,
7133                                        SelectionDAG &DAG) {
7134   switch (N->getOpcode()) {
7135   default: return false;
7136   case ISD::SELECT: {
7137     CC = N->getOperand(0);
7138     SDValue N1 = N->getOperand(1);
7139     SDValue N2 = N->getOperand(2);
7140     if (isZeroOrAllOnes(N1, AllOnes)) {
7141       Invert = false;
7142       OtherOp = N2;
7143       return true;
7144     }
7145     if (isZeroOrAllOnes(N2, AllOnes)) {
7146       Invert = true;
7147       OtherOp = N1;
7148       return true;
7149     }
7150     return false;
7151   }
7152   case ISD::ZERO_EXTEND:
7153     // (zext cc) can never be the all ones value.
7154     if (AllOnes)
7155       return false;
7156     // Fall through.
7157   case ISD::SIGN_EXTEND: {
7158     EVT VT = N->getValueType(0);
7159     CC = N->getOperand(0);
7160     if (CC.getValueType() != MVT::i1)
7161       return false;
7162     Invert = !AllOnes;
7163     if (AllOnes)
7164       // When looking for an AllOnes constant, N is an sext, and the 'other'
7165       // value is 0.
7166       OtherOp = DAG.getConstant(0, VT);
7167     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7168       // When looking for a 0 constant, N can be zext or sext.
7169       OtherOp = DAG.getConstant(1, VT);
7170     else
7171       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7172     return true;
7173   }
7174   }
7175 }
7176
7177 // Combine a constant select operand into its use:
7178 //
7179 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7180 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7181 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7182 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7183 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7184 //
7185 // The transform is rejected if the select doesn't have a constant operand that
7186 // is null, or all ones when AllOnes is set.
7187 //
7188 // Also recognize sext/zext from i1:
7189 //
7190 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7191 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7192 //
7193 // These transformations eventually create predicated instructions.
7194 //
7195 // @param N       The node to transform.
7196 // @param Slct    The N operand that is a select.
7197 // @param OtherOp The other N operand (x above).
7198 // @param DCI     Context.
7199 // @param AllOnes Require the select constant to be all ones instead of null.
7200 // @returns The new node, or SDValue() on failure.
7201 static
7202 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7203                             TargetLowering::DAGCombinerInfo &DCI,
7204                             bool AllOnes = false) {
7205   SelectionDAG &DAG = DCI.DAG;
7206   EVT VT = N->getValueType(0);
7207   SDValue NonConstantVal;
7208   SDValue CCOp;
7209   bool SwapSelectOps;
7210   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7211                                   NonConstantVal, DAG))
7212     return SDValue();
7213
7214   // Slct is now know to be the desired identity constant when CC is true.
7215   SDValue TrueVal = OtherOp;
7216   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7217                                  OtherOp, NonConstantVal);
7218   // Unless SwapSelectOps says CC should be false.
7219   if (SwapSelectOps)
7220     std::swap(TrueVal, FalseVal);
7221
7222   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7223                      CCOp, TrueVal, FalseVal);
7224 }
7225
7226 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7227 static
7228 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7229                                        TargetLowering::DAGCombinerInfo &DCI) {
7230   SDValue N0 = N->getOperand(0);
7231   SDValue N1 = N->getOperand(1);
7232   if (N0.getNode()->hasOneUse()) {
7233     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7234     if (Result.getNode())
7235       return Result;
7236   }
7237   if (N1.getNode()->hasOneUse()) {
7238     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7239     if (Result.getNode())
7240       return Result;
7241   }
7242   return SDValue();
7243 }
7244
7245 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7246 // (only after legalization).
7247 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7248                                  TargetLowering::DAGCombinerInfo &DCI,
7249                                  const ARMSubtarget *Subtarget) {
7250
7251   // Only perform optimization if after legalize, and if NEON is available. We
7252   // also expected both operands to be BUILD_VECTORs.
7253   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7254       || N0.getOpcode() != ISD::BUILD_VECTOR
7255       || N1.getOpcode() != ISD::BUILD_VECTOR)
7256     return SDValue();
7257
7258   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7259   EVT VT = N->getValueType(0);
7260   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7261     return SDValue();
7262
7263   // Check that the vector operands are of the right form.
7264   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7265   // operands, where N is the size of the formed vector.
7266   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7267   // index such that we have a pair wise add pattern.
7268
7269   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7270   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7271     return SDValue();
7272   SDValue Vec = N0->getOperand(0)->getOperand(0);
7273   SDNode *V = Vec.getNode();
7274   unsigned nextIndex = 0;
7275
7276   // For each operands to the ADD which are BUILD_VECTORs,
7277   // check to see if each of their operands are an EXTRACT_VECTOR with
7278   // the same vector and appropriate index.
7279   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7280     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7281         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7282
7283       SDValue ExtVec0 = N0->getOperand(i);
7284       SDValue ExtVec1 = N1->getOperand(i);
7285
7286       // First operand is the vector, verify its the same.
7287       if (V != ExtVec0->getOperand(0).getNode() ||
7288           V != ExtVec1->getOperand(0).getNode())
7289         return SDValue();
7290
7291       // Second is the constant, verify its correct.
7292       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7293       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7294
7295       // For the constant, we want to see all the even or all the odd.
7296       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7297           || C1->getZExtValue() != nextIndex+1)
7298         return SDValue();
7299
7300       // Increment index.
7301       nextIndex+=2;
7302     } else
7303       return SDValue();
7304   }
7305
7306   // Create VPADDL node.
7307   SelectionDAG &DAG = DCI.DAG;
7308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7309
7310   // Build operand list.
7311   SmallVector<SDValue, 8> Ops;
7312   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7313                                 TLI.getPointerTy()));
7314
7315   // Input is the vector.
7316   Ops.push_back(Vec);
7317
7318   // Get widened type and narrowed type.
7319   MVT widenType;
7320   unsigned numElem = VT.getVectorNumElements();
7321   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7322     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7323     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7324     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7325     default:
7326       llvm_unreachable("Invalid vector element type for padd optimization.");
7327   }
7328
7329   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7330                             widenType, &Ops[0], Ops.size());
7331   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7332 }
7333
7334 static SDValue findMUL_LOHI(SDValue V) {
7335   if (V->getOpcode() == ISD::UMUL_LOHI ||
7336       V->getOpcode() == ISD::SMUL_LOHI)
7337     return V;
7338   return SDValue();
7339 }
7340
7341 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7342                                      TargetLowering::DAGCombinerInfo &DCI,
7343                                      const ARMSubtarget *Subtarget) {
7344
7345   if (Subtarget->isThumb1Only()) return SDValue();
7346
7347   // Only perform the checks after legalize when the pattern is available.
7348   if (DCI.isBeforeLegalize()) return SDValue();
7349
7350   // Look for multiply add opportunities.
7351   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7352   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7353   // a glue link from the first add to the second add.
7354   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7355   // a S/UMLAL instruction.
7356   //          loAdd   UMUL_LOHI
7357   //            \    / :lo    \ :hi
7358   //             \  /          \          [no multiline comment]
7359   //              ADDC         |  hiAdd
7360   //                 \ :glue  /  /
7361   //                  \      /  /
7362   //                    ADDE
7363   //
7364   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7365   SDValue AddcOp0 = AddcNode->getOperand(0);
7366   SDValue AddcOp1 = AddcNode->getOperand(1);
7367
7368   // Check if the two operands are from the same mul_lohi node.
7369   if (AddcOp0.getNode() == AddcOp1.getNode())
7370     return SDValue();
7371
7372   assert(AddcNode->getNumValues() == 2 &&
7373          AddcNode->getValueType(0) == MVT::i32 &&
7374          AddcNode->getValueType(1) == MVT::Glue &&
7375          "Expect ADDC with two result values: i32, glue");
7376
7377   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7378   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7379       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7380       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7381       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7382     return SDValue();
7383
7384   // Look for the glued ADDE.
7385   SDNode* AddeNode = AddcNode->getGluedUser();
7386   if (AddeNode == NULL)
7387     return SDValue();
7388
7389   // Make sure it is really an ADDE.
7390   if (AddeNode->getOpcode() != ISD::ADDE)
7391     return SDValue();
7392
7393   assert(AddeNode->getNumOperands() == 3 &&
7394          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7395          "ADDE node has the wrong inputs");
7396
7397   // Check for the triangle shape.
7398   SDValue AddeOp0 = AddeNode->getOperand(0);
7399   SDValue AddeOp1 = AddeNode->getOperand(1);
7400
7401   // Make sure that the ADDE operands are not coming from the same node.
7402   if (AddeOp0.getNode() == AddeOp1.getNode())
7403     return SDValue();
7404
7405   // Find the MUL_LOHI node walking up ADDE's operands.
7406   bool IsLeftOperandMUL = false;
7407   SDValue MULOp = findMUL_LOHI(AddeOp0);
7408   if (MULOp == SDValue())
7409    MULOp = findMUL_LOHI(AddeOp1);
7410   else
7411     IsLeftOperandMUL = true;
7412   if (MULOp == SDValue())
7413      return SDValue();
7414
7415   // Figure out the right opcode.
7416   unsigned Opc = MULOp->getOpcode();
7417   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7418
7419   // Figure out the high and low input values to the MLAL node.
7420   SDValue* HiMul = &MULOp;
7421   SDValue* HiAdd = NULL;
7422   SDValue* LoMul = NULL;
7423   SDValue* LowAdd = NULL;
7424
7425   if (IsLeftOperandMUL)
7426     HiAdd = &AddeOp1;
7427   else
7428     HiAdd = &AddeOp0;
7429
7430
7431   if (AddcOp0->getOpcode() == Opc) {
7432     LoMul = &AddcOp0;
7433     LowAdd = &AddcOp1;
7434   }
7435   if (AddcOp1->getOpcode() == Opc) {
7436     LoMul = &AddcOp1;
7437     LowAdd = &AddcOp0;
7438   }
7439
7440   if (LoMul == NULL)
7441     return SDValue();
7442
7443   if (LoMul->getNode() != HiMul->getNode())
7444     return SDValue();
7445
7446   // Create the merged node.
7447   SelectionDAG &DAG = DCI.DAG;
7448
7449   // Build operand list.
7450   SmallVector<SDValue, 8> Ops;
7451   Ops.push_back(LoMul->getOperand(0));
7452   Ops.push_back(LoMul->getOperand(1));
7453   Ops.push_back(*LowAdd);
7454   Ops.push_back(*HiAdd);
7455
7456   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7457                                  DAG.getVTList(MVT::i32, MVT::i32),
7458                                  &Ops[0], Ops.size());
7459
7460   // Replace the ADDs' nodes uses by the MLA node's values.
7461   SDValue HiMLALResult(MLALNode.getNode(), 1);
7462   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7463
7464   SDValue LoMLALResult(MLALNode.getNode(), 0);
7465   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7466
7467   // Return original node to notify the driver to stop replacing.
7468   SDValue resNode(AddcNode, 0);
7469   return resNode;
7470 }
7471
7472 /// PerformADDCCombine - Target-specific dag combine transform from
7473 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7474 static SDValue PerformADDCCombine(SDNode *N,
7475                                  TargetLowering::DAGCombinerInfo &DCI,
7476                                  const ARMSubtarget *Subtarget) {
7477
7478   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7479
7480 }
7481
7482 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7483 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7484 /// called with the default operands, and if that fails, with commuted
7485 /// operands.
7486 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7487                                           TargetLowering::DAGCombinerInfo &DCI,
7488                                           const ARMSubtarget *Subtarget){
7489
7490   // Attempt to create vpaddl for this add.
7491   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7492   if (Result.getNode())
7493     return Result;
7494
7495   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7496   if (N0.getNode()->hasOneUse()) {
7497     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7498     if (Result.getNode()) return Result;
7499   }
7500   return SDValue();
7501 }
7502
7503 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7504 ///
7505 static SDValue PerformADDCombine(SDNode *N,
7506                                  TargetLowering::DAGCombinerInfo &DCI,
7507                                  const ARMSubtarget *Subtarget) {
7508   SDValue N0 = N->getOperand(0);
7509   SDValue N1 = N->getOperand(1);
7510
7511   // First try with the default operand order.
7512   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7513   if (Result.getNode())
7514     return Result;
7515
7516   // If that didn't work, try again with the operands commuted.
7517   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7518 }
7519
7520 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7521 ///
7522 static SDValue PerformSUBCombine(SDNode *N,
7523                                  TargetLowering::DAGCombinerInfo &DCI) {
7524   SDValue N0 = N->getOperand(0);
7525   SDValue N1 = N->getOperand(1);
7526
7527   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7528   if (N1.getNode()->hasOneUse()) {
7529     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7530     if (Result.getNode()) return Result;
7531   }
7532
7533   return SDValue();
7534 }
7535
7536 /// PerformVMULCombine
7537 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7538 /// special multiplier accumulator forwarding.
7539 ///   vmul d3, d0, d2
7540 ///   vmla d3, d1, d2
7541 /// is faster than
7542 ///   vadd d3, d0, d1
7543 ///   vmul d3, d3, d2
7544 static SDValue PerformVMULCombine(SDNode *N,
7545                                   TargetLowering::DAGCombinerInfo &DCI,
7546                                   const ARMSubtarget *Subtarget) {
7547   if (!Subtarget->hasVMLxForwarding())
7548     return SDValue();
7549
7550   SelectionDAG &DAG = DCI.DAG;
7551   SDValue N0 = N->getOperand(0);
7552   SDValue N1 = N->getOperand(1);
7553   unsigned Opcode = N0.getOpcode();
7554   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7555       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7556     Opcode = N1.getOpcode();
7557     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7558         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7559       return SDValue();
7560     std::swap(N0, N1);
7561   }
7562
7563   EVT VT = N->getValueType(0);
7564   DebugLoc DL = N->getDebugLoc();
7565   SDValue N00 = N0->getOperand(0);
7566   SDValue N01 = N0->getOperand(1);
7567   return DAG.getNode(Opcode, DL, VT,
7568                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7569                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7570 }
7571
7572 static SDValue PerformMULCombine(SDNode *N,
7573                                  TargetLowering::DAGCombinerInfo &DCI,
7574                                  const ARMSubtarget *Subtarget) {
7575   SelectionDAG &DAG = DCI.DAG;
7576
7577   if (Subtarget->isThumb1Only())
7578     return SDValue();
7579
7580   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7581     return SDValue();
7582
7583   EVT VT = N->getValueType(0);
7584   if (VT.is64BitVector() || VT.is128BitVector())
7585     return PerformVMULCombine(N, DCI, Subtarget);
7586   if (VT != MVT::i32)
7587     return SDValue();
7588
7589   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7590   if (!C)
7591     return SDValue();
7592
7593   int64_t MulAmt = C->getSExtValue();
7594   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7595
7596   ShiftAmt = ShiftAmt & (32 - 1);
7597   SDValue V = N->getOperand(0);
7598   DebugLoc DL = N->getDebugLoc();
7599
7600   SDValue Res;
7601   MulAmt >>= ShiftAmt;
7602
7603   if (MulAmt >= 0) {
7604     if (isPowerOf2_32(MulAmt - 1)) {
7605       // (mul x, 2^N + 1) => (add (shl x, N), x)
7606       Res = DAG.getNode(ISD::ADD, DL, VT,
7607                         V,
7608                         DAG.getNode(ISD::SHL, DL, VT,
7609                                     V,
7610                                     DAG.getConstant(Log2_32(MulAmt - 1),
7611                                                     MVT::i32)));
7612     } else if (isPowerOf2_32(MulAmt + 1)) {
7613       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7614       Res = DAG.getNode(ISD::SUB, DL, VT,
7615                         DAG.getNode(ISD::SHL, DL, VT,
7616                                     V,
7617                                     DAG.getConstant(Log2_32(MulAmt + 1),
7618                                                     MVT::i32)),
7619                         V);
7620     } else
7621       return SDValue();
7622   } else {
7623     uint64_t MulAmtAbs = -MulAmt;
7624     if (isPowerOf2_32(MulAmtAbs + 1)) {
7625       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7626       Res = DAG.getNode(ISD::SUB, DL, VT,
7627                         V,
7628                         DAG.getNode(ISD::SHL, DL, VT,
7629                                     V,
7630                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7631                                                     MVT::i32)));
7632     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7633       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7634       Res = DAG.getNode(ISD::ADD, DL, VT,
7635                         V,
7636                         DAG.getNode(ISD::SHL, DL, VT,
7637                                     V,
7638                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7639                                                     MVT::i32)));
7640       Res = DAG.getNode(ISD::SUB, DL, VT,
7641                         DAG.getConstant(0, MVT::i32),Res);
7642
7643     } else
7644       return SDValue();
7645   }
7646
7647   if (ShiftAmt != 0)
7648     Res = DAG.getNode(ISD::SHL, DL, VT,
7649                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7650
7651   // Do not add new nodes to DAG combiner worklist.
7652   DCI.CombineTo(N, Res, false);
7653   return SDValue();
7654 }
7655
7656 static SDValue PerformANDCombine(SDNode *N,
7657                                  TargetLowering::DAGCombinerInfo &DCI,
7658                                  const ARMSubtarget *Subtarget) {
7659
7660   // Attempt to use immediate-form VBIC
7661   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7662   DebugLoc dl = N->getDebugLoc();
7663   EVT VT = N->getValueType(0);
7664   SelectionDAG &DAG = DCI.DAG;
7665
7666   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7667     return SDValue();
7668
7669   APInt SplatBits, SplatUndef;
7670   unsigned SplatBitSize;
7671   bool HasAnyUndefs;
7672   if (BVN &&
7673       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7674     if (SplatBitSize <= 64) {
7675       EVT VbicVT;
7676       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7677                                       SplatUndef.getZExtValue(), SplatBitSize,
7678                                       DAG, VbicVT, VT.is128BitVector(),
7679                                       OtherModImm);
7680       if (Val.getNode()) {
7681         SDValue Input =
7682           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7683         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7684         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7685       }
7686     }
7687   }
7688
7689   if (!Subtarget->isThumb1Only()) {
7690     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7691     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7692     if (Result.getNode())
7693       return Result;
7694   }
7695
7696   return SDValue();
7697 }
7698
7699 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7700 static SDValue PerformORCombine(SDNode *N,
7701                                 TargetLowering::DAGCombinerInfo &DCI,
7702                                 const ARMSubtarget *Subtarget) {
7703   // Attempt to use immediate-form VORR
7704   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7705   DebugLoc dl = N->getDebugLoc();
7706   EVT VT = N->getValueType(0);
7707   SelectionDAG &DAG = DCI.DAG;
7708
7709   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7710     return SDValue();
7711
7712   APInt SplatBits, SplatUndef;
7713   unsigned SplatBitSize;
7714   bool HasAnyUndefs;
7715   if (BVN && Subtarget->hasNEON() &&
7716       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7717     if (SplatBitSize <= 64) {
7718       EVT VorrVT;
7719       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7720                                       SplatUndef.getZExtValue(), SplatBitSize,
7721                                       DAG, VorrVT, VT.is128BitVector(),
7722                                       OtherModImm);
7723       if (Val.getNode()) {
7724         SDValue Input =
7725           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7726         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7727         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7728       }
7729     }
7730   }
7731
7732   if (!Subtarget->isThumb1Only()) {
7733     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7734     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7735     if (Result.getNode())
7736       return Result;
7737   }
7738
7739   // The code below optimizes (or (and X, Y), Z).
7740   // The AND operand needs to have a single user to make these optimizations
7741   // profitable.
7742   SDValue N0 = N->getOperand(0);
7743   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7744     return SDValue();
7745   SDValue N1 = N->getOperand(1);
7746
7747   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7748   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7749       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7750     APInt SplatUndef;
7751     unsigned SplatBitSize;
7752     bool HasAnyUndefs;
7753
7754     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7755     APInt SplatBits0;
7756     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7757                                   HasAnyUndefs) && !HasAnyUndefs) {
7758       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7759       APInt SplatBits1;
7760       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7761                                     HasAnyUndefs) && !HasAnyUndefs &&
7762           SplatBits0 == ~SplatBits1) {
7763         // Canonicalize the vector type to make instruction selection simpler.
7764         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7765         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7766                                      N0->getOperand(1), N0->getOperand(0),
7767                                      N1->getOperand(0));
7768         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7769       }
7770     }
7771   }
7772
7773   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7774   // reasonable.
7775
7776   // BFI is only available on V6T2+
7777   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7778     return SDValue();
7779
7780   DebugLoc DL = N->getDebugLoc();
7781   // 1) or (and A, mask), val => ARMbfi A, val, mask
7782   //      iff (val & mask) == val
7783   //
7784   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7785   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7786   //          && mask == ~mask2
7787   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7788   //          && ~mask == mask2
7789   //  (i.e., copy a bitfield value into another bitfield of the same width)
7790
7791   if (VT != MVT::i32)
7792     return SDValue();
7793
7794   SDValue N00 = N0.getOperand(0);
7795
7796   // The value and the mask need to be constants so we can verify this is
7797   // actually a bitfield set. If the mask is 0xffff, we can do better
7798   // via a movt instruction, so don't use BFI in that case.
7799   SDValue MaskOp = N0.getOperand(1);
7800   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7801   if (!MaskC)
7802     return SDValue();
7803   unsigned Mask = MaskC->getZExtValue();
7804   if (Mask == 0xffff)
7805     return SDValue();
7806   SDValue Res;
7807   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7808   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7809   if (N1C) {
7810     unsigned Val = N1C->getZExtValue();
7811     if ((Val & ~Mask) != Val)
7812       return SDValue();
7813
7814     if (ARM::isBitFieldInvertedMask(Mask)) {
7815       Val >>= CountTrailingZeros_32(~Mask);
7816
7817       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7818                         DAG.getConstant(Val, MVT::i32),
7819                         DAG.getConstant(Mask, MVT::i32));
7820
7821       // Do not add new nodes to DAG combiner worklist.
7822       DCI.CombineTo(N, Res, false);
7823       return SDValue();
7824     }
7825   } else if (N1.getOpcode() == ISD::AND) {
7826     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7827     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7828     if (!N11C)
7829       return SDValue();
7830     unsigned Mask2 = N11C->getZExtValue();
7831
7832     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7833     // as is to match.
7834     if (ARM::isBitFieldInvertedMask(Mask) &&
7835         (Mask == ~Mask2)) {
7836       // The pack halfword instruction works better for masks that fit it,
7837       // so use that when it's available.
7838       if (Subtarget->hasT2ExtractPack() &&
7839           (Mask == 0xffff || Mask == 0xffff0000))
7840         return SDValue();
7841       // 2a
7842       unsigned amt = CountTrailingZeros_32(Mask2);
7843       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7844                         DAG.getConstant(amt, MVT::i32));
7845       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7846                         DAG.getConstant(Mask, MVT::i32));
7847       // Do not add new nodes to DAG combiner worklist.
7848       DCI.CombineTo(N, Res, false);
7849       return SDValue();
7850     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7851                (~Mask == Mask2)) {
7852       // The pack halfword instruction works better for masks that fit it,
7853       // so use that when it's available.
7854       if (Subtarget->hasT2ExtractPack() &&
7855           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7856         return SDValue();
7857       // 2b
7858       unsigned lsb = CountTrailingZeros_32(Mask);
7859       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7860                         DAG.getConstant(lsb, MVT::i32));
7861       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7862                         DAG.getConstant(Mask2, MVT::i32));
7863       // Do not add new nodes to DAG combiner worklist.
7864       DCI.CombineTo(N, Res, false);
7865       return SDValue();
7866     }
7867   }
7868
7869   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7870       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7871       ARM::isBitFieldInvertedMask(~Mask)) {
7872     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7873     // where lsb(mask) == #shamt and masked bits of B are known zero.
7874     SDValue ShAmt = N00.getOperand(1);
7875     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7876     unsigned LSB = CountTrailingZeros_32(Mask);
7877     if (ShAmtC != LSB)
7878       return SDValue();
7879
7880     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7881                       DAG.getConstant(~Mask, MVT::i32));
7882
7883     // Do not add new nodes to DAG combiner worklist.
7884     DCI.CombineTo(N, Res, false);
7885   }
7886
7887   return SDValue();
7888 }
7889
7890 static SDValue PerformXORCombine(SDNode *N,
7891                                  TargetLowering::DAGCombinerInfo &DCI,
7892                                  const ARMSubtarget *Subtarget) {
7893   EVT VT = N->getValueType(0);
7894   SelectionDAG &DAG = DCI.DAG;
7895
7896   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7897     return SDValue();
7898
7899   if (!Subtarget->isThumb1Only()) {
7900     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7901     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7902     if (Result.getNode())
7903       return Result;
7904   }
7905
7906   return SDValue();
7907 }
7908
7909 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7910 /// the bits being cleared by the AND are not demanded by the BFI.
7911 static SDValue PerformBFICombine(SDNode *N,
7912                                  TargetLowering::DAGCombinerInfo &DCI) {
7913   SDValue N1 = N->getOperand(1);
7914   if (N1.getOpcode() == ISD::AND) {
7915     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7916     if (!N11C)
7917       return SDValue();
7918     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7919     unsigned LSB = CountTrailingZeros_32(~InvMask);
7920     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7921     unsigned Mask = (1 << Width)-1;
7922     unsigned Mask2 = N11C->getZExtValue();
7923     if ((Mask & (~Mask2)) == 0)
7924       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7925                              N->getOperand(0), N1.getOperand(0),
7926                              N->getOperand(2));
7927   }
7928   return SDValue();
7929 }
7930
7931 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7932 /// ARMISD::VMOVRRD.
7933 static SDValue PerformVMOVRRDCombine(SDNode *N,
7934                                      TargetLowering::DAGCombinerInfo &DCI) {
7935   // vmovrrd(vmovdrr x, y) -> x,y
7936   SDValue InDouble = N->getOperand(0);
7937   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7938     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7939
7940   // vmovrrd(load f64) -> (load i32), (load i32)
7941   SDNode *InNode = InDouble.getNode();
7942   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7943       InNode->getValueType(0) == MVT::f64 &&
7944       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7945       !cast<LoadSDNode>(InNode)->isVolatile()) {
7946     // TODO: Should this be done for non-FrameIndex operands?
7947     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7948
7949     SelectionDAG &DAG = DCI.DAG;
7950     DebugLoc DL = LD->getDebugLoc();
7951     SDValue BasePtr = LD->getBasePtr();
7952     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7953                                  LD->getPointerInfo(), LD->isVolatile(),
7954                                  LD->isNonTemporal(), LD->isInvariant(),
7955                                  LD->getAlignment());
7956
7957     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7958                                     DAG.getConstant(4, MVT::i32));
7959     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7960                                  LD->getPointerInfo(), LD->isVolatile(),
7961                                  LD->isNonTemporal(), LD->isInvariant(),
7962                                  std::min(4U, LD->getAlignment() / 2));
7963
7964     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7965     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7966     DCI.RemoveFromWorklist(LD);
7967     DAG.DeleteNode(LD);
7968     return Result;
7969   }
7970
7971   return SDValue();
7972 }
7973
7974 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7975 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7976 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7977   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7978   SDValue Op0 = N->getOperand(0);
7979   SDValue Op1 = N->getOperand(1);
7980   if (Op0.getOpcode() == ISD::BITCAST)
7981     Op0 = Op0.getOperand(0);
7982   if (Op1.getOpcode() == ISD::BITCAST)
7983     Op1 = Op1.getOperand(0);
7984   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7985       Op0.getNode() == Op1.getNode() &&
7986       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7987     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7988                        N->getValueType(0), Op0.getOperand(0));
7989   return SDValue();
7990 }
7991
7992 /// PerformSTORECombine - Target-specific dag combine xforms for
7993 /// ISD::STORE.
7994 static SDValue PerformSTORECombine(SDNode *N,
7995                                    TargetLowering::DAGCombinerInfo &DCI) {
7996   StoreSDNode *St = cast<StoreSDNode>(N);
7997   if (St->isVolatile())
7998     return SDValue();
7999
8000   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8001   // pack all of the elements in one place.  Next, store to memory in fewer
8002   // chunks.
8003   SDValue StVal = St->getValue();
8004   EVT VT = StVal.getValueType();
8005   if (St->isTruncatingStore() && VT.isVector()) {
8006     SelectionDAG &DAG = DCI.DAG;
8007     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8008     EVT StVT = St->getMemoryVT();
8009     unsigned NumElems = VT.getVectorNumElements();
8010     assert(StVT != VT && "Cannot truncate to the same type");
8011     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8012     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8013
8014     // From, To sizes and ElemCount must be pow of two
8015     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8016
8017     // We are going to use the original vector elt for storing.
8018     // Accumulated smaller vector elements must be a multiple of the store size.
8019     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8020
8021     unsigned SizeRatio  = FromEltSz / ToEltSz;
8022     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8023
8024     // Create a type on which we perform the shuffle.
8025     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8026                                      NumElems*SizeRatio);
8027     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8028
8029     DebugLoc DL = St->getDebugLoc();
8030     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8031     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8032     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8033
8034     // Can't shuffle using an illegal type.
8035     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8036
8037     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8038                                 DAG.getUNDEF(WideVec.getValueType()),
8039                                 ShuffleVec.data());
8040     // At this point all of the data is stored at the bottom of the
8041     // register. We now need to save it to mem.
8042
8043     // Find the largest store unit
8044     MVT StoreType = MVT::i8;
8045     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8046          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8047       MVT Tp = (MVT::SimpleValueType)tp;
8048       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8049         StoreType = Tp;
8050     }
8051     // Didn't find a legal store type.
8052     if (!TLI.isTypeLegal(StoreType))
8053       return SDValue();
8054
8055     // Bitcast the original vector into a vector of store-size units
8056     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8057             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8058     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8059     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8060     SmallVector<SDValue, 8> Chains;
8061     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8062                                         TLI.getPointerTy());
8063     SDValue BasePtr = St->getBasePtr();
8064
8065     // Perform one or more big stores into memory.
8066     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8067     for (unsigned I = 0; I < E; I++) {
8068       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8069                                    StoreType, ShuffWide,
8070                                    DAG.getIntPtrConstant(I));
8071       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8072                                 St->getPointerInfo(), St->isVolatile(),
8073                                 St->isNonTemporal(), St->getAlignment());
8074       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8075                             Increment);
8076       Chains.push_back(Ch);
8077     }
8078     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8079                        Chains.size());
8080   }
8081
8082   if (!ISD::isNormalStore(St))
8083     return SDValue();
8084
8085   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8086   // ARM stores of arguments in the same cache line.
8087   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8088       StVal.getNode()->hasOneUse()) {
8089     SelectionDAG  &DAG = DCI.DAG;
8090     DebugLoc DL = St->getDebugLoc();
8091     SDValue BasePtr = St->getBasePtr();
8092     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8093                                   StVal.getNode()->getOperand(0), BasePtr,
8094                                   St->getPointerInfo(), St->isVolatile(),
8095                                   St->isNonTemporal(), St->getAlignment());
8096
8097     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8098                                     DAG.getConstant(4, MVT::i32));
8099     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8100                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8101                         St->isNonTemporal(),
8102                         std::min(4U, St->getAlignment() / 2));
8103   }
8104
8105   if (StVal.getValueType() != MVT::i64 ||
8106       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8107     return SDValue();
8108
8109   // Bitcast an i64 store extracted from a vector to f64.
8110   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8111   SelectionDAG &DAG = DCI.DAG;
8112   DebugLoc dl = StVal.getDebugLoc();
8113   SDValue IntVec = StVal.getOperand(0);
8114   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8115                                  IntVec.getValueType().getVectorNumElements());
8116   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8117   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8118                                Vec, StVal.getOperand(1));
8119   dl = N->getDebugLoc();
8120   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8121   // Make the DAGCombiner fold the bitcasts.
8122   DCI.AddToWorklist(Vec.getNode());
8123   DCI.AddToWorklist(ExtElt.getNode());
8124   DCI.AddToWorklist(V.getNode());
8125   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8126                       St->getPointerInfo(), St->isVolatile(),
8127                       St->isNonTemporal(), St->getAlignment(),
8128                       St->getTBAAInfo());
8129 }
8130
8131 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8132 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8133 /// i64 vector to have f64 elements, since the value can then be loaded
8134 /// directly into a VFP register.
8135 static bool hasNormalLoadOperand(SDNode *N) {
8136   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8137   for (unsigned i = 0; i < NumElts; ++i) {
8138     SDNode *Elt = N->getOperand(i).getNode();
8139     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8140       return true;
8141   }
8142   return false;
8143 }
8144
8145 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8146 /// ISD::BUILD_VECTOR.
8147 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8148                                           TargetLowering::DAGCombinerInfo &DCI){
8149   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8150   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8151   // into a pair of GPRs, which is fine when the value is used as a scalar,
8152   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8153   SelectionDAG &DAG = DCI.DAG;
8154   if (N->getNumOperands() == 2) {
8155     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8156     if (RV.getNode())
8157       return RV;
8158   }
8159
8160   // Load i64 elements as f64 values so that type legalization does not split
8161   // them up into i32 values.
8162   EVT VT = N->getValueType(0);
8163   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8164     return SDValue();
8165   DebugLoc dl = N->getDebugLoc();
8166   SmallVector<SDValue, 8> Ops;
8167   unsigned NumElts = VT.getVectorNumElements();
8168   for (unsigned i = 0; i < NumElts; ++i) {
8169     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8170     Ops.push_back(V);
8171     // Make the DAGCombiner fold the bitcast.
8172     DCI.AddToWorklist(V.getNode());
8173   }
8174   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8175   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8176   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8177 }
8178
8179 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8180 /// ISD::INSERT_VECTOR_ELT.
8181 static SDValue PerformInsertEltCombine(SDNode *N,
8182                                        TargetLowering::DAGCombinerInfo &DCI) {
8183   // Bitcast an i64 load inserted into a vector to f64.
8184   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8185   EVT VT = N->getValueType(0);
8186   SDNode *Elt = N->getOperand(1).getNode();
8187   if (VT.getVectorElementType() != MVT::i64 ||
8188       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8189     return SDValue();
8190
8191   SelectionDAG &DAG = DCI.DAG;
8192   DebugLoc dl = N->getDebugLoc();
8193   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8194                                  VT.getVectorNumElements());
8195   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8196   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8197   // Make the DAGCombiner fold the bitcasts.
8198   DCI.AddToWorklist(Vec.getNode());
8199   DCI.AddToWorklist(V.getNode());
8200   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8201                                Vec, V, N->getOperand(2));
8202   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8203 }
8204
8205 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8206 /// ISD::VECTOR_SHUFFLE.
8207 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8208   // The LLVM shufflevector instruction does not require the shuffle mask
8209   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8210   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8211   // operands do not match the mask length, they are extended by concatenating
8212   // them with undef vectors.  That is probably the right thing for other
8213   // targets, but for NEON it is better to concatenate two double-register
8214   // size vector operands into a single quad-register size vector.  Do that
8215   // transformation here:
8216   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8217   //   shuffle(concat(v1, v2), undef)
8218   SDValue Op0 = N->getOperand(0);
8219   SDValue Op1 = N->getOperand(1);
8220   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8221       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8222       Op0.getNumOperands() != 2 ||
8223       Op1.getNumOperands() != 2)
8224     return SDValue();
8225   SDValue Concat0Op1 = Op0.getOperand(1);
8226   SDValue Concat1Op1 = Op1.getOperand(1);
8227   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8228       Concat1Op1.getOpcode() != ISD::UNDEF)
8229     return SDValue();
8230   // Skip the transformation if any of the types are illegal.
8231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8232   EVT VT = N->getValueType(0);
8233   if (!TLI.isTypeLegal(VT) ||
8234       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8235       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8236     return SDValue();
8237
8238   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8239                                   Op0.getOperand(0), Op1.getOperand(0));
8240   // Translate the shuffle mask.
8241   SmallVector<int, 16> NewMask;
8242   unsigned NumElts = VT.getVectorNumElements();
8243   unsigned HalfElts = NumElts/2;
8244   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8245   for (unsigned n = 0; n < NumElts; ++n) {
8246     int MaskElt = SVN->getMaskElt(n);
8247     int NewElt = -1;
8248     if (MaskElt < (int)HalfElts)
8249       NewElt = MaskElt;
8250     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8251       NewElt = HalfElts + MaskElt - NumElts;
8252     NewMask.push_back(NewElt);
8253   }
8254   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8255                               DAG.getUNDEF(VT), NewMask.data());
8256 }
8257
8258 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8259 /// NEON load/store intrinsics to merge base address updates.
8260 static SDValue CombineBaseUpdate(SDNode *N,
8261                                  TargetLowering::DAGCombinerInfo &DCI) {
8262   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8263     return SDValue();
8264
8265   SelectionDAG &DAG = DCI.DAG;
8266   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8267                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8268   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8269   SDValue Addr = N->getOperand(AddrOpIdx);
8270
8271   // Search for a use of the address operand that is an increment.
8272   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8273          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8274     SDNode *User = *UI;
8275     if (User->getOpcode() != ISD::ADD ||
8276         UI.getUse().getResNo() != Addr.getResNo())
8277       continue;
8278
8279     // Check that the add is independent of the load/store.  Otherwise, folding
8280     // it would create a cycle.
8281     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8282       continue;
8283
8284     // Find the new opcode for the updating load/store.
8285     bool isLoad = true;
8286     bool isLaneOp = false;
8287     unsigned NewOpc = 0;
8288     unsigned NumVecs = 0;
8289     if (isIntrinsic) {
8290       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8291       switch (IntNo) {
8292       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8293       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8294         NumVecs = 1; break;
8295       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8296         NumVecs = 2; break;
8297       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8298         NumVecs = 3; break;
8299       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8300         NumVecs = 4; break;
8301       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8302         NumVecs = 2; isLaneOp = true; break;
8303       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8304         NumVecs = 3; isLaneOp = true; break;
8305       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8306         NumVecs = 4; isLaneOp = true; break;
8307       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8308         NumVecs = 1; isLoad = false; break;
8309       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8310         NumVecs = 2; isLoad = false; break;
8311       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8312         NumVecs = 3; isLoad = false; break;
8313       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8314         NumVecs = 4; isLoad = false; break;
8315       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8316         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8317       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8318         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8319       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8320         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8321       }
8322     } else {
8323       isLaneOp = true;
8324       switch (N->getOpcode()) {
8325       default: llvm_unreachable("unexpected opcode for Neon base update");
8326       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8327       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8328       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8329       }
8330     }
8331
8332     // Find the size of memory referenced by the load/store.
8333     EVT VecTy;
8334     if (isLoad)
8335       VecTy = N->getValueType(0);
8336     else
8337       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8338     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8339     if (isLaneOp)
8340       NumBytes /= VecTy.getVectorNumElements();
8341
8342     // If the increment is a constant, it must match the memory ref size.
8343     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8344     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8345       uint64_t IncVal = CInc->getZExtValue();
8346       if (IncVal != NumBytes)
8347         continue;
8348     } else if (NumBytes >= 3 * 16) {
8349       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8350       // separate instructions that make it harder to use a non-constant update.
8351       continue;
8352     }
8353
8354     // Create the new updating load/store node.
8355     EVT Tys[6];
8356     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8357     unsigned n;
8358     for (n = 0; n < NumResultVecs; ++n)
8359       Tys[n] = VecTy;
8360     Tys[n++] = MVT::i32;
8361     Tys[n] = MVT::Other;
8362     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8363     SmallVector<SDValue, 8> Ops;
8364     Ops.push_back(N->getOperand(0)); // incoming chain
8365     Ops.push_back(N->getOperand(AddrOpIdx));
8366     Ops.push_back(Inc);
8367     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8368       Ops.push_back(N->getOperand(i));
8369     }
8370     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8371     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8372                                            Ops.data(), Ops.size(),
8373                                            MemInt->getMemoryVT(),
8374                                            MemInt->getMemOperand());
8375
8376     // Update the uses.
8377     std::vector<SDValue> NewResults;
8378     for (unsigned i = 0; i < NumResultVecs; ++i) {
8379       NewResults.push_back(SDValue(UpdN.getNode(), i));
8380     }
8381     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8382     DCI.CombineTo(N, NewResults);
8383     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8384
8385     break;
8386   }
8387   return SDValue();
8388 }
8389
8390 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8391 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8392 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8393 /// return true.
8394 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8395   SelectionDAG &DAG = DCI.DAG;
8396   EVT VT = N->getValueType(0);
8397   // vldN-dup instructions only support 64-bit vectors for N > 1.
8398   if (!VT.is64BitVector())
8399     return false;
8400
8401   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8402   SDNode *VLD = N->getOperand(0).getNode();
8403   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8404     return false;
8405   unsigned NumVecs = 0;
8406   unsigned NewOpc = 0;
8407   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8408   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8409     NumVecs = 2;
8410     NewOpc = ARMISD::VLD2DUP;
8411   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8412     NumVecs = 3;
8413     NewOpc = ARMISD::VLD3DUP;
8414   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8415     NumVecs = 4;
8416     NewOpc = ARMISD::VLD4DUP;
8417   } else {
8418     return false;
8419   }
8420
8421   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8422   // numbers match the load.
8423   unsigned VLDLaneNo =
8424     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8425   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8426        UI != UE; ++UI) {
8427     // Ignore uses of the chain result.
8428     if (UI.getUse().getResNo() == NumVecs)
8429       continue;
8430     SDNode *User = *UI;
8431     if (User->getOpcode() != ARMISD::VDUPLANE ||
8432         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8433       return false;
8434   }
8435
8436   // Create the vldN-dup node.
8437   EVT Tys[5];
8438   unsigned n;
8439   for (n = 0; n < NumVecs; ++n)
8440     Tys[n] = VT;
8441   Tys[n] = MVT::Other;
8442   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8443   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8444   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8445   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8446                                            Ops, 2, VLDMemInt->getMemoryVT(),
8447                                            VLDMemInt->getMemOperand());
8448
8449   // Update the uses.
8450   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8451        UI != UE; ++UI) {
8452     unsigned ResNo = UI.getUse().getResNo();
8453     // Ignore uses of the chain result.
8454     if (ResNo == NumVecs)
8455       continue;
8456     SDNode *User = *UI;
8457     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8458   }
8459
8460   // Now the vldN-lane intrinsic is dead except for its chain result.
8461   // Update uses of the chain.
8462   std::vector<SDValue> VLDDupResults;
8463   for (unsigned n = 0; n < NumVecs; ++n)
8464     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8465   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8466   DCI.CombineTo(VLD, VLDDupResults);
8467
8468   return true;
8469 }
8470
8471 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8472 /// ARMISD::VDUPLANE.
8473 static SDValue PerformVDUPLANECombine(SDNode *N,
8474                                       TargetLowering::DAGCombinerInfo &DCI) {
8475   SDValue Op = N->getOperand(0);
8476
8477   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8478   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8479   if (CombineVLDDUP(N, DCI))
8480     return SDValue(N, 0);
8481
8482   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8483   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8484   while (Op.getOpcode() == ISD::BITCAST)
8485     Op = Op.getOperand(0);
8486   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8487     return SDValue();
8488
8489   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8490   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8491   // The canonical VMOV for a zero vector uses a 32-bit element size.
8492   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8493   unsigned EltBits;
8494   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8495     EltSize = 8;
8496   EVT VT = N->getValueType(0);
8497   if (EltSize > VT.getVectorElementType().getSizeInBits())
8498     return SDValue();
8499
8500   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8501 }
8502
8503 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8504 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8505 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8506 {
8507   integerPart cN;
8508   integerPart c0 = 0;
8509   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8510        I != E; I++) {
8511     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8512     if (!C)
8513       return false;
8514
8515     bool isExact;
8516     APFloat APF = C->getValueAPF();
8517     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8518         != APFloat::opOK || !isExact)
8519       return false;
8520
8521     c0 = (I == 0) ? cN : c0;
8522     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8523       return false;
8524   }
8525   C = c0;
8526   return true;
8527 }
8528
8529 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8530 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8531 /// when the VMUL has a constant operand that is a power of 2.
8532 ///
8533 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8534 ///  vmul.f32        d16, d17, d16
8535 ///  vcvt.s32.f32    d16, d16
8536 /// becomes:
8537 ///  vcvt.s32.f32    d16, d16, #3
8538 static SDValue PerformVCVTCombine(SDNode *N,
8539                                   TargetLowering::DAGCombinerInfo &DCI,
8540                                   const ARMSubtarget *Subtarget) {
8541   SelectionDAG &DAG = DCI.DAG;
8542   SDValue Op = N->getOperand(0);
8543
8544   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8545       Op.getOpcode() != ISD::FMUL)
8546     return SDValue();
8547
8548   uint64_t C;
8549   SDValue N0 = Op->getOperand(0);
8550   SDValue ConstVec = Op->getOperand(1);
8551   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8552
8553   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8554       !isConstVecPow2(ConstVec, isSigned, C))
8555     return SDValue();
8556
8557   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8558     Intrinsic::arm_neon_vcvtfp2fxu;
8559   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8560                      N->getValueType(0),
8561                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8562                      DAG.getConstant(Log2_64(C), MVT::i32));
8563 }
8564
8565 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8566 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8567 /// when the VDIV has a constant operand that is a power of 2.
8568 ///
8569 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8570 ///  vcvt.f32.s32    d16, d16
8571 ///  vdiv.f32        d16, d17, d16
8572 /// becomes:
8573 ///  vcvt.f32.s32    d16, d16, #3
8574 static SDValue PerformVDIVCombine(SDNode *N,
8575                                   TargetLowering::DAGCombinerInfo &DCI,
8576                                   const ARMSubtarget *Subtarget) {
8577   SelectionDAG &DAG = DCI.DAG;
8578   SDValue Op = N->getOperand(0);
8579   unsigned OpOpcode = Op.getNode()->getOpcode();
8580
8581   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8582       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8583     return SDValue();
8584
8585   uint64_t C;
8586   SDValue ConstVec = N->getOperand(1);
8587   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8588
8589   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8590       !isConstVecPow2(ConstVec, isSigned, C))
8591     return SDValue();
8592
8593   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8594     Intrinsic::arm_neon_vcvtfxu2fp;
8595   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8596                      Op.getValueType(),
8597                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8598                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8599 }
8600
8601 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8602 /// operand of a vector shift operation, where all the elements of the
8603 /// build_vector must have the same constant integer value.
8604 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8605   // Ignore bit_converts.
8606   while (Op.getOpcode() == ISD::BITCAST)
8607     Op = Op.getOperand(0);
8608   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8609   APInt SplatBits, SplatUndef;
8610   unsigned SplatBitSize;
8611   bool HasAnyUndefs;
8612   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8613                                       HasAnyUndefs, ElementBits) ||
8614       SplatBitSize > ElementBits)
8615     return false;
8616   Cnt = SplatBits.getSExtValue();
8617   return true;
8618 }
8619
8620 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8621 /// operand of a vector shift left operation.  That value must be in the range:
8622 ///   0 <= Value < ElementBits for a left shift; or
8623 ///   0 <= Value <= ElementBits for a long left shift.
8624 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8625   assert(VT.isVector() && "vector shift count is not a vector type");
8626   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8627   if (! getVShiftImm(Op, ElementBits, Cnt))
8628     return false;
8629   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8630 }
8631
8632 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8633 /// operand of a vector shift right operation.  For a shift opcode, the value
8634 /// is positive, but for an intrinsic the value count must be negative. The
8635 /// absolute value must be in the range:
8636 ///   1 <= |Value| <= ElementBits for a right shift; or
8637 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8638 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8639                          int64_t &Cnt) {
8640   assert(VT.isVector() && "vector shift count is not a vector type");
8641   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8642   if (! getVShiftImm(Op, ElementBits, Cnt))
8643     return false;
8644   if (isIntrinsic)
8645     Cnt = -Cnt;
8646   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8647 }
8648
8649 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8650 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8651   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8652   switch (IntNo) {
8653   default:
8654     // Don't do anything for most intrinsics.
8655     break;
8656
8657   // Vector shifts: check for immediate versions and lower them.
8658   // Note: This is done during DAG combining instead of DAG legalizing because
8659   // the build_vectors for 64-bit vector element shift counts are generally
8660   // not legal, and it is hard to see their values after they get legalized to
8661   // loads from a constant pool.
8662   case Intrinsic::arm_neon_vshifts:
8663   case Intrinsic::arm_neon_vshiftu:
8664   case Intrinsic::arm_neon_vshiftls:
8665   case Intrinsic::arm_neon_vshiftlu:
8666   case Intrinsic::arm_neon_vshiftn:
8667   case Intrinsic::arm_neon_vrshifts:
8668   case Intrinsic::arm_neon_vrshiftu:
8669   case Intrinsic::arm_neon_vrshiftn:
8670   case Intrinsic::arm_neon_vqshifts:
8671   case Intrinsic::arm_neon_vqshiftu:
8672   case Intrinsic::arm_neon_vqshiftsu:
8673   case Intrinsic::arm_neon_vqshiftns:
8674   case Intrinsic::arm_neon_vqshiftnu:
8675   case Intrinsic::arm_neon_vqshiftnsu:
8676   case Intrinsic::arm_neon_vqrshiftns:
8677   case Intrinsic::arm_neon_vqrshiftnu:
8678   case Intrinsic::arm_neon_vqrshiftnsu: {
8679     EVT VT = N->getOperand(1).getValueType();
8680     int64_t Cnt;
8681     unsigned VShiftOpc = 0;
8682
8683     switch (IntNo) {
8684     case Intrinsic::arm_neon_vshifts:
8685     case Intrinsic::arm_neon_vshiftu:
8686       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8687         VShiftOpc = ARMISD::VSHL;
8688         break;
8689       }
8690       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8691         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8692                      ARMISD::VSHRs : ARMISD::VSHRu);
8693         break;
8694       }
8695       return SDValue();
8696
8697     case Intrinsic::arm_neon_vshiftls:
8698     case Intrinsic::arm_neon_vshiftlu:
8699       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8700         break;
8701       llvm_unreachable("invalid shift count for vshll intrinsic");
8702
8703     case Intrinsic::arm_neon_vrshifts:
8704     case Intrinsic::arm_neon_vrshiftu:
8705       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8706         break;
8707       return SDValue();
8708
8709     case Intrinsic::arm_neon_vqshifts:
8710     case Intrinsic::arm_neon_vqshiftu:
8711       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8712         break;
8713       return SDValue();
8714
8715     case Intrinsic::arm_neon_vqshiftsu:
8716       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8717         break;
8718       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8719
8720     case Intrinsic::arm_neon_vshiftn:
8721     case Intrinsic::arm_neon_vrshiftn:
8722     case Intrinsic::arm_neon_vqshiftns:
8723     case Intrinsic::arm_neon_vqshiftnu:
8724     case Intrinsic::arm_neon_vqshiftnsu:
8725     case Intrinsic::arm_neon_vqrshiftns:
8726     case Intrinsic::arm_neon_vqrshiftnu:
8727     case Intrinsic::arm_neon_vqrshiftnsu:
8728       // Narrowing shifts require an immediate right shift.
8729       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8730         break;
8731       llvm_unreachable("invalid shift count for narrowing vector shift "
8732                        "intrinsic");
8733
8734     default:
8735       llvm_unreachable("unhandled vector shift");
8736     }
8737
8738     switch (IntNo) {
8739     case Intrinsic::arm_neon_vshifts:
8740     case Intrinsic::arm_neon_vshiftu:
8741       // Opcode already set above.
8742       break;
8743     case Intrinsic::arm_neon_vshiftls:
8744     case Intrinsic::arm_neon_vshiftlu:
8745       if (Cnt == VT.getVectorElementType().getSizeInBits())
8746         VShiftOpc = ARMISD::VSHLLi;
8747       else
8748         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8749                      ARMISD::VSHLLs : ARMISD::VSHLLu);
8750       break;
8751     case Intrinsic::arm_neon_vshiftn:
8752       VShiftOpc = ARMISD::VSHRN; break;
8753     case Intrinsic::arm_neon_vrshifts:
8754       VShiftOpc = ARMISD::VRSHRs; break;
8755     case Intrinsic::arm_neon_vrshiftu:
8756       VShiftOpc = ARMISD::VRSHRu; break;
8757     case Intrinsic::arm_neon_vrshiftn:
8758       VShiftOpc = ARMISD::VRSHRN; break;
8759     case Intrinsic::arm_neon_vqshifts:
8760       VShiftOpc = ARMISD::VQSHLs; break;
8761     case Intrinsic::arm_neon_vqshiftu:
8762       VShiftOpc = ARMISD::VQSHLu; break;
8763     case Intrinsic::arm_neon_vqshiftsu:
8764       VShiftOpc = ARMISD::VQSHLsu; break;
8765     case Intrinsic::arm_neon_vqshiftns:
8766       VShiftOpc = ARMISD::VQSHRNs; break;
8767     case Intrinsic::arm_neon_vqshiftnu:
8768       VShiftOpc = ARMISD::VQSHRNu; break;
8769     case Intrinsic::arm_neon_vqshiftnsu:
8770       VShiftOpc = ARMISD::VQSHRNsu; break;
8771     case Intrinsic::arm_neon_vqrshiftns:
8772       VShiftOpc = ARMISD::VQRSHRNs; break;
8773     case Intrinsic::arm_neon_vqrshiftnu:
8774       VShiftOpc = ARMISD::VQRSHRNu; break;
8775     case Intrinsic::arm_neon_vqrshiftnsu:
8776       VShiftOpc = ARMISD::VQRSHRNsu; break;
8777     }
8778
8779     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8780                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8781   }
8782
8783   case Intrinsic::arm_neon_vshiftins: {
8784     EVT VT = N->getOperand(1).getValueType();
8785     int64_t Cnt;
8786     unsigned VShiftOpc = 0;
8787
8788     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8789       VShiftOpc = ARMISD::VSLI;
8790     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8791       VShiftOpc = ARMISD::VSRI;
8792     else {
8793       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8794     }
8795
8796     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8797                        N->getOperand(1), N->getOperand(2),
8798                        DAG.getConstant(Cnt, MVT::i32));
8799   }
8800
8801   case Intrinsic::arm_neon_vqrshifts:
8802   case Intrinsic::arm_neon_vqrshiftu:
8803     // No immediate versions of these to check for.
8804     break;
8805   }
8806
8807   return SDValue();
8808 }
8809
8810 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8811 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
8812 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8813 /// vector element shift counts are generally not legal, and it is hard to see
8814 /// their values after they get legalized to loads from a constant pool.
8815 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8816                                    const ARMSubtarget *ST) {
8817   EVT VT = N->getValueType(0);
8818   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8819     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8820     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8821     SDValue N1 = N->getOperand(1);
8822     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8823       SDValue N0 = N->getOperand(0);
8824       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8825           DAG.MaskedValueIsZero(N0.getOperand(0),
8826                                 APInt::getHighBitsSet(32, 16)))
8827         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8828     }
8829   }
8830
8831   // Nothing to be done for scalar shifts.
8832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8833   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8834     return SDValue();
8835
8836   assert(ST->hasNEON() && "unexpected vector shift");
8837   int64_t Cnt;
8838
8839   switch (N->getOpcode()) {
8840   default: llvm_unreachable("unexpected shift opcode");
8841
8842   case ISD::SHL:
8843     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8844       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8845                          DAG.getConstant(Cnt, MVT::i32));
8846     break;
8847
8848   case ISD::SRA:
8849   case ISD::SRL:
8850     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8851       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8852                             ARMISD::VSHRs : ARMISD::VSHRu);
8853       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8854                          DAG.getConstant(Cnt, MVT::i32));
8855     }
8856   }
8857   return SDValue();
8858 }
8859
8860 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8861 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8862 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8863                                     const ARMSubtarget *ST) {
8864   SDValue N0 = N->getOperand(0);
8865
8866   // Check for sign- and zero-extensions of vector extract operations of 8-
8867   // and 16-bit vector elements.  NEON supports these directly.  They are
8868   // handled during DAG combining because type legalization will promote them
8869   // to 32-bit types and it is messy to recognize the operations after that.
8870   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8871     SDValue Vec = N0.getOperand(0);
8872     SDValue Lane = N0.getOperand(1);
8873     EVT VT = N->getValueType(0);
8874     EVT EltVT = N0.getValueType();
8875     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8876
8877     if (VT == MVT::i32 &&
8878         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8879         TLI.isTypeLegal(Vec.getValueType()) &&
8880         isa<ConstantSDNode>(Lane)) {
8881
8882       unsigned Opc = 0;
8883       switch (N->getOpcode()) {
8884       default: llvm_unreachable("unexpected opcode");
8885       case ISD::SIGN_EXTEND:
8886         Opc = ARMISD::VGETLANEs;
8887         break;
8888       case ISD::ZERO_EXTEND:
8889       case ISD::ANY_EXTEND:
8890         Opc = ARMISD::VGETLANEu;
8891         break;
8892       }
8893       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8894     }
8895   }
8896
8897   return SDValue();
8898 }
8899
8900 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8901 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8902 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8903                                        const ARMSubtarget *ST) {
8904   // If the target supports NEON, try to use vmax/vmin instructions for f32
8905   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8906   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8907   // a NaN; only do the transformation when it matches that behavior.
8908
8909   // For now only do this when using NEON for FP operations; if using VFP, it
8910   // is not obvious that the benefit outweighs the cost of switching to the
8911   // NEON pipeline.
8912   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8913       N->getValueType(0) != MVT::f32)
8914     return SDValue();
8915
8916   SDValue CondLHS = N->getOperand(0);
8917   SDValue CondRHS = N->getOperand(1);
8918   SDValue LHS = N->getOperand(2);
8919   SDValue RHS = N->getOperand(3);
8920   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8921
8922   unsigned Opcode = 0;
8923   bool IsReversed;
8924   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8925     IsReversed = false; // x CC y ? x : y
8926   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8927     IsReversed = true ; // x CC y ? y : x
8928   } else {
8929     return SDValue();
8930   }
8931
8932   bool IsUnordered;
8933   switch (CC) {
8934   default: break;
8935   case ISD::SETOLT:
8936   case ISD::SETOLE:
8937   case ISD::SETLT:
8938   case ISD::SETLE:
8939   case ISD::SETULT:
8940   case ISD::SETULE:
8941     // If LHS is NaN, an ordered comparison will be false and the result will
8942     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8943     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8944     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8945     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8946       break;
8947     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8948     // will return -0, so vmin can only be used for unsafe math or if one of
8949     // the operands is known to be nonzero.
8950     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8951         !DAG.getTarget().Options.UnsafeFPMath &&
8952         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8953       break;
8954     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8955     break;
8956
8957   case ISD::SETOGT:
8958   case ISD::SETOGE:
8959   case ISD::SETGT:
8960   case ISD::SETGE:
8961   case ISD::SETUGT:
8962   case ISD::SETUGE:
8963     // If LHS is NaN, an ordered comparison will be false and the result will
8964     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8965     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8966     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8967     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8968       break;
8969     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8970     // will return +0, so vmax can only be used for unsafe math or if one of
8971     // the operands is known to be nonzero.
8972     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8973         !DAG.getTarget().Options.UnsafeFPMath &&
8974         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8975       break;
8976     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8977     break;
8978   }
8979
8980   if (!Opcode)
8981     return SDValue();
8982   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8983 }
8984
8985 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8986 SDValue
8987 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8988   SDValue Cmp = N->getOperand(4);
8989   if (Cmp.getOpcode() != ARMISD::CMPZ)
8990     // Only looking at EQ and NE cases.
8991     return SDValue();
8992
8993   EVT VT = N->getValueType(0);
8994   DebugLoc dl = N->getDebugLoc();
8995   SDValue LHS = Cmp.getOperand(0);
8996   SDValue RHS = Cmp.getOperand(1);
8997   SDValue FalseVal = N->getOperand(0);
8998   SDValue TrueVal = N->getOperand(1);
8999   SDValue ARMcc = N->getOperand(2);
9000   ARMCC::CondCodes CC =
9001     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9002
9003   // Simplify
9004   //   mov     r1, r0
9005   //   cmp     r1, x
9006   //   mov     r0, y
9007   //   moveq   r0, x
9008   // to
9009   //   cmp     r0, x
9010   //   movne   r0, y
9011   //
9012   //   mov     r1, r0
9013   //   cmp     r1, x
9014   //   mov     r0, x
9015   //   movne   r0, y
9016   // to
9017   //   cmp     r0, x
9018   //   movne   r0, y
9019   /// FIXME: Turn this into a target neutral optimization?
9020   SDValue Res;
9021   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9022     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9023                       N->getOperand(3), Cmp);
9024   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9025     SDValue ARMcc;
9026     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9027     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9028                       N->getOperand(3), NewCmp);
9029   }
9030
9031   if (Res.getNode()) {
9032     APInt KnownZero, KnownOne;
9033     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9034     // Capture demanded bits information that would be otherwise lost.
9035     if (KnownZero == 0xfffffffe)
9036       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9037                         DAG.getValueType(MVT::i1));
9038     else if (KnownZero == 0xffffff00)
9039       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9040                         DAG.getValueType(MVT::i8));
9041     else if (KnownZero == 0xffff0000)
9042       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9043                         DAG.getValueType(MVT::i16));
9044   }
9045
9046   return Res;
9047 }
9048
9049 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9050                                              DAGCombinerInfo &DCI) const {
9051   switch (N->getOpcode()) {
9052   default: break;
9053   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9054   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9055   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9056   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9057   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9058   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9059   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9060   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9061   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9062   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9063   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9064   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9065   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9066   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9067   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9068   case ISD::FP_TO_SINT:
9069   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9070   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9071   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9072   case ISD::SHL:
9073   case ISD::SRA:
9074   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9075   case ISD::SIGN_EXTEND:
9076   case ISD::ZERO_EXTEND:
9077   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9078   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9079   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9080   case ARMISD::VLD2DUP:
9081   case ARMISD::VLD3DUP:
9082   case ARMISD::VLD4DUP:
9083     return CombineBaseUpdate(N, DCI);
9084   case ISD::INTRINSIC_VOID:
9085   case ISD::INTRINSIC_W_CHAIN:
9086     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9087     case Intrinsic::arm_neon_vld1:
9088     case Intrinsic::arm_neon_vld2:
9089     case Intrinsic::arm_neon_vld3:
9090     case Intrinsic::arm_neon_vld4:
9091     case Intrinsic::arm_neon_vld2lane:
9092     case Intrinsic::arm_neon_vld3lane:
9093     case Intrinsic::arm_neon_vld4lane:
9094     case Intrinsic::arm_neon_vst1:
9095     case Intrinsic::arm_neon_vst2:
9096     case Intrinsic::arm_neon_vst3:
9097     case Intrinsic::arm_neon_vst4:
9098     case Intrinsic::arm_neon_vst2lane:
9099     case Intrinsic::arm_neon_vst3lane:
9100     case Intrinsic::arm_neon_vst4lane:
9101       return CombineBaseUpdate(N, DCI);
9102     default: break;
9103     }
9104     break;
9105   }
9106   return SDValue();
9107 }
9108
9109 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9110                                                           EVT VT) const {
9111   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9112 }
9113
9114 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9115   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9116   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9117
9118   switch (VT.getSimpleVT().SimpleTy) {
9119   default:
9120     return false;
9121   case MVT::i8:
9122   case MVT::i16:
9123   case MVT::i32:
9124     // Unaligned access can use (for example) LRDB, LRDH, LDR
9125     return AllowsUnaligned;
9126   case MVT::f64:
9127   case MVT::v2f64:
9128     // For any little-endian targets with neon, we can support unaligned ld/st
9129     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9130     // A big-endian target may also explictly support unaligned accesses
9131     return Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian());
9132   }
9133 }
9134
9135 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9136                        unsigned AlignCheck) {
9137   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9138           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9139 }
9140
9141 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9142                                            unsigned DstAlign, unsigned SrcAlign,
9143                                            bool IsZeroVal,
9144                                            bool MemcpyStrSrc,
9145                                            MachineFunction &MF) const {
9146   const Function *F = MF.getFunction();
9147
9148   // See if we can use NEON instructions for this...
9149   if (IsZeroVal &&
9150       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat) &&
9151       Subtarget->hasNEON()) {
9152     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9153       return MVT::v4i32;
9154     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9155       return MVT::v2i32;
9156     }
9157   }
9158
9159   // Lowering to i32/i16 if the size permits.
9160   if (Size >= 4) {
9161     return MVT::i32;
9162   } else if (Size >= 2) {
9163     return MVT::i16;
9164   }
9165
9166   // Let the target-independent logic figure it out.
9167   return MVT::Other;
9168 }
9169
9170 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9171   if (V < 0)
9172     return false;
9173
9174   unsigned Scale = 1;
9175   switch (VT.getSimpleVT().SimpleTy) {
9176   default: return false;
9177   case MVT::i1:
9178   case MVT::i8:
9179     // Scale == 1;
9180     break;
9181   case MVT::i16:
9182     // Scale == 2;
9183     Scale = 2;
9184     break;
9185   case MVT::i32:
9186     // Scale == 4;
9187     Scale = 4;
9188     break;
9189   }
9190
9191   if ((V & (Scale - 1)) != 0)
9192     return false;
9193   V /= Scale;
9194   return V == (V & ((1LL << 5) - 1));
9195 }
9196
9197 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9198                                       const ARMSubtarget *Subtarget) {
9199   bool isNeg = false;
9200   if (V < 0) {
9201     isNeg = true;
9202     V = - V;
9203   }
9204
9205   switch (VT.getSimpleVT().SimpleTy) {
9206   default: return false;
9207   case MVT::i1:
9208   case MVT::i8:
9209   case MVT::i16:
9210   case MVT::i32:
9211     // + imm12 or - imm8
9212     if (isNeg)
9213       return V == (V & ((1LL << 8) - 1));
9214     return V == (V & ((1LL << 12) - 1));
9215   case MVT::f32:
9216   case MVT::f64:
9217     // Same as ARM mode. FIXME: NEON?
9218     if (!Subtarget->hasVFP2())
9219       return false;
9220     if ((V & 3) != 0)
9221       return false;
9222     V >>= 2;
9223     return V == (V & ((1LL << 8) - 1));
9224   }
9225 }
9226
9227 /// isLegalAddressImmediate - Return true if the integer value can be used
9228 /// as the offset of the target addressing mode for load / store of the
9229 /// given type.
9230 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9231                                     const ARMSubtarget *Subtarget) {
9232   if (V == 0)
9233     return true;
9234
9235   if (!VT.isSimple())
9236     return false;
9237
9238   if (Subtarget->isThumb1Only())
9239     return isLegalT1AddressImmediate(V, VT);
9240   else if (Subtarget->isThumb2())
9241     return isLegalT2AddressImmediate(V, VT, Subtarget);
9242
9243   // ARM mode.
9244   if (V < 0)
9245     V = - V;
9246   switch (VT.getSimpleVT().SimpleTy) {
9247   default: return false;
9248   case MVT::i1:
9249   case MVT::i8:
9250   case MVT::i32:
9251     // +- imm12
9252     return V == (V & ((1LL << 12) - 1));
9253   case MVT::i16:
9254     // +- imm8
9255     return V == (V & ((1LL << 8) - 1));
9256   case MVT::f32:
9257   case MVT::f64:
9258     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9259       return false;
9260     if ((V & 3) != 0)
9261       return false;
9262     V >>= 2;
9263     return V == (V & ((1LL << 8) - 1));
9264   }
9265 }
9266
9267 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9268                                                       EVT VT) const {
9269   int Scale = AM.Scale;
9270   if (Scale < 0)
9271     return false;
9272
9273   switch (VT.getSimpleVT().SimpleTy) {
9274   default: return false;
9275   case MVT::i1:
9276   case MVT::i8:
9277   case MVT::i16:
9278   case MVT::i32:
9279     if (Scale == 1)
9280       return true;
9281     // r + r << imm
9282     Scale = Scale & ~1;
9283     return Scale == 2 || Scale == 4 || Scale == 8;
9284   case MVT::i64:
9285     // r + r
9286     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9287       return true;
9288     return false;
9289   case MVT::isVoid:
9290     // Note, we allow "void" uses (basically, uses that aren't loads or
9291     // stores), because arm allows folding a scale into many arithmetic
9292     // operations.  This should be made more precise and revisited later.
9293
9294     // Allow r << imm, but the imm has to be a multiple of two.
9295     if (Scale & 1) return false;
9296     return isPowerOf2_32(Scale);
9297   }
9298 }
9299
9300 /// isLegalAddressingMode - Return true if the addressing mode represented
9301 /// by AM is legal for this target, for a load/store of the specified type.
9302 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9303                                               Type *Ty) const {
9304   EVT VT = getValueType(Ty, true);
9305   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9306     return false;
9307
9308   // Can never fold addr of global into load/store.
9309   if (AM.BaseGV)
9310     return false;
9311
9312   switch (AM.Scale) {
9313   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9314     break;
9315   case 1:
9316     if (Subtarget->isThumb1Only())
9317       return false;
9318     // FALL THROUGH.
9319   default:
9320     // ARM doesn't support any R+R*scale+imm addr modes.
9321     if (AM.BaseOffs)
9322       return false;
9323
9324     if (!VT.isSimple())
9325       return false;
9326
9327     if (Subtarget->isThumb2())
9328       return isLegalT2ScaledAddressingMode(AM, VT);
9329
9330     int Scale = AM.Scale;
9331     switch (VT.getSimpleVT().SimpleTy) {
9332     default: return false;
9333     case MVT::i1:
9334     case MVT::i8:
9335     case MVT::i32:
9336       if (Scale < 0) Scale = -Scale;
9337       if (Scale == 1)
9338         return true;
9339       // r + r << imm
9340       return isPowerOf2_32(Scale & ~1);
9341     case MVT::i16:
9342     case MVT::i64:
9343       // r + r
9344       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9345         return true;
9346       return false;
9347
9348     case MVT::isVoid:
9349       // Note, we allow "void" uses (basically, uses that aren't loads or
9350       // stores), because arm allows folding a scale into many arithmetic
9351       // operations.  This should be made more precise and revisited later.
9352
9353       // Allow r << imm, but the imm has to be a multiple of two.
9354       if (Scale & 1) return false;
9355       return isPowerOf2_32(Scale);
9356     }
9357   }
9358   return true;
9359 }
9360
9361 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9362 /// icmp immediate, that is the target has icmp instructions which can compare
9363 /// a register against the immediate without having to materialize the
9364 /// immediate into a register.
9365 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9366   // Thumb2 and ARM modes can use cmn for negative immediates.
9367   if (!Subtarget->isThumb())
9368     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9369   if (Subtarget->isThumb2())
9370     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9371   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9372   return Imm >= 0 && Imm <= 255;
9373 }
9374
9375 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9376 /// *or sub* immediate, that is the target has add or sub instructions which can
9377 /// add a register with the immediate without having to materialize the
9378 /// immediate into a register.
9379 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9380   // Same encoding for add/sub, just flip the sign.
9381   int64_t AbsImm = llvm::abs64(Imm);
9382   if (!Subtarget->isThumb())
9383     return ARM_AM::getSOImmVal(AbsImm) != -1;
9384   if (Subtarget->isThumb2())
9385     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9386   // Thumb1 only has 8-bit unsigned immediate.
9387   return AbsImm >= 0 && AbsImm <= 255;
9388 }
9389
9390 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9391                                       bool isSEXTLoad, SDValue &Base,
9392                                       SDValue &Offset, bool &isInc,
9393                                       SelectionDAG &DAG) {
9394   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9395     return false;
9396
9397   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9398     // AddressingMode 3
9399     Base = Ptr->getOperand(0);
9400     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9401       int RHSC = (int)RHS->getZExtValue();
9402       if (RHSC < 0 && RHSC > -256) {
9403         assert(Ptr->getOpcode() == ISD::ADD);
9404         isInc = false;
9405         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9406         return true;
9407       }
9408     }
9409     isInc = (Ptr->getOpcode() == ISD::ADD);
9410     Offset = Ptr->getOperand(1);
9411     return true;
9412   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9413     // AddressingMode 2
9414     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9415       int RHSC = (int)RHS->getZExtValue();
9416       if (RHSC < 0 && RHSC > -0x1000) {
9417         assert(Ptr->getOpcode() == ISD::ADD);
9418         isInc = false;
9419         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9420         Base = Ptr->getOperand(0);
9421         return true;
9422       }
9423     }
9424
9425     if (Ptr->getOpcode() == ISD::ADD) {
9426       isInc = true;
9427       ARM_AM::ShiftOpc ShOpcVal=
9428         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9429       if (ShOpcVal != ARM_AM::no_shift) {
9430         Base = Ptr->getOperand(1);
9431         Offset = Ptr->getOperand(0);
9432       } else {
9433         Base = Ptr->getOperand(0);
9434         Offset = Ptr->getOperand(1);
9435       }
9436       return true;
9437     }
9438
9439     isInc = (Ptr->getOpcode() == ISD::ADD);
9440     Base = Ptr->getOperand(0);
9441     Offset = Ptr->getOperand(1);
9442     return true;
9443   }
9444
9445   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9446   return false;
9447 }
9448
9449 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9450                                      bool isSEXTLoad, SDValue &Base,
9451                                      SDValue &Offset, bool &isInc,
9452                                      SelectionDAG &DAG) {
9453   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9454     return false;
9455
9456   Base = Ptr->getOperand(0);
9457   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9458     int RHSC = (int)RHS->getZExtValue();
9459     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9460       assert(Ptr->getOpcode() == ISD::ADD);
9461       isInc = false;
9462       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9463       return true;
9464     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9465       isInc = Ptr->getOpcode() == ISD::ADD;
9466       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9467       return true;
9468     }
9469   }
9470
9471   return false;
9472 }
9473
9474 /// getPreIndexedAddressParts - returns true by value, base pointer and
9475 /// offset pointer and addressing mode by reference if the node's address
9476 /// can be legally represented as pre-indexed load / store address.
9477 bool
9478 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9479                                              SDValue &Offset,
9480                                              ISD::MemIndexedMode &AM,
9481                                              SelectionDAG &DAG) const {
9482   if (Subtarget->isThumb1Only())
9483     return false;
9484
9485   EVT VT;
9486   SDValue Ptr;
9487   bool isSEXTLoad = false;
9488   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9489     Ptr = LD->getBasePtr();
9490     VT  = LD->getMemoryVT();
9491     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9492   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9493     Ptr = ST->getBasePtr();
9494     VT  = ST->getMemoryVT();
9495   } else
9496     return false;
9497
9498   bool isInc;
9499   bool isLegal = false;
9500   if (Subtarget->isThumb2())
9501     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9502                                        Offset, isInc, DAG);
9503   else
9504     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9505                                         Offset, isInc, DAG);
9506   if (!isLegal)
9507     return false;
9508
9509   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9510   return true;
9511 }
9512
9513 /// getPostIndexedAddressParts - returns true by value, base pointer and
9514 /// offset pointer and addressing mode by reference if this node can be
9515 /// combined with a load / store to form a post-indexed load / store.
9516 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9517                                                    SDValue &Base,
9518                                                    SDValue &Offset,
9519                                                    ISD::MemIndexedMode &AM,
9520                                                    SelectionDAG &DAG) const {
9521   if (Subtarget->isThumb1Only())
9522     return false;
9523
9524   EVT VT;
9525   SDValue Ptr;
9526   bool isSEXTLoad = false;
9527   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9528     VT  = LD->getMemoryVT();
9529     Ptr = LD->getBasePtr();
9530     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9531   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9532     VT  = ST->getMemoryVT();
9533     Ptr = ST->getBasePtr();
9534   } else
9535     return false;
9536
9537   bool isInc;
9538   bool isLegal = false;
9539   if (Subtarget->isThumb2())
9540     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9541                                        isInc, DAG);
9542   else
9543     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9544                                         isInc, DAG);
9545   if (!isLegal)
9546     return false;
9547
9548   if (Ptr != Base) {
9549     // Swap base ptr and offset to catch more post-index load / store when
9550     // it's legal. In Thumb2 mode, offset must be an immediate.
9551     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9552         !Subtarget->isThumb2())
9553       std::swap(Base, Offset);
9554
9555     // Post-indexed load / store update the base pointer.
9556     if (Ptr != Base)
9557       return false;
9558   }
9559
9560   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9561   return true;
9562 }
9563
9564 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9565                                                        APInt &KnownZero,
9566                                                        APInt &KnownOne,
9567                                                        const SelectionDAG &DAG,
9568                                                        unsigned Depth) const {
9569   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9570   switch (Op.getOpcode()) {
9571   default: break;
9572   case ARMISD::CMOV: {
9573     // Bits are known zero/one if known on the LHS and RHS.
9574     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9575     if (KnownZero == 0 && KnownOne == 0) return;
9576
9577     APInt KnownZeroRHS, KnownOneRHS;
9578     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9579     KnownZero &= KnownZeroRHS;
9580     KnownOne  &= KnownOneRHS;
9581     return;
9582   }
9583   }
9584 }
9585
9586 //===----------------------------------------------------------------------===//
9587 //                           ARM Inline Assembly Support
9588 //===----------------------------------------------------------------------===//
9589
9590 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9591   // Looking for "rev" which is V6+.
9592   if (!Subtarget->hasV6Ops())
9593     return false;
9594
9595   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9596   std::string AsmStr = IA->getAsmString();
9597   SmallVector<StringRef, 4> AsmPieces;
9598   SplitString(AsmStr, AsmPieces, ";\n");
9599
9600   switch (AsmPieces.size()) {
9601   default: return false;
9602   case 1:
9603     AsmStr = AsmPieces[0];
9604     AsmPieces.clear();
9605     SplitString(AsmStr, AsmPieces, " \t,");
9606
9607     // rev $0, $1
9608     if (AsmPieces.size() == 3 &&
9609         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9610         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9611       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9612       if (Ty && Ty->getBitWidth() == 32)
9613         return IntrinsicLowering::LowerToByteSwap(CI);
9614     }
9615     break;
9616   }
9617
9618   return false;
9619 }
9620
9621 /// getConstraintType - Given a constraint letter, return the type of
9622 /// constraint it is for this target.
9623 ARMTargetLowering::ConstraintType
9624 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9625   if (Constraint.size() == 1) {
9626     switch (Constraint[0]) {
9627     default:  break;
9628     case 'l': return C_RegisterClass;
9629     case 'w': return C_RegisterClass;
9630     case 'h': return C_RegisterClass;
9631     case 'x': return C_RegisterClass;
9632     case 't': return C_RegisterClass;
9633     case 'j': return C_Other; // Constant for movw.
9634       // An address with a single base register. Due to the way we
9635       // currently handle addresses it is the same as an 'r' memory constraint.
9636     case 'Q': return C_Memory;
9637     }
9638   } else if (Constraint.size() == 2) {
9639     switch (Constraint[0]) {
9640     default: break;
9641     // All 'U+' constraints are addresses.
9642     case 'U': return C_Memory;
9643     }
9644   }
9645   return TargetLowering::getConstraintType(Constraint);
9646 }
9647
9648 /// Examine constraint type and operand type and determine a weight value.
9649 /// This object must already have been set up with the operand type
9650 /// and the current alternative constraint selected.
9651 TargetLowering::ConstraintWeight
9652 ARMTargetLowering::getSingleConstraintMatchWeight(
9653     AsmOperandInfo &info, const char *constraint) const {
9654   ConstraintWeight weight = CW_Invalid;
9655   Value *CallOperandVal = info.CallOperandVal;
9656     // If we don't have a value, we can't do a match,
9657     // but allow it at the lowest weight.
9658   if (CallOperandVal == NULL)
9659     return CW_Default;
9660   Type *type = CallOperandVal->getType();
9661   // Look at the constraint type.
9662   switch (*constraint) {
9663   default:
9664     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9665     break;
9666   case 'l':
9667     if (type->isIntegerTy()) {
9668       if (Subtarget->isThumb())
9669         weight = CW_SpecificReg;
9670       else
9671         weight = CW_Register;
9672     }
9673     break;
9674   case 'w':
9675     if (type->isFloatingPointTy())
9676       weight = CW_Register;
9677     break;
9678   }
9679   return weight;
9680 }
9681
9682 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9683 RCPair
9684 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9685                                                 EVT VT) const {
9686   if (Constraint.size() == 1) {
9687     // GCC ARM Constraint Letters
9688     switch (Constraint[0]) {
9689     case 'l': // Low regs or general regs.
9690       if (Subtarget->isThumb())
9691         return RCPair(0U, &ARM::tGPRRegClass);
9692       return RCPair(0U, &ARM::GPRRegClass);
9693     case 'h': // High regs or no regs.
9694       if (Subtarget->isThumb())
9695         return RCPair(0U, &ARM::hGPRRegClass);
9696       break;
9697     case 'r':
9698       return RCPair(0U, &ARM::GPRRegClass);
9699     case 'w':
9700       if (VT == MVT::f32)
9701         return RCPair(0U, &ARM::SPRRegClass);
9702       if (VT.getSizeInBits() == 64)
9703         return RCPair(0U, &ARM::DPRRegClass);
9704       if (VT.getSizeInBits() == 128)
9705         return RCPair(0U, &ARM::QPRRegClass);
9706       break;
9707     case 'x':
9708       if (VT == MVT::f32)
9709         return RCPair(0U, &ARM::SPR_8RegClass);
9710       if (VT.getSizeInBits() == 64)
9711         return RCPair(0U, &ARM::DPR_8RegClass);
9712       if (VT.getSizeInBits() == 128)
9713         return RCPair(0U, &ARM::QPR_8RegClass);
9714       break;
9715     case 't':
9716       if (VT == MVT::f32)
9717         return RCPair(0U, &ARM::SPRRegClass);
9718       break;
9719     }
9720   }
9721   if (StringRef("{cc}").equals_lower(Constraint))
9722     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9723
9724   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9725 }
9726
9727 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9728 /// vector.  If it is invalid, don't add anything to Ops.
9729 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9730                                                      std::string &Constraint,
9731                                                      std::vector<SDValue>&Ops,
9732                                                      SelectionDAG &DAG) const {
9733   SDValue Result(0, 0);
9734
9735   // Currently only support length 1 constraints.
9736   if (Constraint.length() != 1) return;
9737
9738   char ConstraintLetter = Constraint[0];
9739   switch (ConstraintLetter) {
9740   default: break;
9741   case 'j':
9742   case 'I': case 'J': case 'K': case 'L':
9743   case 'M': case 'N': case 'O':
9744     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9745     if (!C)
9746       return;
9747
9748     int64_t CVal64 = C->getSExtValue();
9749     int CVal = (int) CVal64;
9750     // None of these constraints allow values larger than 32 bits.  Check
9751     // that the value fits in an int.
9752     if (CVal != CVal64)
9753       return;
9754
9755     switch (ConstraintLetter) {
9756       case 'j':
9757         // Constant suitable for movw, must be between 0 and
9758         // 65535.
9759         if (Subtarget->hasV6T2Ops())
9760           if (CVal >= 0 && CVal <= 65535)
9761             break;
9762         return;
9763       case 'I':
9764         if (Subtarget->isThumb1Only()) {
9765           // This must be a constant between 0 and 255, for ADD
9766           // immediates.
9767           if (CVal >= 0 && CVal <= 255)
9768             break;
9769         } else if (Subtarget->isThumb2()) {
9770           // A constant that can be used as an immediate value in a
9771           // data-processing instruction.
9772           if (ARM_AM::getT2SOImmVal(CVal) != -1)
9773             break;
9774         } else {
9775           // A constant that can be used as an immediate value in a
9776           // data-processing instruction.
9777           if (ARM_AM::getSOImmVal(CVal) != -1)
9778             break;
9779         }
9780         return;
9781
9782       case 'J':
9783         if (Subtarget->isThumb()) {  // FIXME thumb2
9784           // This must be a constant between -255 and -1, for negated ADD
9785           // immediates. This can be used in GCC with an "n" modifier that
9786           // prints the negated value, for use with SUB instructions. It is
9787           // not useful otherwise but is implemented for compatibility.
9788           if (CVal >= -255 && CVal <= -1)
9789             break;
9790         } else {
9791           // This must be a constant between -4095 and 4095. It is not clear
9792           // what this constraint is intended for. Implemented for
9793           // compatibility with GCC.
9794           if (CVal >= -4095 && CVal <= 4095)
9795             break;
9796         }
9797         return;
9798
9799       case 'K':
9800         if (Subtarget->isThumb1Only()) {
9801           // A 32-bit value where only one byte has a nonzero value. Exclude
9802           // zero to match GCC. This constraint is used by GCC internally for
9803           // constants that can be loaded with a move/shift combination.
9804           // It is not useful otherwise but is implemented for compatibility.
9805           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9806             break;
9807         } else if (Subtarget->isThumb2()) {
9808           // A constant whose bitwise inverse can be used as an immediate
9809           // value in a data-processing instruction. This can be used in GCC
9810           // with a "B" modifier that prints the inverted value, for use with
9811           // BIC and MVN instructions. It is not useful otherwise but is
9812           // implemented for compatibility.
9813           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9814             break;
9815         } else {
9816           // A constant whose bitwise inverse can be used as an immediate
9817           // value in a data-processing instruction. This can be used in GCC
9818           // with a "B" modifier that prints the inverted value, for use with
9819           // BIC and MVN instructions. It is not useful otherwise but is
9820           // implemented for compatibility.
9821           if (ARM_AM::getSOImmVal(~CVal) != -1)
9822             break;
9823         }
9824         return;
9825
9826       case 'L':
9827         if (Subtarget->isThumb1Only()) {
9828           // This must be a constant between -7 and 7,
9829           // for 3-operand ADD/SUB immediate instructions.
9830           if (CVal >= -7 && CVal < 7)
9831             break;
9832         } else if (Subtarget->isThumb2()) {
9833           // A constant whose negation can be used as an immediate value in a
9834           // data-processing instruction. This can be used in GCC with an "n"
9835           // modifier that prints the negated value, for use with SUB
9836           // instructions. It is not useful otherwise but is implemented for
9837           // compatibility.
9838           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9839             break;
9840         } else {
9841           // A constant whose negation can be used as an immediate value in a
9842           // data-processing instruction. This can be used in GCC with an "n"
9843           // modifier that prints the negated value, for use with SUB
9844           // instructions. It is not useful otherwise but is implemented for
9845           // compatibility.
9846           if (ARM_AM::getSOImmVal(-CVal) != -1)
9847             break;
9848         }
9849         return;
9850
9851       case 'M':
9852         if (Subtarget->isThumb()) { // FIXME thumb2
9853           // This must be a multiple of 4 between 0 and 1020, for
9854           // ADD sp + immediate.
9855           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9856             break;
9857         } else {
9858           // A power of two or a constant between 0 and 32.  This is used in
9859           // GCC for the shift amount on shifted register operands, but it is
9860           // useful in general for any shift amounts.
9861           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9862             break;
9863         }
9864         return;
9865
9866       case 'N':
9867         if (Subtarget->isThumb()) {  // FIXME thumb2
9868           // This must be a constant between 0 and 31, for shift amounts.
9869           if (CVal >= 0 && CVal <= 31)
9870             break;
9871         }
9872         return;
9873
9874       case 'O':
9875         if (Subtarget->isThumb()) {  // FIXME thumb2
9876           // This must be a multiple of 4 between -508 and 508, for
9877           // ADD/SUB sp = sp + immediate.
9878           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9879             break;
9880         }
9881         return;
9882     }
9883     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9884     break;
9885   }
9886
9887   if (Result.getNode()) {
9888     Ops.push_back(Result);
9889     return;
9890   }
9891   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9892 }
9893
9894 bool
9895 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9896   // The ARM target isn't yet aware of offsets.
9897   return false;
9898 }
9899
9900 bool ARM::isBitFieldInvertedMask(unsigned v) {
9901   if (v == 0xffffffff)
9902     return 0;
9903   // there can be 1's on either or both "outsides", all the "inside"
9904   // bits must be 0's
9905   unsigned int lsb = 0, msb = 31;
9906   while (v & (1 << msb)) --msb;
9907   while (v & (1 << lsb)) ++lsb;
9908   for (unsigned int i = lsb; i <= msb; ++i) {
9909     if (v & (1 << i))
9910       return 0;
9911   }
9912   return 1;
9913 }
9914
9915 /// isFPImmLegal - Returns true if the target can instruction select the
9916 /// specified FP immediate natively. If false, the legalizer will
9917 /// materialize the FP immediate as a load from a constant pool.
9918 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9919   if (!Subtarget->hasVFP3())
9920     return false;
9921   if (VT == MVT::f32)
9922     return ARM_AM::getFP32Imm(Imm) != -1;
9923   if (VT == MVT::f64)
9924     return ARM_AM::getFP64Imm(Imm) != -1;
9925   return false;
9926 }
9927
9928 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9929 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9930 /// specified in the intrinsic calls.
9931 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9932                                            const CallInst &I,
9933                                            unsigned Intrinsic) const {
9934   switch (Intrinsic) {
9935   case Intrinsic::arm_neon_vld1:
9936   case Intrinsic::arm_neon_vld2:
9937   case Intrinsic::arm_neon_vld3:
9938   case Intrinsic::arm_neon_vld4:
9939   case Intrinsic::arm_neon_vld2lane:
9940   case Intrinsic::arm_neon_vld3lane:
9941   case Intrinsic::arm_neon_vld4lane: {
9942     Info.opc = ISD::INTRINSIC_W_CHAIN;
9943     // Conservatively set memVT to the entire set of vectors loaded.
9944     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
9945     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9946     Info.ptrVal = I.getArgOperand(0);
9947     Info.offset = 0;
9948     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9949     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9950     Info.vol = false; // volatile loads with NEON intrinsics not supported
9951     Info.readMem = true;
9952     Info.writeMem = false;
9953     return true;
9954   }
9955   case Intrinsic::arm_neon_vst1:
9956   case Intrinsic::arm_neon_vst2:
9957   case Intrinsic::arm_neon_vst3:
9958   case Intrinsic::arm_neon_vst4:
9959   case Intrinsic::arm_neon_vst2lane:
9960   case Intrinsic::arm_neon_vst3lane:
9961   case Intrinsic::arm_neon_vst4lane: {
9962     Info.opc = ISD::INTRINSIC_VOID;
9963     // Conservatively set memVT to the entire set of vectors stored.
9964     unsigned NumElts = 0;
9965     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9966       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9967       if (!ArgTy->isVectorTy())
9968         break;
9969       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
9970     }
9971     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9972     Info.ptrVal = I.getArgOperand(0);
9973     Info.offset = 0;
9974     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9975     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9976     Info.vol = false; // volatile stores with NEON intrinsics not supported
9977     Info.readMem = false;
9978     Info.writeMem = true;
9979     return true;
9980   }
9981   case Intrinsic::arm_strexd: {
9982     Info.opc = ISD::INTRINSIC_W_CHAIN;
9983     Info.memVT = MVT::i64;
9984     Info.ptrVal = I.getArgOperand(2);
9985     Info.offset = 0;
9986     Info.align = 8;
9987     Info.vol = true;
9988     Info.readMem = false;
9989     Info.writeMem = true;
9990     return true;
9991   }
9992   case Intrinsic::arm_ldrexd: {
9993     Info.opc = ISD::INTRINSIC_W_CHAIN;
9994     Info.memVT = MVT::i64;
9995     Info.ptrVal = I.getArgOperand(0);
9996     Info.offset = 0;
9997     Info.align = 8;
9998     Info.vol = true;
9999     Info.readMem = true;
10000     Info.writeMem = false;
10001     return true;
10002   }
10003   default:
10004     break;
10005   }
10006
10007   return false;
10008 }