9b68590f856d07ac6b8c2c24afb57b4fce933466
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
508
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Mark v2f32 intrinsics.
526     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
541
542     // Neon does not support some operations on v1i64 and v2i64 types.
543     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544     // Custom handling for some quad-vector types to detect VMULL.
545     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548     // Custom handling for some vector types to avoid expensive expansions
549     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556     // a destination type that is wider than the source, and nor does
557     // it have a FP_TO_[SU]INT instruction with a narrower destination than
558     // source.
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
563
564     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
565     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
566
567     // Custom expand long extensions to vectors.
568     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
569     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
571     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
575     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
576
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585     // NEON only has FMA instructions as of VFP4.
586     if (!Subtarget->hasVFP4()) {
587       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
589     }
590
591     setTargetDAGCombine(ISD::INTRINSIC_VOID);
592     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594     setTargetDAGCombine(ISD::SHL);
595     setTargetDAGCombine(ISD::SRL);
596     setTargetDAGCombine(ISD::SRA);
597     setTargetDAGCombine(ISD::SIGN_EXTEND);
598     setTargetDAGCombine(ISD::ZERO_EXTEND);
599     setTargetDAGCombine(ISD::ANY_EXTEND);
600     setTargetDAGCombine(ISD::SELECT_CC);
601     setTargetDAGCombine(ISD::BUILD_VECTOR);
602     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604     setTargetDAGCombine(ISD::STORE);
605     setTargetDAGCombine(ISD::FP_TO_SINT);
606     setTargetDAGCombine(ISD::FP_TO_UINT);
607     setTargetDAGCombine(ISD::FDIV);
608
609     // It is legal to extload from v4i8 to v4i16 or v4i32.
610     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611                   MVT::v4i16, MVT::v2i16,
612                   MVT::v2i32};
613     for (unsigned i = 0; i < 6; ++i) {
614       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
617     }
618   }
619
620   // ARM and Thumb2 support UMLAL/SMLAL.
621   if (!Subtarget->isThumb1Only())
622     setTargetDAGCombine(ISD::ADDC);
623
624
625   computeRegisterProperties();
626
627   // ARM does not have f32 extending load.
628   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
629
630   // ARM does not have i1 sign extending load.
631   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
632
633   // ARM supports all 4 flavors of integer indexed load / store.
634   if (!Subtarget->isThumb1Only()) {
635     for (unsigned im = (unsigned)ISD::PRE_INC;
636          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637       setIndexedLoadAction(im,  MVT::i1,  Legal);
638       setIndexedLoadAction(im,  MVT::i8,  Legal);
639       setIndexedLoadAction(im,  MVT::i16, Legal);
640       setIndexedLoadAction(im,  MVT::i32, Legal);
641       setIndexedStoreAction(im, MVT::i1,  Legal);
642       setIndexedStoreAction(im, MVT::i8,  Legal);
643       setIndexedStoreAction(im, MVT::i16, Legal);
644       setIndexedStoreAction(im, MVT::i32, Legal);
645     }
646   }
647
648   // i64 operation support.
649   setOperationAction(ISD::MUL,     MVT::i64, Expand);
650   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
651   if (Subtarget->isThumb1Only()) {
652     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
654   }
655   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657     setOperationAction(ISD::MULHS, MVT::i32, Expand);
658
659   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL,       MVT::i64, Custom);
663   setOperationAction(ISD::SRA,       MVT::i64, Custom);
664
665   if (!Subtarget->isThumb1Only()) {
666     // FIXME: We should do this for Thumb1 as well.
667     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
668     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
669     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
671   }
672
673   // ARM does not have ROTL.
674   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
675   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
676   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
679
680   // These just redirect to CTTZ and CTLZ on ARM.
681   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
682   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
683
684   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
685
686   // Only ARMv6 has BSWAP.
687   if (!Subtarget->hasV6Ops())
688     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
689
690   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
691       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
692     // These are expanded into libcalls if the cpu doesn't have HW divider.
693     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
694     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
695   }
696   setOperationAction(ISD::SREM,  MVT::i32, Expand);
697   setOperationAction(ISD::UREM,  MVT::i32, Expand);
698   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
699   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
700
701   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
702   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
703   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
704   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
705   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
706
707   setOperationAction(ISD::TRAP, MVT::Other, Legal);
708
709   // Use the default implementation.
710   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
711   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
712   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
713   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
714   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
715   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
716
717   if (!Subtarget->isTargetDarwin()) {
718     // Non-Darwin platforms may return values in these registers via the
719     // personality function.
720     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
721     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
722     setExceptionPointerRegister(ARM::R0);
723     setExceptionSelectorRegister(ARM::R1);
724   }
725
726   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
727   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
728   // the default expansion.
729   // FIXME: This should be checking for v6k, not just v6.
730   if (Subtarget->hasDataBarrier() ||
731       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
732     // membarrier needs custom lowering; the rest are legal and handled
733     // normally.
734     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
735     // Custom lowering for 64-bit ops
736     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
737     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
738     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
739     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
740     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
741     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
742     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
743     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
744     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
745     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
746     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
747     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
748     setInsertFencesForAtomic(true);
749   } else {
750     // Set them all for expansion, which will force libcalls.
751     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
752     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
755     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
756     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
757     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
758     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
759     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
762     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
763     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
764     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
765     // Unordered/Monotonic case.
766     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
767     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
768   }
769
770   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
771
772   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
773   if (!Subtarget->hasV6Ops()) {
774     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
775     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
776   }
777   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
778
779   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
780       !Subtarget->isThumb1Only()) {
781     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
782     // iff target supports vfp2.
783     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
784     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
785   }
786
787   // We want to custom lower some of our intrinsics.
788   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
789   if (Subtarget->isTargetDarwin()) {
790     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
791     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
792     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
793   }
794
795   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
796   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
797   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
798   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
799   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
800   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
801   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
802   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
803   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
804
805   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
806   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
807   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
808   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
809   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
810
811   // We don't support sin/cos/fmod/copysign/pow
812   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
813   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
814   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
815   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
816   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
817   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
818   setOperationAction(ISD::FREM,      MVT::f64, Expand);
819   setOperationAction(ISD::FREM,      MVT::f32, Expand);
820   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821       !Subtarget->isThumb1Only()) {
822     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
823     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
824   }
825   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
826   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
827
828   if (!Subtarget->hasVFP4()) {
829     setOperationAction(ISD::FMA, MVT::f64, Expand);
830     setOperationAction(ISD::FMA, MVT::f32, Expand);
831   }
832
833   // Various VFP goodness
834   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
835     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
836     if (Subtarget->hasVFP2()) {
837       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
838       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
839       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
840       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
841     }
842     // Special handling for half-precision FP.
843     if (!Subtarget->hasFP16()) {
844       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
845       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
846     }
847   }
848
849   // We have target-specific dag combine patterns for the following nodes:
850   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
851   setTargetDAGCombine(ISD::ADD);
852   setTargetDAGCombine(ISD::SUB);
853   setTargetDAGCombine(ISD::MUL);
854   setTargetDAGCombine(ISD::AND);
855   setTargetDAGCombine(ISD::OR);
856   setTargetDAGCombine(ISD::XOR);
857
858   if (Subtarget->hasV6Ops())
859     setTargetDAGCombine(ISD::SRL);
860
861   setStackPointerRegisterToSaveRestore(ARM::SP);
862
863   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
864       !Subtarget->hasVFP2())
865     setSchedulingPreference(Sched::RegPressure);
866   else
867     setSchedulingPreference(Sched::Hybrid);
868
869   //// temporary - rewrite interface to use type
870   MaxStoresPerMemset = 8;
871   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
872   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
873   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
875   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
876
877   // On ARM arguments smaller than 4 bytes are extended, so all arguments
878   // are at least 4 bytes aligned.
879   setMinStackArgumentAlignment(4);
880
881   // Prefer likely predicted branches to selects on out-of-order cores.
882   PredictableSelectIsExpensive = Subtarget->isLikeA9();
883
884   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
885 }
886
887 // FIXME: It might make sense to define the representative register class as the
888 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
889 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
890 // SPR's representative would be DPR_VFP2. This should work well if register
891 // pressure tracking were modified such that a register use would increment the
892 // pressure of the register class's representative and all of it's super
893 // classes' representatives transitively. We have not implemented this because
894 // of the difficulty prior to coalescing of modeling operand register classes
895 // due to the common occurrence of cross class copies and subregister insertions
896 // and extractions.
897 std::pair<const TargetRegisterClass*, uint8_t>
898 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
899   const TargetRegisterClass *RRC = 0;
900   uint8_t Cost = 1;
901   switch (VT.SimpleTy) {
902   default:
903     return TargetLowering::findRepresentativeClass(VT);
904   // Use DPR as representative register class for all floating point
905   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
906   // the cost is 1 for both f32 and f64.
907   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
908   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
909     RRC = &ARM::DPRRegClass;
910     // When NEON is used for SP, only half of the register file is available
911     // because operations that define both SP and DP results will be constrained
912     // to the VFP2 class (D0-D15). We currently model this constraint prior to
913     // coalescing by double-counting the SP regs. See the FIXME above.
914     if (Subtarget->useNEONForSinglePrecisionFP())
915       Cost = 2;
916     break;
917   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
918   case MVT::v4f32: case MVT::v2f64:
919     RRC = &ARM::DPRRegClass;
920     Cost = 2;
921     break;
922   case MVT::v4i64:
923     RRC = &ARM::DPRRegClass;
924     Cost = 4;
925     break;
926   case MVT::v8i64:
927     RRC = &ARM::DPRRegClass;
928     Cost = 8;
929     break;
930   }
931   return std::make_pair(RRC, Cost);
932 }
933
934 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
935   switch (Opcode) {
936   default: return 0;
937   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
938   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
939   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
940   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
941   case ARMISD::CALL:          return "ARMISD::CALL";
942   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
943   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
944   case ARMISD::tCALL:         return "ARMISD::tCALL";
945   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
946   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
947   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
948   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
949   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
950   case ARMISD::CMP:           return "ARMISD::CMP";
951   case ARMISD::CMN:           return "ARMISD::CMN";
952   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
953   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
954   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
955   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
956   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
957
958   case ARMISD::CMOV:          return "ARMISD::CMOV";
959
960   case ARMISD::RBIT:          return "ARMISD::RBIT";
961
962   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
963   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
964   case ARMISD::SITOF:         return "ARMISD::SITOF";
965   case ARMISD::UITOF:         return "ARMISD::UITOF";
966
967   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
968   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
969   case ARMISD::RRX:           return "ARMISD::RRX";
970
971   case ARMISD::ADDC:          return "ARMISD::ADDC";
972   case ARMISD::ADDE:          return "ARMISD::ADDE";
973   case ARMISD::SUBC:          return "ARMISD::SUBC";
974   case ARMISD::SUBE:          return "ARMISD::SUBE";
975
976   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
977   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
978
979   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
980   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
981
982   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
983
984   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
985
986   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
987
988   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
989   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
990
991   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
992
993   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
994   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
995   case ARMISD::VCGE:          return "ARMISD::VCGE";
996   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
997   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
998   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
999   case ARMISD::VCGT:          return "ARMISD::VCGT";
1000   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1001   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1002   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1003   case ARMISD::VTST:          return "ARMISD::VTST";
1004
1005   case ARMISD::VSHL:          return "ARMISD::VSHL";
1006   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1007   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1008   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1009   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1010   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1011   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1012   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1013   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1014   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1015   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1016   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1017   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1018   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1019   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1020   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1021   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1022   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1023   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1024   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1025   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1026   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1027   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1028   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1029   case ARMISD::VDUP:          return "ARMISD::VDUP";
1030   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1031   case ARMISD::VEXT:          return "ARMISD::VEXT";
1032   case ARMISD::VREV64:        return "ARMISD::VREV64";
1033   case ARMISD::VREV32:        return "ARMISD::VREV32";
1034   case ARMISD::VREV16:        return "ARMISD::VREV16";
1035   case ARMISD::VZIP:          return "ARMISD::VZIP";
1036   case ARMISD::VUZP:          return "ARMISD::VUZP";
1037   case ARMISD::VTRN:          return "ARMISD::VTRN";
1038   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1039   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1040   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1041   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1042   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1043   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1044   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1045   case ARMISD::FMAX:          return "ARMISD::FMAX";
1046   case ARMISD::FMIN:          return "ARMISD::FMIN";
1047   case ARMISD::BFI:           return "ARMISD::BFI";
1048   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1049   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1050   case ARMISD::VBSL:          return "ARMISD::VBSL";
1051   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1052   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1053   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1054   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1055   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1056   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1057   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1058   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1059   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1060   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1061   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1062   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1063   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1064   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1065   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1066   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1067   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1068   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1069   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1070   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1071   }
1072 }
1073
1074 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1075   if (!VT.isVector()) return getPointerTy();
1076   return VT.changeVectorElementTypeToInteger();
1077 }
1078
1079 /// getRegClassFor - Return the register class that should be used for the
1080 /// specified value type.
1081 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1082   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1083   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1084   // load / store 4 to 8 consecutive D registers.
1085   if (Subtarget->hasNEON()) {
1086     if (VT == MVT::v4i64)
1087       return &ARM::QQPRRegClass;
1088     if (VT == MVT::v8i64)
1089       return &ARM::QQQQPRRegClass;
1090   }
1091   return TargetLowering::getRegClassFor(VT);
1092 }
1093
1094 // Create a fast isel object.
1095 FastISel *
1096 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1097                                   const TargetLibraryInfo *libInfo) const {
1098   return ARM::createFastISel(funcInfo, libInfo);
1099 }
1100
1101 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1102 /// be used for loads / stores from the global.
1103 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1104   return (Subtarget->isThumb1Only() ? 127 : 4095);
1105 }
1106
1107 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1108   unsigned NumVals = N->getNumValues();
1109   if (!NumVals)
1110     return Sched::RegPressure;
1111
1112   for (unsigned i = 0; i != NumVals; ++i) {
1113     EVT VT = N->getValueType(i);
1114     if (VT == MVT::Glue || VT == MVT::Other)
1115       continue;
1116     if (VT.isFloatingPoint() || VT.isVector())
1117       return Sched::ILP;
1118   }
1119
1120   if (!N->isMachineOpcode())
1121     return Sched::RegPressure;
1122
1123   // Load are scheduled for latency even if there instruction itinerary
1124   // is not available.
1125   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1126   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1127
1128   if (MCID.getNumDefs() == 0)
1129     return Sched::RegPressure;
1130   if (!Itins->isEmpty() &&
1131       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1132     return Sched::ILP;
1133
1134   return Sched::RegPressure;
1135 }
1136
1137 //===----------------------------------------------------------------------===//
1138 // Lowering Code
1139 //===----------------------------------------------------------------------===//
1140
1141 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1142 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1143   switch (CC) {
1144   default: llvm_unreachable("Unknown condition code!");
1145   case ISD::SETNE:  return ARMCC::NE;
1146   case ISD::SETEQ:  return ARMCC::EQ;
1147   case ISD::SETGT:  return ARMCC::GT;
1148   case ISD::SETGE:  return ARMCC::GE;
1149   case ISD::SETLT:  return ARMCC::LT;
1150   case ISD::SETLE:  return ARMCC::LE;
1151   case ISD::SETUGT: return ARMCC::HI;
1152   case ISD::SETUGE: return ARMCC::HS;
1153   case ISD::SETULT: return ARMCC::LO;
1154   case ISD::SETULE: return ARMCC::LS;
1155   }
1156 }
1157
1158 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1159 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1160                         ARMCC::CondCodes &CondCode2) {
1161   CondCode2 = ARMCC::AL;
1162   switch (CC) {
1163   default: llvm_unreachable("Unknown FP condition!");
1164   case ISD::SETEQ:
1165   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1166   case ISD::SETGT:
1167   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1168   case ISD::SETGE:
1169   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1170   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1171   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1172   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1173   case ISD::SETO:   CondCode = ARMCC::VC; break;
1174   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1175   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1176   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1177   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1178   case ISD::SETLT:
1179   case ISD::SETULT: CondCode = ARMCC::LT; break;
1180   case ISD::SETLE:
1181   case ISD::SETULE: CondCode = ARMCC::LE; break;
1182   case ISD::SETNE:
1183   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1184   }
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 //                      Calling Convention Implementation
1189 //===----------------------------------------------------------------------===//
1190
1191 #include "ARMGenCallingConv.inc"
1192
1193 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1194 /// given CallingConvention value.
1195 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1196                                                  bool Return,
1197                                                  bool isVarArg) const {
1198   switch (CC) {
1199   default:
1200     llvm_unreachable("Unsupported calling convention");
1201   case CallingConv::Fast:
1202     if (Subtarget->hasVFP2() && !isVarArg) {
1203       if (!Subtarget->isAAPCS_ABI())
1204         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1205       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1206       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1207     }
1208     // Fallthrough
1209   case CallingConv::C: {
1210     // Use target triple & subtarget features to do actual dispatch.
1211     if (!Subtarget->isAAPCS_ABI())
1212       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1213     else if (Subtarget->hasVFP2() &&
1214              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1215              !isVarArg)
1216       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1217     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1218   }
1219   case CallingConv::ARM_AAPCS_VFP:
1220     if (!isVarArg)
1221       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1222     // Fallthrough
1223   case CallingConv::ARM_AAPCS:
1224     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1225   case CallingConv::ARM_APCS:
1226     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1227   case CallingConv::GHC:
1228     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1229   }
1230 }
1231
1232 /// LowerCallResult - Lower the result values of a call into the
1233 /// appropriate copies out of appropriate physical registers.
1234 SDValue
1235 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1236                                    CallingConv::ID CallConv, bool isVarArg,
1237                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1238                                    SDLoc dl, SelectionDAG &DAG,
1239                                    SmallVectorImpl<SDValue> &InVals,
1240                                    bool isThisReturn, SDValue ThisVal) const {
1241
1242   // Assign locations to each value returned by this call.
1243   SmallVector<CCValAssign, 16> RVLocs;
1244   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1245                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1246   CCInfo.AnalyzeCallResult(Ins,
1247                            CCAssignFnForNode(CallConv, /* Return*/ true,
1248                                              isVarArg));
1249
1250   // Copy all of the result registers out of their specified physreg.
1251   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1252     CCValAssign VA = RVLocs[i];
1253
1254     // Pass 'this' value directly from the argument to return value, to avoid
1255     // reg unit interference
1256     if (i == 0 && isThisReturn) {
1257       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1258              "unexpected return calling convention register assignment");
1259       InVals.push_back(ThisVal);
1260       continue;
1261     }
1262
1263     SDValue Val;
1264     if (VA.needsCustom()) {
1265       // Handle f64 or half of a v2f64.
1266       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1267                                       InFlag);
1268       Chain = Lo.getValue(1);
1269       InFlag = Lo.getValue(2);
1270       VA = RVLocs[++i]; // skip ahead to next loc
1271       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1272                                       InFlag);
1273       Chain = Hi.getValue(1);
1274       InFlag = Hi.getValue(2);
1275       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1276
1277       if (VA.getLocVT() == MVT::v2f64) {
1278         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1279         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1280                           DAG.getConstant(0, MVT::i32));
1281
1282         VA = RVLocs[++i]; // skip ahead to next loc
1283         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1284         Chain = Lo.getValue(1);
1285         InFlag = Lo.getValue(2);
1286         VA = RVLocs[++i]; // skip ahead to next loc
1287         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1288         Chain = Hi.getValue(1);
1289         InFlag = Hi.getValue(2);
1290         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1291         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1292                           DAG.getConstant(1, MVT::i32));
1293       }
1294     } else {
1295       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1296                                InFlag);
1297       Chain = Val.getValue(1);
1298       InFlag = Val.getValue(2);
1299     }
1300
1301     switch (VA.getLocInfo()) {
1302     default: llvm_unreachable("Unknown loc info!");
1303     case CCValAssign::Full: break;
1304     case CCValAssign::BCvt:
1305       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1306       break;
1307     }
1308
1309     InVals.push_back(Val);
1310   }
1311
1312   return Chain;
1313 }
1314
1315 /// LowerMemOpCallTo - Store the argument to the stack.
1316 SDValue
1317 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1318                                     SDValue StackPtr, SDValue Arg,
1319                                     SDLoc dl, SelectionDAG &DAG,
1320                                     const CCValAssign &VA,
1321                                     ISD::ArgFlagsTy Flags) const {
1322   unsigned LocMemOffset = VA.getLocMemOffset();
1323   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1324   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1325   return DAG.getStore(Chain, dl, Arg, PtrOff,
1326                       MachinePointerInfo::getStack(LocMemOffset),
1327                       false, false, 0);
1328 }
1329
1330 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1331                                          SDValue Chain, SDValue &Arg,
1332                                          RegsToPassVector &RegsToPass,
1333                                          CCValAssign &VA, CCValAssign &NextVA,
1334                                          SDValue &StackPtr,
1335                                          SmallVector<SDValue, 8> &MemOpChains,
1336                                          ISD::ArgFlagsTy Flags) const {
1337
1338   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1339                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1340   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1341
1342   if (NextVA.isRegLoc())
1343     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1344   else {
1345     assert(NextVA.isMemLoc());
1346     if (StackPtr.getNode() == 0)
1347       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1348
1349     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1350                                            dl, DAG, NextVA,
1351                                            Flags));
1352   }
1353 }
1354
1355 /// LowerCall - Lowering a call into a callseq_start <-
1356 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1357 /// nodes.
1358 SDValue
1359 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1360                              SmallVectorImpl<SDValue> &InVals) const {
1361   SelectionDAG &DAG                     = CLI.DAG;
1362   SDLoc &dl                          = CLI.DL;
1363   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1364   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1365   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1366   SDValue Chain                         = CLI.Chain;
1367   SDValue Callee                        = CLI.Callee;
1368   bool &isTailCall                      = CLI.IsTailCall;
1369   CallingConv::ID CallConv              = CLI.CallConv;
1370   bool doesNotRet                       = CLI.DoesNotReturn;
1371   bool isVarArg                         = CLI.IsVarArg;
1372
1373   MachineFunction &MF = DAG.getMachineFunction();
1374   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1375   bool isThisReturn   = false;
1376   bool isSibCall      = false;
1377   // Disable tail calls if they're not supported.
1378   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1379     isTailCall = false;
1380   if (isTailCall) {
1381     // Check if it's really possible to do a tail call.
1382     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1383                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1384                                                    Outs, OutVals, Ins, DAG);
1385     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1386     // detected sibcalls.
1387     if (isTailCall) {
1388       ++NumTailCalls;
1389       isSibCall = true;
1390     }
1391   }
1392
1393   // Analyze operands of the call, assigning locations to each operand.
1394   SmallVector<CCValAssign, 16> ArgLocs;
1395   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1396                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1397   CCInfo.AnalyzeCallOperands(Outs,
1398                              CCAssignFnForNode(CallConv, /* Return*/ false,
1399                                                isVarArg));
1400
1401   // Get a count of how many bytes are to be pushed on the stack.
1402   unsigned NumBytes = CCInfo.getNextStackOffset();
1403
1404   // For tail calls, memory operands are available in our caller's stack.
1405   if (isSibCall)
1406     NumBytes = 0;
1407
1408   // Adjust the stack pointer for the new arguments...
1409   // These operations are automatically eliminated by the prolog/epilog pass
1410   if (!isSibCall)
1411     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1412                                  dl);
1413
1414   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1415
1416   RegsToPassVector RegsToPass;
1417   SmallVector<SDValue, 8> MemOpChains;
1418
1419   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1420   // of tail call optimization, arguments are handled later.
1421   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1422        i != e;
1423        ++i, ++realArgIdx) {
1424     CCValAssign &VA = ArgLocs[i];
1425     SDValue Arg = OutVals[realArgIdx];
1426     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1427     bool isByVal = Flags.isByVal();
1428
1429     // Promote the value if needed.
1430     switch (VA.getLocInfo()) {
1431     default: llvm_unreachable("Unknown loc info!");
1432     case CCValAssign::Full: break;
1433     case CCValAssign::SExt:
1434       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1435       break;
1436     case CCValAssign::ZExt:
1437       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1438       break;
1439     case CCValAssign::AExt:
1440       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1441       break;
1442     case CCValAssign::BCvt:
1443       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1444       break;
1445     }
1446
1447     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1448     if (VA.needsCustom()) {
1449       if (VA.getLocVT() == MVT::v2f64) {
1450         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1451                                   DAG.getConstant(0, MVT::i32));
1452         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1453                                   DAG.getConstant(1, MVT::i32));
1454
1455         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1456                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1457
1458         VA = ArgLocs[++i]; // skip ahead to next loc
1459         if (VA.isRegLoc()) {
1460           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1461                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1462         } else {
1463           assert(VA.isMemLoc());
1464
1465           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1466                                                  dl, DAG, VA, Flags));
1467         }
1468       } else {
1469         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1470                          StackPtr, MemOpChains, Flags);
1471       }
1472     } else if (VA.isRegLoc()) {
1473       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1474         assert(VA.getLocVT() == MVT::i32 &&
1475                "unexpected calling convention register assignment");
1476         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1477                "unexpected use of 'returned'");
1478         isThisReturn = true;
1479       }
1480       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1481     } else if (isByVal) {
1482       assert(VA.isMemLoc());
1483       unsigned offset = 0;
1484
1485       // True if this byval aggregate will be split between registers
1486       // and memory.
1487       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1488       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1489
1490       if (CurByValIdx < ByValArgsCount) {
1491
1492         unsigned RegBegin, RegEnd;
1493         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1494
1495         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1496         unsigned int i, j;
1497         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1498           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1499           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1500           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1501                                      MachinePointerInfo(),
1502                                      false, false, false, 0);
1503           MemOpChains.push_back(Load.getValue(1));
1504           RegsToPass.push_back(std::make_pair(j, Load));
1505         }
1506
1507         // If parameter size outsides register area, "offset" value
1508         // helps us to calculate stack slot for remained part properly.
1509         offset = RegEnd - RegBegin;
1510
1511         CCInfo.nextInRegsParam();
1512       }
1513
1514       if (Flags.getByValSize() > 4*offset) {
1515         unsigned LocMemOffset = VA.getLocMemOffset();
1516         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1517         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1518                                   StkPtrOff);
1519         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1520         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1521         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1522                                            MVT::i32);
1523         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1524
1525         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1526         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1527         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1528                                           Ops, array_lengthof(Ops)));
1529       }
1530     } else if (!isSibCall) {
1531       assert(VA.isMemLoc());
1532
1533       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1534                                              dl, DAG, VA, Flags));
1535     }
1536   }
1537
1538   if (!MemOpChains.empty())
1539     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1540                         &MemOpChains[0], MemOpChains.size());
1541
1542   // Build a sequence of copy-to-reg nodes chained together with token chain
1543   // and flag operands which copy the outgoing args into the appropriate regs.
1544   SDValue InFlag;
1545   // Tail call byval lowering might overwrite argument registers so in case of
1546   // tail call optimization the copies to registers are lowered later.
1547   if (!isTailCall)
1548     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1549       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1550                                RegsToPass[i].second, InFlag);
1551       InFlag = Chain.getValue(1);
1552     }
1553
1554   // For tail calls lower the arguments to the 'real' stack slot.
1555   if (isTailCall) {
1556     // Force all the incoming stack arguments to be loaded from the stack
1557     // before any new outgoing arguments are stored to the stack, because the
1558     // outgoing stack slots may alias the incoming argument stack slots, and
1559     // the alias isn't otherwise explicit. This is slightly more conservative
1560     // than necessary, because it means that each store effectively depends
1561     // on every argument instead of just those arguments it would clobber.
1562
1563     // Do not flag preceding copytoreg stuff together with the following stuff.
1564     InFlag = SDValue();
1565     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1566       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1567                                RegsToPass[i].second, InFlag);
1568       InFlag = Chain.getValue(1);
1569     }
1570     InFlag = SDValue();
1571   }
1572
1573   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1574   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1575   // node so that legalize doesn't hack it.
1576   bool isDirect = false;
1577   bool isARMFunc = false;
1578   bool isLocalARMFunc = false;
1579   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1580
1581   if (EnableARMLongCalls) {
1582     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1583             && "long-calls with non-static relocation model!");
1584     // Handle a global address or an external symbol. If it's not one of
1585     // those, the target's already in a register, so we don't need to do
1586     // anything extra.
1587     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1588       const GlobalValue *GV = G->getGlobal();
1589       // Create a constant pool entry for the callee address
1590       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1591       ARMConstantPoolValue *CPV =
1592         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1593
1594       // Get the address of the callee into a register
1595       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1596       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1597       Callee = DAG.getLoad(getPointerTy(), dl,
1598                            DAG.getEntryNode(), CPAddr,
1599                            MachinePointerInfo::getConstantPool(),
1600                            false, false, false, 0);
1601     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1602       const char *Sym = S->getSymbol();
1603
1604       // Create a constant pool entry for the callee address
1605       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1606       ARMConstantPoolValue *CPV =
1607         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1608                                       ARMPCLabelIndex, 0);
1609       // Get the address of the callee into a register
1610       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1611       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1612       Callee = DAG.getLoad(getPointerTy(), dl,
1613                            DAG.getEntryNode(), CPAddr,
1614                            MachinePointerInfo::getConstantPool(),
1615                            false, false, false, 0);
1616     }
1617   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1618     const GlobalValue *GV = G->getGlobal();
1619     isDirect = true;
1620     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1621     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1622                    getTargetMachine().getRelocationModel() != Reloc::Static;
1623     isARMFunc = !Subtarget->isThumb() || isStub;
1624     // ARM call to a local ARM function is predicable.
1625     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1626     // tBX takes a register source operand.
1627     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1628       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1629       ARMConstantPoolValue *CPV =
1630         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1631       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1632       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1633       Callee = DAG.getLoad(getPointerTy(), dl,
1634                            DAG.getEntryNode(), CPAddr,
1635                            MachinePointerInfo::getConstantPool(),
1636                            false, false, false, 0);
1637       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1638       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1639                            getPointerTy(), Callee, PICLabel);
1640     } else {
1641       // On ELF targets for PIC code, direct calls should go through the PLT
1642       unsigned OpFlags = 0;
1643       if (Subtarget->isTargetELF() &&
1644           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1645         OpFlags = ARMII::MO_PLT;
1646       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1647     }
1648   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1649     isDirect = true;
1650     bool isStub = Subtarget->isTargetDarwin() &&
1651                   getTargetMachine().getRelocationModel() != Reloc::Static;
1652     isARMFunc = !Subtarget->isThumb() || isStub;
1653     // tBX takes a register source operand.
1654     const char *Sym = S->getSymbol();
1655     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1656       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1657       ARMConstantPoolValue *CPV =
1658         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1659                                       ARMPCLabelIndex, 4);
1660       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1661       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1662       Callee = DAG.getLoad(getPointerTy(), dl,
1663                            DAG.getEntryNode(), CPAddr,
1664                            MachinePointerInfo::getConstantPool(),
1665                            false, false, false, 0);
1666       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1667       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1668                            getPointerTy(), Callee, PICLabel);
1669     } else {
1670       unsigned OpFlags = 0;
1671       // On ELF targets for PIC code, direct calls should go through the PLT
1672       if (Subtarget->isTargetELF() &&
1673                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1674         OpFlags = ARMII::MO_PLT;
1675       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1676     }
1677   }
1678
1679   // FIXME: handle tail calls differently.
1680   unsigned CallOpc;
1681   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1682     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1683   if (Subtarget->isThumb()) {
1684     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1685       CallOpc = ARMISD::CALL_NOLINK;
1686     else
1687       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1688   } else {
1689     if (!isDirect && !Subtarget->hasV5TOps())
1690       CallOpc = ARMISD::CALL_NOLINK;
1691     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1692                // Emit regular call when code size is the priority
1693                !HasMinSizeAttr)
1694       // "mov lr, pc; b _foo" to avoid confusing the RSP
1695       CallOpc = ARMISD::CALL_NOLINK;
1696     else
1697       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1698   }
1699
1700   std::vector<SDValue> Ops;
1701   Ops.push_back(Chain);
1702   Ops.push_back(Callee);
1703
1704   // Add argument registers to the end of the list so that they are known live
1705   // into the call.
1706   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1707     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1708                                   RegsToPass[i].second.getValueType()));
1709
1710   // Add a register mask operand representing the call-preserved registers.
1711   const uint32_t *Mask;
1712   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1713   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1714   if (isThisReturn) {
1715     // For 'this' returns, use the R0-preserving mask if applicable
1716     Mask = ARI->getThisReturnPreservedMask(CallConv);
1717     if (!Mask) {
1718       // Set isThisReturn to false if the calling convention is not one that
1719       // allows 'returned' to be modeled in this way, so LowerCallResult does
1720       // not try to pass 'this' straight through 
1721       isThisReturn = false;
1722       Mask = ARI->getCallPreservedMask(CallConv);
1723     }
1724   } else
1725     Mask = ARI->getCallPreservedMask(CallConv);
1726
1727   assert(Mask && "Missing call preserved mask for calling convention");
1728   Ops.push_back(DAG.getRegisterMask(Mask));
1729
1730   if (InFlag.getNode())
1731     Ops.push_back(InFlag);
1732
1733   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1734   if (isTailCall)
1735     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1736
1737   // Returns a chain and a flag for retval copy to use.
1738   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1739   InFlag = Chain.getValue(1);
1740
1741   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1742                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1743   if (!Ins.empty())
1744     InFlag = Chain.getValue(1);
1745
1746   // Handle result values, copying them out of physregs into vregs that we
1747   // return.
1748   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1749                          InVals, isThisReturn,
1750                          isThisReturn ? OutVals[0] : SDValue());
1751 }
1752
1753 /// HandleByVal - Every parameter *after* a byval parameter is passed
1754 /// on the stack.  Remember the next parameter register to allocate,
1755 /// and then confiscate the rest of the parameter registers to insure
1756 /// this.
1757 void
1758 ARMTargetLowering::HandleByVal(
1759     CCState *State, unsigned &size, unsigned Align) const {
1760   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1761   assert((State->getCallOrPrologue() == Prologue ||
1762           State->getCallOrPrologue() == Call) &&
1763          "unhandled ParmContext");
1764
1765   // For in-prologue parameters handling, we also introduce stack offset
1766   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1767   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1768   // NSAA should be evaluted (NSAA means "next stacked argument address").
1769   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1770   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1771   unsigned NSAAOffset = State->getNextStackOffset();
1772   if (State->getCallOrPrologue() != Call) {
1773     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1774       unsigned RB, RE;
1775       State->getInRegsParamInfo(i, RB, RE);
1776       assert(NSAAOffset >= (RE-RB)*4 &&
1777              "Stack offset for byval regs doesn't introduced anymore?");
1778       NSAAOffset -= (RE-RB)*4;
1779     }
1780   }
1781   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1782     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1783       unsigned AlignInRegs = Align / 4;
1784       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1785       for (unsigned i = 0; i < Waste; ++i)
1786         reg = State->AllocateReg(GPRArgRegs, 4);
1787     }
1788     if (reg != 0) {
1789       unsigned excess = 4 * (ARM::R4 - reg);
1790
1791       // Special case when NSAA != SP and parameter size greater than size of
1792       // all remained GPR regs. In that case we can't split parameter, we must
1793       // send it to stack. We also must set NCRN to R4, so waste all
1794       // remained registers.
1795       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1796         while (State->AllocateReg(GPRArgRegs, 4))
1797           ;
1798         return;
1799       }
1800
1801       // First register for byval parameter is the first register that wasn't
1802       // allocated before this method call, so it would be "reg".
1803       // If parameter is small enough to be saved in range [reg, r4), then
1804       // the end (first after last) register would be reg + param-size-in-regs,
1805       // else parameter would be splitted between registers and stack,
1806       // end register would be r4 in this case.
1807       unsigned ByValRegBegin = reg;
1808       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1809       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1810       // Note, first register is allocated in the beginning of function already,
1811       // allocate remained amount of registers we need.
1812       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1813         State->AllocateReg(GPRArgRegs, 4);
1814       // At a call site, a byval parameter that is split between
1815       // registers and memory needs its size truncated here.  In a
1816       // function prologue, such byval parameters are reassembled in
1817       // memory, and are not truncated.
1818       if (State->getCallOrPrologue() == Call) {
1819         // Make remained size equal to 0 in case, when
1820         // the whole structure may be stored into registers.
1821         if (size < excess)
1822           size = 0;
1823         else
1824           size -= excess;
1825       }
1826     }
1827   }
1828 }
1829
1830 /// MatchingStackOffset - Return true if the given stack call argument is
1831 /// already available in the same position (relatively) of the caller's
1832 /// incoming argument stack.
1833 static
1834 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1835                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1836                          const TargetInstrInfo *TII) {
1837   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1838   int FI = INT_MAX;
1839   if (Arg.getOpcode() == ISD::CopyFromReg) {
1840     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1841     if (!TargetRegisterInfo::isVirtualRegister(VR))
1842       return false;
1843     MachineInstr *Def = MRI->getVRegDef(VR);
1844     if (!Def)
1845       return false;
1846     if (!Flags.isByVal()) {
1847       if (!TII->isLoadFromStackSlot(Def, FI))
1848         return false;
1849     } else {
1850       return false;
1851     }
1852   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1853     if (Flags.isByVal())
1854       // ByVal argument is passed in as a pointer but it's now being
1855       // dereferenced. e.g.
1856       // define @foo(%struct.X* %A) {
1857       //   tail call @bar(%struct.X* byval %A)
1858       // }
1859       return false;
1860     SDValue Ptr = Ld->getBasePtr();
1861     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1862     if (!FINode)
1863       return false;
1864     FI = FINode->getIndex();
1865   } else
1866     return false;
1867
1868   assert(FI != INT_MAX);
1869   if (!MFI->isFixedObjectIndex(FI))
1870     return false;
1871   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1872 }
1873
1874 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1875 /// for tail call optimization. Targets which want to do tail call
1876 /// optimization should implement this function.
1877 bool
1878 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1879                                                      CallingConv::ID CalleeCC,
1880                                                      bool isVarArg,
1881                                                      bool isCalleeStructRet,
1882                                                      bool isCallerStructRet,
1883                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1884                                     const SmallVectorImpl<SDValue> &OutVals,
1885                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1886                                                      SelectionDAG& DAG) const {
1887   const Function *CallerF = DAG.getMachineFunction().getFunction();
1888   CallingConv::ID CallerCC = CallerF->getCallingConv();
1889   bool CCMatch = CallerCC == CalleeCC;
1890
1891   // Look for obvious safe cases to perform tail call optimization that do not
1892   // require ABI changes. This is what gcc calls sibcall.
1893
1894   // Do not sibcall optimize vararg calls unless the call site is not passing
1895   // any arguments.
1896   if (isVarArg && !Outs.empty())
1897     return false;
1898
1899   // Also avoid sibcall optimization if either caller or callee uses struct
1900   // return semantics.
1901   if (isCalleeStructRet || isCallerStructRet)
1902     return false;
1903
1904   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1905   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1906   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1907   // support in the assembler and linker to be used. This would need to be
1908   // fixed to fully support tail calls in Thumb1.
1909   //
1910   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1911   // LR.  This means if we need to reload LR, it takes an extra instructions,
1912   // which outweighs the value of the tail call; but here we don't know yet
1913   // whether LR is going to be used.  Probably the right approach is to
1914   // generate the tail call here and turn it back into CALL/RET in
1915   // emitEpilogue if LR is used.
1916
1917   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1918   // but we need to make sure there are enough registers; the only valid
1919   // registers are the 4 used for parameters.  We don't currently do this
1920   // case.
1921   if (Subtarget->isThumb1Only())
1922     return false;
1923
1924   // If the calling conventions do not match, then we'd better make sure the
1925   // results are returned in the same way as what the caller expects.
1926   if (!CCMatch) {
1927     SmallVector<CCValAssign, 16> RVLocs1;
1928     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1929                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1930     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1931
1932     SmallVector<CCValAssign, 16> RVLocs2;
1933     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1934                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1935     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1936
1937     if (RVLocs1.size() != RVLocs2.size())
1938       return false;
1939     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1940       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1941         return false;
1942       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1943         return false;
1944       if (RVLocs1[i].isRegLoc()) {
1945         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1946           return false;
1947       } else {
1948         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1949           return false;
1950       }
1951     }
1952   }
1953
1954   // If Caller's vararg or byval argument has been split between registers and
1955   // stack, do not perform tail call, since part of the argument is in caller's
1956   // local frame.
1957   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1958                                       getInfo<ARMFunctionInfo>();
1959   if (AFI_Caller->getArgRegsSaveSize())
1960     return false;
1961
1962   // If the callee takes no arguments then go on to check the results of the
1963   // call.
1964   if (!Outs.empty()) {
1965     // Check if stack adjustment is needed. For now, do not do this if any
1966     // argument is passed on the stack.
1967     SmallVector<CCValAssign, 16> ArgLocs;
1968     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1969                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1970     CCInfo.AnalyzeCallOperands(Outs,
1971                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1972     if (CCInfo.getNextStackOffset()) {
1973       MachineFunction &MF = DAG.getMachineFunction();
1974
1975       // Check if the arguments are already laid out in the right way as
1976       // the caller's fixed stack objects.
1977       MachineFrameInfo *MFI = MF.getFrameInfo();
1978       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1979       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1980       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1981            i != e;
1982            ++i, ++realArgIdx) {
1983         CCValAssign &VA = ArgLocs[i];
1984         EVT RegVT = VA.getLocVT();
1985         SDValue Arg = OutVals[realArgIdx];
1986         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1987         if (VA.getLocInfo() == CCValAssign::Indirect)
1988           return false;
1989         if (VA.needsCustom()) {
1990           // f64 and vector types are split into multiple registers or
1991           // register/stack-slot combinations.  The types will not match
1992           // the registers; give up on memory f64 refs until we figure
1993           // out what to do about this.
1994           if (!VA.isRegLoc())
1995             return false;
1996           if (!ArgLocs[++i].isRegLoc())
1997             return false;
1998           if (RegVT == MVT::v2f64) {
1999             if (!ArgLocs[++i].isRegLoc())
2000               return false;
2001             if (!ArgLocs[++i].isRegLoc())
2002               return false;
2003           }
2004         } else if (!VA.isRegLoc()) {
2005           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2006                                    MFI, MRI, TII))
2007             return false;
2008         }
2009       }
2010     }
2011   }
2012
2013   return true;
2014 }
2015
2016 bool
2017 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2018                                   MachineFunction &MF, bool isVarArg,
2019                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2020                                   LLVMContext &Context) const {
2021   SmallVector<CCValAssign, 16> RVLocs;
2022   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2023   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2024                                                     isVarArg));
2025 }
2026
2027 SDValue
2028 ARMTargetLowering::LowerReturn(SDValue Chain,
2029                                CallingConv::ID CallConv, bool isVarArg,
2030                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2031                                const SmallVectorImpl<SDValue> &OutVals,
2032                                SDLoc dl, SelectionDAG &DAG) const {
2033
2034   // CCValAssign - represent the assignment of the return value to a location.
2035   SmallVector<CCValAssign, 16> RVLocs;
2036
2037   // CCState - Info about the registers and stack slots.
2038   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2039                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2040
2041   // Analyze outgoing return values.
2042   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2043                                                isVarArg));
2044
2045   SDValue Flag;
2046   SmallVector<SDValue, 4> RetOps;
2047   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2048
2049   // Copy the result values into the output registers.
2050   for (unsigned i = 0, realRVLocIdx = 0;
2051        i != RVLocs.size();
2052        ++i, ++realRVLocIdx) {
2053     CCValAssign &VA = RVLocs[i];
2054     assert(VA.isRegLoc() && "Can only return in registers!");
2055
2056     SDValue Arg = OutVals[realRVLocIdx];
2057
2058     switch (VA.getLocInfo()) {
2059     default: llvm_unreachable("Unknown loc info!");
2060     case CCValAssign::Full: break;
2061     case CCValAssign::BCvt:
2062       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2063       break;
2064     }
2065
2066     if (VA.needsCustom()) {
2067       if (VA.getLocVT() == MVT::v2f64) {
2068         // Extract the first half and return it in two registers.
2069         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2070                                    DAG.getConstant(0, MVT::i32));
2071         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2072                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2073
2074         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2075         Flag = Chain.getValue(1);
2076         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2077         VA = RVLocs[++i]; // skip ahead to next loc
2078         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2079                                  HalfGPRs.getValue(1), Flag);
2080         Flag = Chain.getValue(1);
2081         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2082         VA = RVLocs[++i]; // skip ahead to next loc
2083
2084         // Extract the 2nd half and fall through to handle it as an f64 value.
2085         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2086                           DAG.getConstant(1, MVT::i32));
2087       }
2088       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2089       // available.
2090       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2091                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2092       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2093       Flag = Chain.getValue(1);
2094       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2095       VA = RVLocs[++i]; // skip ahead to next loc
2096       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2097                                Flag);
2098     } else
2099       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2100
2101     // Guarantee that all emitted copies are
2102     // stuck together, avoiding something bad.
2103     Flag = Chain.getValue(1);
2104     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2105   }
2106
2107   // Update chain and glue.
2108   RetOps[0] = Chain;
2109   if (Flag.getNode())
2110     RetOps.push_back(Flag);
2111
2112   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2113                      RetOps.data(), RetOps.size());
2114 }
2115
2116 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2117   if (N->getNumValues() != 1)
2118     return false;
2119   if (!N->hasNUsesOfValue(1, 0))
2120     return false;
2121
2122   SDValue TCChain = Chain;
2123   SDNode *Copy = *N->use_begin();
2124   if (Copy->getOpcode() == ISD::CopyToReg) {
2125     // If the copy has a glue operand, we conservatively assume it isn't safe to
2126     // perform a tail call.
2127     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2128       return false;
2129     TCChain = Copy->getOperand(0);
2130   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2131     SDNode *VMov = Copy;
2132     // f64 returned in a pair of GPRs.
2133     SmallPtrSet<SDNode*, 2> Copies;
2134     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2135          UI != UE; ++UI) {
2136       if (UI->getOpcode() != ISD::CopyToReg)
2137         return false;
2138       Copies.insert(*UI);
2139     }
2140     if (Copies.size() > 2)
2141       return false;
2142
2143     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2144          UI != UE; ++UI) {
2145       SDValue UseChain = UI->getOperand(0);
2146       if (Copies.count(UseChain.getNode()))
2147         // Second CopyToReg
2148         Copy = *UI;
2149       else
2150         // First CopyToReg
2151         TCChain = UseChain;
2152     }
2153   } else if (Copy->getOpcode() == ISD::BITCAST) {
2154     // f32 returned in a single GPR.
2155     if (!Copy->hasOneUse())
2156       return false;
2157     Copy = *Copy->use_begin();
2158     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2159       return false;
2160     TCChain = Copy->getOperand(0);
2161   } else {
2162     return false;
2163   }
2164
2165   bool HasRet = false;
2166   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2167        UI != UE; ++UI) {
2168     if (UI->getOpcode() != ARMISD::RET_FLAG)
2169       return false;
2170     HasRet = true;
2171   }
2172
2173   if (!HasRet)
2174     return false;
2175
2176   Chain = TCChain;
2177   return true;
2178 }
2179
2180 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2181   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2182     return false;
2183
2184   if (!CI->isTailCall())
2185     return false;
2186
2187   return !Subtarget->isThumb1Only();
2188 }
2189
2190 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2191 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2192 // one of the above mentioned nodes. It has to be wrapped because otherwise
2193 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2194 // be used to form addressing mode. These wrapped nodes will be selected
2195 // into MOVi.
2196 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2197   EVT PtrVT = Op.getValueType();
2198   // FIXME there is no actual debug info here
2199   SDLoc dl(Op);
2200   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2201   SDValue Res;
2202   if (CP->isMachineConstantPoolEntry())
2203     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2204                                     CP->getAlignment());
2205   else
2206     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2207                                     CP->getAlignment());
2208   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2209 }
2210
2211 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2212   return MachineJumpTableInfo::EK_Inline;
2213 }
2214
2215 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2216                                              SelectionDAG &DAG) const {
2217   MachineFunction &MF = DAG.getMachineFunction();
2218   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2219   unsigned ARMPCLabelIndex = 0;
2220   SDLoc DL(Op);
2221   EVT PtrVT = getPointerTy();
2222   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2223   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2224   SDValue CPAddr;
2225   if (RelocM == Reloc::Static) {
2226     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2227   } else {
2228     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2229     ARMPCLabelIndex = AFI->createPICLabelUId();
2230     ARMConstantPoolValue *CPV =
2231       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2232                                       ARMCP::CPBlockAddress, PCAdj);
2233     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2234   }
2235   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2236   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2237                                MachinePointerInfo::getConstantPool(),
2238                                false, false, false, 0);
2239   if (RelocM == Reloc::Static)
2240     return Result;
2241   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2242   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2243 }
2244
2245 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2246 SDValue
2247 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2248                                                  SelectionDAG &DAG) const {
2249   SDLoc dl(GA);
2250   EVT PtrVT = getPointerTy();
2251   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2252   MachineFunction &MF = DAG.getMachineFunction();
2253   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2254   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2255   ARMConstantPoolValue *CPV =
2256     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2257                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2258   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2259   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2260   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2261                          MachinePointerInfo::getConstantPool(),
2262                          false, false, false, 0);
2263   SDValue Chain = Argument.getValue(1);
2264
2265   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2266   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2267
2268   // call __tls_get_addr.
2269   ArgListTy Args;
2270   ArgListEntry Entry;
2271   Entry.Node = Argument;
2272   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2273   Args.push_back(Entry);
2274   // FIXME: is there useful debug info available here?
2275   TargetLowering::CallLoweringInfo CLI(Chain,
2276                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2277                 false, false, false, false,
2278                 0, CallingConv::C, /*isTailCall=*/false,
2279                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2280                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2281   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2282   return CallResult.first;
2283 }
2284
2285 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2286 // "local exec" model.
2287 SDValue
2288 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2289                                         SelectionDAG &DAG,
2290                                         TLSModel::Model model) const {
2291   const GlobalValue *GV = GA->getGlobal();
2292   SDLoc dl(GA);
2293   SDValue Offset;
2294   SDValue Chain = DAG.getEntryNode();
2295   EVT PtrVT = getPointerTy();
2296   // Get the Thread Pointer
2297   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2298
2299   if (model == TLSModel::InitialExec) {
2300     MachineFunction &MF = DAG.getMachineFunction();
2301     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2302     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2303     // Initial exec model.
2304     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2305     ARMConstantPoolValue *CPV =
2306       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2307                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2308                                       true);
2309     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2310     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2311     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2312                          MachinePointerInfo::getConstantPool(),
2313                          false, false, false, 0);
2314     Chain = Offset.getValue(1);
2315
2316     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2317     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2318
2319     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2320                          MachinePointerInfo::getConstantPool(),
2321                          false, false, false, 0);
2322   } else {
2323     // local exec model
2324     assert(model == TLSModel::LocalExec);
2325     ARMConstantPoolValue *CPV =
2326       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2327     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2328     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2329     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2330                          MachinePointerInfo::getConstantPool(),
2331                          false, false, false, 0);
2332   }
2333
2334   // The address of the thread local variable is the add of the thread
2335   // pointer with the offset of the variable.
2336   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2337 }
2338
2339 SDValue
2340 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2341   // TODO: implement the "local dynamic" model
2342   assert(Subtarget->isTargetELF() &&
2343          "TLS not implemented for non-ELF targets");
2344   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2345
2346   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2347
2348   switch (model) {
2349     case TLSModel::GeneralDynamic:
2350     case TLSModel::LocalDynamic:
2351       return LowerToTLSGeneralDynamicModel(GA, DAG);
2352     case TLSModel::InitialExec:
2353     case TLSModel::LocalExec:
2354       return LowerToTLSExecModels(GA, DAG, model);
2355   }
2356   llvm_unreachable("bogus TLS model");
2357 }
2358
2359 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2360                                                  SelectionDAG &DAG) const {
2361   EVT PtrVT = getPointerTy();
2362   SDLoc dl(Op);
2363   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2364   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2365     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2366     ARMConstantPoolValue *CPV =
2367       ARMConstantPoolConstant::Create(GV,
2368                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2369     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2370     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2371     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2372                                  CPAddr,
2373                                  MachinePointerInfo::getConstantPool(),
2374                                  false, false, false, 0);
2375     SDValue Chain = Result.getValue(1);
2376     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2377     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2378     if (!UseGOTOFF)
2379       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2380                            MachinePointerInfo::getGOT(),
2381                            false, false, false, 0);
2382     return Result;
2383   }
2384
2385   // If we have T2 ops, we can materialize the address directly via movt/movw
2386   // pair. This is always cheaper.
2387   if (Subtarget->useMovt()) {
2388     ++NumMovwMovt;
2389     // FIXME: Once remat is capable of dealing with instructions with register
2390     // operands, expand this into two nodes.
2391     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2392                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2393   } else {
2394     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2395     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2396     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2397                        MachinePointerInfo::getConstantPool(),
2398                        false, false, false, 0);
2399   }
2400 }
2401
2402 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2403                                                     SelectionDAG &DAG) const {
2404   EVT PtrVT = getPointerTy();
2405   SDLoc dl(Op);
2406   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2407   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2408
2409   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2410   // update ARMFastISel::ARMMaterializeGV.
2411   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2412     ++NumMovwMovt;
2413     // FIXME: Once remat is capable of dealing with instructions with register
2414     // operands, expand this into two nodes.
2415     if (RelocM == Reloc::Static)
2416       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2417                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2418
2419     unsigned Wrapper = (RelocM == Reloc::PIC_)
2420       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2421     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2422                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2423     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2424       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2425                            MachinePointerInfo::getGOT(),
2426                            false, false, false, 0);
2427     return Result;
2428   }
2429
2430   unsigned ARMPCLabelIndex = 0;
2431   SDValue CPAddr;
2432   if (RelocM == Reloc::Static) {
2433     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2434   } else {
2435     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2436     ARMPCLabelIndex = AFI->createPICLabelUId();
2437     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2438     ARMConstantPoolValue *CPV =
2439       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2440                                       PCAdj);
2441     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2442   }
2443   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2444
2445   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2446                                MachinePointerInfo::getConstantPool(),
2447                                false, false, false, 0);
2448   SDValue Chain = Result.getValue(1);
2449
2450   if (RelocM == Reloc::PIC_) {
2451     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2452     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2453   }
2454
2455   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2456     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2457                          false, false, false, 0);
2458
2459   return Result;
2460 }
2461
2462 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2463                                                     SelectionDAG &DAG) const {
2464   assert(Subtarget->isTargetELF() &&
2465          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2466   MachineFunction &MF = DAG.getMachineFunction();
2467   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2468   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2469   EVT PtrVT = getPointerTy();
2470   SDLoc dl(Op);
2471   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2472   ARMConstantPoolValue *CPV =
2473     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2474                                   ARMPCLabelIndex, PCAdj);
2475   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2476   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2477   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2478                                MachinePointerInfo::getConstantPool(),
2479                                false, false, false, 0);
2480   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2481   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2482 }
2483
2484 SDValue
2485 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2486   SDLoc dl(Op);
2487   SDValue Val = DAG.getConstant(0, MVT::i32);
2488   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2489                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2490                      Op.getOperand(1), Val);
2491 }
2492
2493 SDValue
2494 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2495   SDLoc dl(Op);
2496   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2497                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2498 }
2499
2500 SDValue
2501 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2502                                           const ARMSubtarget *Subtarget) const {
2503   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2504   SDLoc dl(Op);
2505   switch (IntNo) {
2506   default: return SDValue();    // Don't custom lower most intrinsics.
2507   case Intrinsic::arm_thread_pointer: {
2508     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2509     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2510   }
2511   case Intrinsic::eh_sjlj_lsda: {
2512     MachineFunction &MF = DAG.getMachineFunction();
2513     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2514     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2515     EVT PtrVT = getPointerTy();
2516     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2517     SDValue CPAddr;
2518     unsigned PCAdj = (RelocM != Reloc::PIC_)
2519       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2520     ARMConstantPoolValue *CPV =
2521       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2522                                       ARMCP::CPLSDA, PCAdj);
2523     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2524     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2525     SDValue Result =
2526       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2527                   MachinePointerInfo::getConstantPool(),
2528                   false, false, false, 0);
2529
2530     if (RelocM == Reloc::PIC_) {
2531       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2532       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2533     }
2534     return Result;
2535   }
2536   case Intrinsic::arm_neon_vmulls:
2537   case Intrinsic::arm_neon_vmullu: {
2538     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2539       ? ARMISD::VMULLs : ARMISD::VMULLu;
2540     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2541                        Op.getOperand(1), Op.getOperand(2));
2542   }
2543   }
2544 }
2545
2546 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2547                                  const ARMSubtarget *Subtarget) {
2548   // FIXME: handle "fence singlethread" more efficiently.
2549   SDLoc dl(Op);
2550   if (!Subtarget->hasDataBarrier()) {
2551     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2552     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2553     // here.
2554     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2555            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2556     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2557                        DAG.getConstant(0, MVT::i32));
2558   }
2559
2560   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2561   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2562   unsigned Domain = ARM_MB::ISH;
2563   if (Subtarget->isSwift() && Ord == Release) {
2564     // Swift happens to implement ISHST barriers in a way that's compatible with
2565     // Release semantics but weaker than ISH so we'd be fools not to use
2566     // it. Beware: other processors probably don't!
2567     Domain = ARM_MB::ISHST;
2568   }
2569
2570   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2571                      DAG.getConstant(Domain, MVT::i32));
2572 }
2573
2574 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2575                              const ARMSubtarget *Subtarget) {
2576   // ARM pre v5TE and Thumb1 does not have preload instructions.
2577   if (!(Subtarget->isThumb2() ||
2578         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2579     // Just preserve the chain.
2580     return Op.getOperand(0);
2581
2582   SDLoc dl(Op);
2583   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2584   if (!isRead &&
2585       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2586     // ARMv7 with MP extension has PLDW.
2587     return Op.getOperand(0);
2588
2589   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2590   if (Subtarget->isThumb()) {
2591     // Invert the bits.
2592     isRead = ~isRead & 1;
2593     isData = ~isData & 1;
2594   }
2595
2596   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2597                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2598                      DAG.getConstant(isData, MVT::i32));
2599 }
2600
2601 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2602   MachineFunction &MF = DAG.getMachineFunction();
2603   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2604
2605   // vastart just stores the address of the VarArgsFrameIndex slot into the
2606   // memory location argument.
2607   SDLoc dl(Op);
2608   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2609   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2610   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2611   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2612                       MachinePointerInfo(SV), false, false, 0);
2613 }
2614
2615 SDValue
2616 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2617                                         SDValue &Root, SelectionDAG &DAG,
2618                                         SDLoc dl) const {
2619   MachineFunction &MF = DAG.getMachineFunction();
2620   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2621
2622   const TargetRegisterClass *RC;
2623   if (AFI->isThumb1OnlyFunction())
2624     RC = &ARM::tGPRRegClass;
2625   else
2626     RC = &ARM::GPRRegClass;
2627
2628   // Transform the arguments stored in physical registers into virtual ones.
2629   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2630   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2631
2632   SDValue ArgValue2;
2633   if (NextVA.isMemLoc()) {
2634     MachineFrameInfo *MFI = MF.getFrameInfo();
2635     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2636
2637     // Create load node to retrieve arguments from the stack.
2638     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2639     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2640                             MachinePointerInfo::getFixedStack(FI),
2641                             false, false, false, 0);
2642   } else {
2643     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2644     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2645   }
2646
2647   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2648 }
2649
2650 void
2651 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2652                                   unsigned InRegsParamRecordIdx,
2653                                   unsigned ArgSize,
2654                                   unsigned &ArgRegsSize,
2655                                   unsigned &ArgRegsSaveSize)
2656   const {
2657   unsigned NumGPRs;
2658   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2659     unsigned RBegin, REnd;
2660     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2661     NumGPRs = REnd - RBegin;
2662   } else {
2663     unsigned int firstUnalloced;
2664     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2665                                                 sizeof(GPRArgRegs) /
2666                                                 sizeof(GPRArgRegs[0]));
2667     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2668   }
2669
2670   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2671   ArgRegsSize = NumGPRs * 4;
2672
2673   // If parameter is split between stack and GPRs...
2674   if (NumGPRs && Align == 8 &&
2675       (ArgRegsSize < ArgSize ||
2676         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2677     // Add padding for part of param recovered from GPRs, so
2678     // its last byte must be at address K*8 - 1.
2679     // We need to do it, since remained (stack) part of parameter has
2680     // stack alignment, and we need to "attach" "GPRs head" without gaps
2681     // to it:
2682     // Stack:
2683     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2684     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2685     //
2686     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2687     unsigned Padding =
2688         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2689         (ArgRegsSize + AFI->getArgRegsSaveSize());
2690     ArgRegsSaveSize = ArgRegsSize + Padding;
2691   } else
2692     // We don't need to extend regs save size for byval parameters if they
2693     // are passed via GPRs only.
2694     ArgRegsSaveSize = ArgRegsSize;
2695 }
2696
2697 // The remaining GPRs hold either the beginning of variable-argument
2698 // data, or the beginning of an aggregate passed by value (usually
2699 // byval).  Either way, we allocate stack slots adjacent to the data
2700 // provided by our caller, and store the unallocated registers there.
2701 // If this is a variadic function, the va_list pointer will begin with
2702 // these values; otherwise, this reassembles a (byval) structure that
2703 // was split between registers and memory.
2704 // Return: The frame index registers were stored into.
2705 int
2706 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2707                                   SDLoc dl, SDValue &Chain,
2708                                   const Value *OrigArg,
2709                                   unsigned InRegsParamRecordIdx,
2710                                   unsigned OffsetFromOrigArg,
2711                                   unsigned ArgOffset,
2712                                   unsigned ArgSize,
2713                                   bool ForceMutable) const {
2714
2715   // Currently, two use-cases possible:
2716   // Case #1. Non var-args function, and we meet first byval parameter.
2717   //          Setup first unallocated register as first byval register;
2718   //          eat all remained registers
2719   //          (these two actions are performed by HandleByVal method).
2720   //          Then, here, we initialize stack frame with
2721   //          "store-reg" instructions.
2722   // Case #2. Var-args function, that doesn't contain byval parameters.
2723   //          The same: eat all remained unallocated registers,
2724   //          initialize stack frame.
2725
2726   MachineFunction &MF = DAG.getMachineFunction();
2727   MachineFrameInfo *MFI = MF.getFrameInfo();
2728   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2729   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2730   unsigned RBegin, REnd;
2731   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2732     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2733     firstRegToSaveIndex = RBegin - ARM::R0;
2734     lastRegToSaveIndex = REnd - ARM::R0;
2735   } else {
2736     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2737       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2738     lastRegToSaveIndex = 4;
2739   }
2740
2741   unsigned ArgRegsSize, ArgRegsSaveSize;
2742   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2743                  ArgRegsSize, ArgRegsSaveSize);
2744
2745   // Store any by-val regs to their spots on the stack so that they may be
2746   // loaded by deferencing the result of formal parameter pointer or va_next.
2747   // Note: once stack area for byval/varargs registers
2748   // was initialized, it can't be initialized again.
2749   if (ArgRegsSaveSize) {
2750
2751     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2752
2753     if (Padding) {
2754       assert(AFI->getStoredByValParamsPadding() == 0 &&
2755              "The only parameter may be padded.");
2756       AFI->setStoredByValParamsPadding(Padding);
2757     }
2758
2759     int FrameIndex = MFI->CreateFixedObject(
2760                       ArgRegsSaveSize,
2761                       Padding + ArgOffset,
2762                       false);
2763     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2764
2765     SmallVector<SDValue, 4> MemOps;
2766     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2767          ++firstRegToSaveIndex, ++i) {
2768       const TargetRegisterClass *RC;
2769       if (AFI->isThumb1OnlyFunction())
2770         RC = &ARM::tGPRRegClass;
2771       else
2772         RC = &ARM::GPRRegClass;
2773
2774       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2775       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2776       SDValue Store =
2777         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2778                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2779                      false, false, 0);
2780       MemOps.push_back(Store);
2781       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2782                         DAG.getConstant(4, getPointerTy()));
2783     }
2784
2785     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2786
2787     if (!MemOps.empty())
2788       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2789                           &MemOps[0], MemOps.size());
2790     return FrameIndex;
2791   } else
2792     // This will point to the next argument passed via stack.
2793     return MFI->CreateFixedObject(
2794         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2795 }
2796
2797 // Setup stack frame, the va_list pointer will start from.
2798 void
2799 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2800                                         SDLoc dl, SDValue &Chain,
2801                                         unsigned ArgOffset,
2802                                         bool ForceMutable) const {
2803   MachineFunction &MF = DAG.getMachineFunction();
2804   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2805
2806   // Try to store any remaining integer argument regs
2807   // to their spots on the stack so that they may be loaded by deferencing
2808   // the result of va_next.
2809   // If there is no regs to be stored, just point address after last
2810   // argument passed via stack.
2811   int FrameIndex =
2812     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2813                    0, ArgOffset, 0, ForceMutable);
2814
2815   AFI->setVarArgsFrameIndex(FrameIndex);
2816 }
2817
2818 SDValue
2819 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2820                                         CallingConv::ID CallConv, bool isVarArg,
2821                                         const SmallVectorImpl<ISD::InputArg>
2822                                           &Ins,
2823                                         SDLoc dl, SelectionDAG &DAG,
2824                                         SmallVectorImpl<SDValue> &InVals)
2825                                           const {
2826   MachineFunction &MF = DAG.getMachineFunction();
2827   MachineFrameInfo *MFI = MF.getFrameInfo();
2828
2829   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2830
2831   // Assign locations to all of the incoming arguments.
2832   SmallVector<CCValAssign, 16> ArgLocs;
2833   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2834                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2835   CCInfo.AnalyzeFormalArguments(Ins,
2836                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2837                                                   isVarArg));
2838
2839   SmallVector<SDValue, 16> ArgValues;
2840   int lastInsIndex = -1;
2841   SDValue ArgValue;
2842   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2843   unsigned CurArgIdx = 0;
2844
2845   // Initially ArgRegsSaveSize is zero.
2846   // Then we increase this value each time we meet byval parameter.
2847   // We also increase this value in case of varargs function.
2848   AFI->setArgRegsSaveSize(0);
2849
2850   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851     CCValAssign &VA = ArgLocs[i];
2852     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2853     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2854     // Arguments stored in registers.
2855     if (VA.isRegLoc()) {
2856       EVT RegVT = VA.getLocVT();
2857
2858       if (VA.needsCustom()) {
2859         // f64 and vector types are split up into multiple registers or
2860         // combinations of registers and stack slots.
2861         if (VA.getLocVT() == MVT::v2f64) {
2862           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2863                                                    Chain, DAG, dl);
2864           VA = ArgLocs[++i]; // skip ahead to next loc
2865           SDValue ArgValue2;
2866           if (VA.isMemLoc()) {
2867             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2868             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2869             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2870                                     MachinePointerInfo::getFixedStack(FI),
2871                                     false, false, false, 0);
2872           } else {
2873             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2874                                              Chain, DAG, dl);
2875           }
2876           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2877           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2878                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2879           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2880                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2881         } else
2882           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2883
2884       } else {
2885         const TargetRegisterClass *RC;
2886
2887         if (RegVT == MVT::f32)
2888           RC = &ARM::SPRRegClass;
2889         else if (RegVT == MVT::f64)
2890           RC = &ARM::DPRRegClass;
2891         else if (RegVT == MVT::v2f64)
2892           RC = &ARM::QPRRegClass;
2893         else if (RegVT == MVT::i32)
2894           RC = AFI->isThumb1OnlyFunction() ?
2895             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2896             (const TargetRegisterClass*)&ARM::GPRRegClass;
2897         else
2898           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2899
2900         // Transform the arguments in physical registers into virtual ones.
2901         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2902         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2903       }
2904
2905       // If this is an 8 or 16-bit value, it is really passed promoted
2906       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2907       // truncate to the right size.
2908       switch (VA.getLocInfo()) {
2909       default: llvm_unreachable("Unknown loc info!");
2910       case CCValAssign::Full: break;
2911       case CCValAssign::BCvt:
2912         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2913         break;
2914       case CCValAssign::SExt:
2915         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2916                                DAG.getValueType(VA.getValVT()));
2917         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2918         break;
2919       case CCValAssign::ZExt:
2920         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2921                                DAG.getValueType(VA.getValVT()));
2922         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2923         break;
2924       }
2925
2926       InVals.push_back(ArgValue);
2927
2928     } else { // VA.isRegLoc()
2929
2930       // sanity check
2931       assert(VA.isMemLoc());
2932       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2933
2934       int index = ArgLocs[i].getValNo();
2935
2936       // Some Ins[] entries become multiple ArgLoc[] entries.
2937       // Process them only once.
2938       if (index != lastInsIndex)
2939         {
2940           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2941           // FIXME: For now, all byval parameter objects are marked mutable.
2942           // This can be changed with more analysis.
2943           // In case of tail call optimization mark all arguments mutable.
2944           // Since they could be overwritten by lowering of arguments in case of
2945           // a tail call.
2946           if (Flags.isByVal()) {
2947             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2948             int FrameIndex = StoreByValRegs(
2949                 CCInfo, DAG, dl, Chain, CurOrigArg,
2950                 CurByValIndex,
2951                 Ins[VA.getValNo()].PartOffset,
2952                 VA.getLocMemOffset(),
2953                 Flags.getByValSize(),
2954                 true /*force mutable frames*/);
2955             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2956             CCInfo.nextInRegsParam();
2957           } else {
2958             unsigned FIOffset = VA.getLocMemOffset() +
2959                                 AFI->getStoredByValParamsPadding();
2960             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2961                                             FIOffset, true);
2962
2963             // Create load nodes to retrieve arguments from the stack.
2964             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2965             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2966                                          MachinePointerInfo::getFixedStack(FI),
2967                                          false, false, false, 0));
2968           }
2969           lastInsIndex = index;
2970         }
2971     }
2972   }
2973
2974   // varargs
2975   if (isVarArg)
2976     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2977                          CCInfo.getNextStackOffset());
2978
2979   return Chain;
2980 }
2981
2982 /// isFloatingPointZero - Return true if this is +0.0.
2983 static bool isFloatingPointZero(SDValue Op) {
2984   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2985     return CFP->getValueAPF().isPosZero();
2986   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2987     // Maybe this has already been legalized into the constant pool?
2988     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2989       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2990       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2991         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2992           return CFP->getValueAPF().isPosZero();
2993     }
2994   }
2995   return false;
2996 }
2997
2998 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2999 /// the given operands.
3000 SDValue
3001 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3002                              SDValue &ARMcc, SelectionDAG &DAG,
3003                              SDLoc dl) const {
3004   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3005     unsigned C = RHSC->getZExtValue();
3006     if (!isLegalICmpImmediate(C)) {
3007       // Constant does not fit, try adjusting it by one?
3008       switch (CC) {
3009       default: break;
3010       case ISD::SETLT:
3011       case ISD::SETGE:
3012         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3013           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3014           RHS = DAG.getConstant(C-1, MVT::i32);
3015         }
3016         break;
3017       case ISD::SETULT:
3018       case ISD::SETUGE:
3019         if (C != 0 && isLegalICmpImmediate(C-1)) {
3020           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3021           RHS = DAG.getConstant(C-1, MVT::i32);
3022         }
3023         break;
3024       case ISD::SETLE:
3025       case ISD::SETGT:
3026         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3027           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3028           RHS = DAG.getConstant(C+1, MVT::i32);
3029         }
3030         break;
3031       case ISD::SETULE:
3032       case ISD::SETUGT:
3033         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3034           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3035           RHS = DAG.getConstant(C+1, MVT::i32);
3036         }
3037         break;
3038       }
3039     }
3040   }
3041
3042   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3043   ARMISD::NodeType CompareType;
3044   switch (CondCode) {
3045   default:
3046     CompareType = ARMISD::CMP;
3047     break;
3048   case ARMCC::EQ:
3049   case ARMCC::NE:
3050     // Uses only Z Flag
3051     CompareType = ARMISD::CMPZ;
3052     break;
3053   }
3054   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3055   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3056 }
3057
3058 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3059 SDValue
3060 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3061                              SDLoc dl) const {
3062   SDValue Cmp;
3063   if (!isFloatingPointZero(RHS))
3064     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3065   else
3066     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3067   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3068 }
3069
3070 /// duplicateCmp - Glue values can have only one use, so this function
3071 /// duplicates a comparison node.
3072 SDValue
3073 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3074   unsigned Opc = Cmp.getOpcode();
3075   SDLoc DL(Cmp);
3076   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3077     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3078
3079   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3080   Cmp = Cmp.getOperand(0);
3081   Opc = Cmp.getOpcode();
3082   if (Opc == ARMISD::CMPFP)
3083     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3084   else {
3085     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3086     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3087   }
3088   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3089 }
3090
3091 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3092   SDValue Cond = Op.getOperand(0);
3093   SDValue SelectTrue = Op.getOperand(1);
3094   SDValue SelectFalse = Op.getOperand(2);
3095   SDLoc dl(Op);
3096
3097   // Convert:
3098   //
3099   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3100   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3101   //
3102   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3103     const ConstantSDNode *CMOVTrue =
3104       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3105     const ConstantSDNode *CMOVFalse =
3106       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3107
3108     if (CMOVTrue && CMOVFalse) {
3109       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3110       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3111
3112       SDValue True;
3113       SDValue False;
3114       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3115         True = SelectTrue;
3116         False = SelectFalse;
3117       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3118         True = SelectFalse;
3119         False = SelectTrue;
3120       }
3121
3122       if (True.getNode() && False.getNode()) {
3123         EVT VT = Op.getValueType();
3124         SDValue ARMcc = Cond.getOperand(2);
3125         SDValue CCR = Cond.getOperand(3);
3126         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3127         assert(True.getValueType() == VT);
3128         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3129       }
3130     }
3131   }
3132
3133   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3134   // undefined bits before doing a full-word comparison with zero.
3135   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3136                      DAG.getConstant(1, Cond.getValueType()));
3137
3138   return DAG.getSelectCC(dl, Cond,
3139                          DAG.getConstant(0, Cond.getValueType()),
3140                          SelectTrue, SelectFalse, ISD::SETNE);
3141 }
3142
3143 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3144   EVT VT = Op.getValueType();
3145   SDValue LHS = Op.getOperand(0);
3146   SDValue RHS = Op.getOperand(1);
3147   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3148   SDValue TrueVal = Op.getOperand(2);
3149   SDValue FalseVal = Op.getOperand(3);
3150   SDLoc dl(Op);
3151
3152   if (LHS.getValueType() == MVT::i32) {
3153     SDValue ARMcc;
3154     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3155     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3156     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3157   }
3158
3159   ARMCC::CondCodes CondCode, CondCode2;
3160   FPCCToARMCC(CC, CondCode, CondCode2);
3161
3162   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3163   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3164   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3165   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3166                                ARMcc, CCR, Cmp);
3167   if (CondCode2 != ARMCC::AL) {
3168     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3169     // FIXME: Needs another CMP because flag can have but one use.
3170     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3171     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3172                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3173   }
3174   return Result;
3175 }
3176
3177 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3178 /// to morph to an integer compare sequence.
3179 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3180                            const ARMSubtarget *Subtarget) {
3181   SDNode *N = Op.getNode();
3182   if (!N->hasOneUse())
3183     // Otherwise it requires moving the value from fp to integer registers.
3184     return false;
3185   if (!N->getNumValues())
3186     return false;
3187   EVT VT = Op.getValueType();
3188   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3189     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3190     // vmrs are very slow, e.g. cortex-a8.
3191     return false;
3192
3193   if (isFloatingPointZero(Op)) {
3194     SeenZero = true;
3195     return true;
3196   }
3197   return ISD::isNormalLoad(N);
3198 }
3199
3200 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3201   if (isFloatingPointZero(Op))
3202     return DAG.getConstant(0, MVT::i32);
3203
3204   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3205     return DAG.getLoad(MVT::i32, SDLoc(Op),
3206                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3207                        Ld->isVolatile(), Ld->isNonTemporal(),
3208                        Ld->isInvariant(), Ld->getAlignment());
3209
3210   llvm_unreachable("Unknown VFP cmp argument!");
3211 }
3212
3213 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3214                            SDValue &RetVal1, SDValue &RetVal2) {
3215   if (isFloatingPointZero(Op)) {
3216     RetVal1 = DAG.getConstant(0, MVT::i32);
3217     RetVal2 = DAG.getConstant(0, MVT::i32);
3218     return;
3219   }
3220
3221   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3222     SDValue Ptr = Ld->getBasePtr();
3223     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3224                           Ld->getChain(), Ptr,
3225                           Ld->getPointerInfo(),
3226                           Ld->isVolatile(), Ld->isNonTemporal(),
3227                           Ld->isInvariant(), Ld->getAlignment());
3228
3229     EVT PtrType = Ptr.getValueType();
3230     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3231     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3232                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3233     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3234                           Ld->getChain(), NewPtr,
3235                           Ld->getPointerInfo().getWithOffset(4),
3236                           Ld->isVolatile(), Ld->isNonTemporal(),
3237                           Ld->isInvariant(), NewAlign);
3238     return;
3239   }
3240
3241   llvm_unreachable("Unknown VFP cmp argument!");
3242 }
3243
3244 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3245 /// f32 and even f64 comparisons to integer ones.
3246 SDValue
3247 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3248   SDValue Chain = Op.getOperand(0);
3249   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3250   SDValue LHS = Op.getOperand(2);
3251   SDValue RHS = Op.getOperand(3);
3252   SDValue Dest = Op.getOperand(4);
3253   SDLoc dl(Op);
3254
3255   bool LHSSeenZero = false;
3256   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3257   bool RHSSeenZero = false;
3258   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3259   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3260     // If unsafe fp math optimization is enabled and there are no other uses of
3261     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3262     // to an integer comparison.
3263     if (CC == ISD::SETOEQ)
3264       CC = ISD::SETEQ;
3265     else if (CC == ISD::SETUNE)
3266       CC = ISD::SETNE;
3267
3268     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3269     SDValue ARMcc;
3270     if (LHS.getValueType() == MVT::f32) {
3271       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3272                         bitcastf32Toi32(LHS, DAG), Mask);
3273       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3274                         bitcastf32Toi32(RHS, DAG), Mask);
3275       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3276       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3277       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3278                          Chain, Dest, ARMcc, CCR, Cmp);
3279     }
3280
3281     SDValue LHS1, LHS2;
3282     SDValue RHS1, RHS2;
3283     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3284     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3285     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3286     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3287     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3288     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3289     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3290     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3291     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3292   }
3293
3294   return SDValue();
3295 }
3296
3297 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3298   SDValue Chain = Op.getOperand(0);
3299   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3300   SDValue LHS = Op.getOperand(2);
3301   SDValue RHS = Op.getOperand(3);
3302   SDValue Dest = Op.getOperand(4);
3303   SDLoc dl(Op);
3304
3305   if (LHS.getValueType() == MVT::i32) {
3306     SDValue ARMcc;
3307     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3308     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3309     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3310                        Chain, Dest, ARMcc, CCR, Cmp);
3311   }
3312
3313   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3314
3315   if (getTargetMachine().Options.UnsafeFPMath &&
3316       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3317        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3318     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3319     if (Result.getNode())
3320       return Result;
3321   }
3322
3323   ARMCC::CondCodes CondCode, CondCode2;
3324   FPCCToARMCC(CC, CondCode, CondCode2);
3325
3326   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3327   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3328   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3329   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3330   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3331   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3332   if (CondCode2 != ARMCC::AL) {
3333     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3334     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3335     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3336   }
3337   return Res;
3338 }
3339
3340 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3341   SDValue Chain = Op.getOperand(0);
3342   SDValue Table = Op.getOperand(1);
3343   SDValue Index = Op.getOperand(2);
3344   SDLoc dl(Op);
3345
3346   EVT PTy = getPointerTy();
3347   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3348   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3349   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3350   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3351   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3352   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3353   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3354   if (Subtarget->isThumb2()) {
3355     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3356     // which does another jump to the destination. This also makes it easier
3357     // to translate it to TBB / TBH later.
3358     // FIXME: This might not work if the function is extremely large.
3359     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3360                        Addr, Op.getOperand(2), JTI, UId);
3361   }
3362   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3363     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3364                        MachinePointerInfo::getJumpTable(),
3365                        false, false, false, 0);
3366     Chain = Addr.getValue(1);
3367     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3368     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3369   } else {
3370     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3371                        MachinePointerInfo::getJumpTable(),
3372                        false, false, false, 0);
3373     Chain = Addr.getValue(1);
3374     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3375   }
3376 }
3377
3378 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3379   EVT VT = Op.getValueType();
3380   SDLoc dl(Op);
3381
3382   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3383     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3384       return Op;
3385     return DAG.UnrollVectorOp(Op.getNode());
3386   }
3387
3388   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3389          "Invalid type for custom lowering!");
3390   if (VT != MVT::v4i16)
3391     return DAG.UnrollVectorOp(Op.getNode());
3392
3393   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3394   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3395 }
3396
3397 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3398   EVT VT = Op.getValueType();
3399   if (VT.isVector())
3400     return LowerVectorFP_TO_INT(Op, DAG);
3401
3402   SDLoc dl(Op);
3403   unsigned Opc;
3404
3405   switch (Op.getOpcode()) {
3406   default: llvm_unreachable("Invalid opcode!");
3407   case ISD::FP_TO_SINT:
3408     Opc = ARMISD::FTOSI;
3409     break;
3410   case ISD::FP_TO_UINT:
3411     Opc = ARMISD::FTOUI;
3412     break;
3413   }
3414   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3415   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3416 }
3417
3418 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3419   EVT VT = Op.getValueType();
3420   SDLoc dl(Op);
3421
3422   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3423     if (VT.getVectorElementType() == MVT::f32)
3424       return Op;
3425     return DAG.UnrollVectorOp(Op.getNode());
3426   }
3427
3428   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3429          "Invalid type for custom lowering!");
3430   if (VT != MVT::v4f32)
3431     return DAG.UnrollVectorOp(Op.getNode());
3432
3433   unsigned CastOpc;
3434   unsigned Opc;
3435   switch (Op.getOpcode()) {
3436   default: llvm_unreachable("Invalid opcode!");
3437   case ISD::SINT_TO_FP:
3438     CastOpc = ISD::SIGN_EXTEND;
3439     Opc = ISD::SINT_TO_FP;
3440     break;
3441   case ISD::UINT_TO_FP:
3442     CastOpc = ISD::ZERO_EXTEND;
3443     Opc = ISD::UINT_TO_FP;
3444     break;
3445   }
3446
3447   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3448   return DAG.getNode(Opc, dl, VT, Op);
3449 }
3450
3451 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3452   EVT VT = Op.getValueType();
3453   if (VT.isVector())
3454     return LowerVectorINT_TO_FP(Op, DAG);
3455
3456   SDLoc dl(Op);
3457   unsigned Opc;
3458
3459   switch (Op.getOpcode()) {
3460   default: llvm_unreachable("Invalid opcode!");
3461   case ISD::SINT_TO_FP:
3462     Opc = ARMISD::SITOF;
3463     break;
3464   case ISD::UINT_TO_FP:
3465     Opc = ARMISD::UITOF;
3466     break;
3467   }
3468
3469   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3470   return DAG.getNode(Opc, dl, VT, Op);
3471 }
3472
3473 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3474   // Implement fcopysign with a fabs and a conditional fneg.
3475   SDValue Tmp0 = Op.getOperand(0);
3476   SDValue Tmp1 = Op.getOperand(1);
3477   SDLoc dl(Op);
3478   EVT VT = Op.getValueType();
3479   EVT SrcVT = Tmp1.getValueType();
3480   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3481     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3482   bool UseNEON = !InGPR && Subtarget->hasNEON();
3483
3484   if (UseNEON) {
3485     // Use VBSL to copy the sign bit.
3486     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3487     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3488                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3489     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3490     if (VT == MVT::f64)
3491       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3492                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3493                          DAG.getConstant(32, MVT::i32));
3494     else /*if (VT == MVT::f32)*/
3495       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3496     if (SrcVT == MVT::f32) {
3497       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3498       if (VT == MVT::f64)
3499         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3500                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3501                            DAG.getConstant(32, MVT::i32));
3502     } else if (VT == MVT::f32)
3503       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3504                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3505                          DAG.getConstant(32, MVT::i32));
3506     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3507     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3508
3509     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3510                                             MVT::i32);
3511     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3512     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3513                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3514
3515     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3516                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3517                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3518     if (VT == MVT::f32) {
3519       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3520       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3521                         DAG.getConstant(0, MVT::i32));
3522     } else {
3523       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3524     }
3525
3526     return Res;
3527   }
3528
3529   // Bitcast operand 1 to i32.
3530   if (SrcVT == MVT::f64)
3531     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3532                        &Tmp1, 1).getValue(1);
3533   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3534
3535   // Or in the signbit with integer operations.
3536   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3537   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3538   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3539   if (VT == MVT::f32) {
3540     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3541                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3542     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3543                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3544   }
3545
3546   // f64: Or the high part with signbit and then combine two parts.
3547   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3548                      &Tmp0, 1);
3549   SDValue Lo = Tmp0.getValue(0);
3550   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3551   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3552   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3553 }
3554
3555 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3556   MachineFunction &MF = DAG.getMachineFunction();
3557   MachineFrameInfo *MFI = MF.getFrameInfo();
3558   MFI->setReturnAddressIsTaken(true);
3559
3560   EVT VT = Op.getValueType();
3561   SDLoc dl(Op);
3562   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3563   if (Depth) {
3564     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3565     SDValue Offset = DAG.getConstant(4, MVT::i32);
3566     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3567                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3568                        MachinePointerInfo(), false, false, false, 0);
3569   }
3570
3571   // Return LR, which contains the return address. Mark it an implicit live-in.
3572   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3573   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3574 }
3575
3576 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3577   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3578   MFI->setFrameAddressIsTaken(true);
3579
3580   EVT VT = Op.getValueType();
3581   SDLoc dl(Op);  // FIXME probably not meaningful
3582   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3583   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3584     ? ARM::R7 : ARM::R11;
3585   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3586   while (Depth--)
3587     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3588                             MachinePointerInfo(),
3589                             false, false, false, 0);
3590   return FrameAddr;
3591 }
3592
3593 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3594 /// and size(DestVec) > 128-bits.
3595 /// This is achieved by doing the one extension from the SrcVec, splitting the
3596 /// result, extending these parts, and then concatenating these into the
3597 /// destination.
3598 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3599   SDValue Op = N->getOperand(0);
3600   EVT SrcVT = Op.getValueType();
3601   EVT DestVT = N->getValueType(0);
3602
3603   assert(DestVT.getSizeInBits() > 128 &&
3604          "Custom sext/zext expansion needs >128-bit vector.");
3605   // If this is a normal length extension, use the default expansion.
3606   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3607       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3608     return SDValue();
3609
3610   SDLoc dl(N);
3611   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3612   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3613   unsigned NumElts = SrcVT.getVectorNumElements();
3614   LLVMContext &Ctx = *DAG.getContext();
3615   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3616
3617   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3618                                NumElts);
3619   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3620                                  NumElts/2);
3621   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3622                                NumElts/2);
3623
3624   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3625   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3626                         DAG.getIntPtrConstant(0));
3627   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3628                         DAG.getIntPtrConstant(NumElts/2));
3629   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3630   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3631   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3632 }
3633
3634 /// ExpandBITCAST - If the target supports VFP, this function is called to
3635 /// expand a bit convert where either the source or destination type is i64 to
3636 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3637 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3638 /// vectors), since the legalizer won't know what to do with that.
3639 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3641   SDLoc dl(N);
3642   SDValue Op = N->getOperand(0);
3643
3644   // This function is only supposed to be called for i64 types, either as the
3645   // source or destination of the bit convert.
3646   EVT SrcVT = Op.getValueType();
3647   EVT DstVT = N->getValueType(0);
3648   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3649          "ExpandBITCAST called for non-i64 type");
3650
3651   // Turn i64->f64 into VMOVDRR.
3652   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3653     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3654                              DAG.getConstant(0, MVT::i32));
3655     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3656                              DAG.getConstant(1, MVT::i32));
3657     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3658                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3659   }
3660
3661   // Turn f64->i64 into VMOVRRD.
3662   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3663     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3664                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3665     // Merge the pieces into a single i64 value.
3666     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3667   }
3668
3669   return SDValue();
3670 }
3671
3672 /// getZeroVector - Returns a vector of specified type with all zero elements.
3673 /// Zero vectors are used to represent vector negation and in those cases
3674 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3675 /// not support i64 elements, so sometimes the zero vectors will need to be
3676 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3677 /// zero vector.
3678 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3679   assert(VT.isVector() && "Expected a vector type");
3680   // The canonical modified immediate encoding of a zero vector is....0!
3681   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3682   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3683   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3684   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3685 }
3686
3687 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3688 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3689 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3690                                                 SelectionDAG &DAG) const {
3691   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3692   EVT VT = Op.getValueType();
3693   unsigned VTBits = VT.getSizeInBits();
3694   SDLoc dl(Op);
3695   SDValue ShOpLo = Op.getOperand(0);
3696   SDValue ShOpHi = Op.getOperand(1);
3697   SDValue ShAmt  = Op.getOperand(2);
3698   SDValue ARMcc;
3699   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3700
3701   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3702
3703   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3704                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3705   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3706   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3707                                    DAG.getConstant(VTBits, MVT::i32));
3708   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3709   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3710   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3711
3712   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3713   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3714                           ARMcc, DAG, dl);
3715   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3716   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3717                            CCR, Cmp);
3718
3719   SDValue Ops[2] = { Lo, Hi };
3720   return DAG.getMergeValues(Ops, 2, dl);
3721 }
3722
3723 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3724 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3725 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3726                                                SelectionDAG &DAG) const {
3727   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3728   EVT VT = Op.getValueType();
3729   unsigned VTBits = VT.getSizeInBits();
3730   SDLoc dl(Op);
3731   SDValue ShOpLo = Op.getOperand(0);
3732   SDValue ShOpHi = Op.getOperand(1);
3733   SDValue ShAmt  = Op.getOperand(2);
3734   SDValue ARMcc;
3735
3736   assert(Op.getOpcode() == ISD::SHL_PARTS);
3737   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3738                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3739   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3740   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3741                                    DAG.getConstant(VTBits, MVT::i32));
3742   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3743   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3744
3745   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3746   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3747   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3748                           ARMcc, DAG, dl);
3749   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3750   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3751                            CCR, Cmp);
3752
3753   SDValue Ops[2] = { Lo, Hi };
3754   return DAG.getMergeValues(Ops, 2, dl);
3755 }
3756
3757 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3758                                             SelectionDAG &DAG) const {
3759   // The rounding mode is in bits 23:22 of the FPSCR.
3760   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3761   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3762   // so that the shift + and get folded into a bitfield extract.
3763   SDLoc dl(Op);
3764   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3765                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3766                                               MVT::i32));
3767   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3768                                   DAG.getConstant(1U << 22, MVT::i32));
3769   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3770                               DAG.getConstant(22, MVT::i32));
3771   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3772                      DAG.getConstant(3, MVT::i32));
3773 }
3774
3775 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3776                          const ARMSubtarget *ST) {
3777   EVT VT = N->getValueType(0);
3778   SDLoc dl(N);
3779
3780   if (!ST->hasV6T2Ops())
3781     return SDValue();
3782
3783   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3784   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3785 }
3786
3787 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3788 /// for each 16-bit element from operand, repeated.  The basic idea is to
3789 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3790 ///
3791 /// Trace for v4i16:
3792 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3793 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3794 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3795 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3796 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3797 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3798 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3799 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3800 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3801   EVT VT = N->getValueType(0);
3802   SDLoc DL(N);
3803
3804   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3805   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3806   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3807   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3808   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3809   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3810 }
3811
3812 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3813 /// bit-count for each 16-bit element from the operand.  We need slightly
3814 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3815 /// 64/128-bit registers.
3816 ///
3817 /// Trace for v4i16:
3818 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3819 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3820 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3821 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3822 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3823   EVT VT = N->getValueType(0);
3824   SDLoc DL(N);
3825
3826   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3827   if (VT.is64BitVector()) {
3828     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3829     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3830                        DAG.getIntPtrConstant(0));
3831   } else {
3832     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3833                                     BitCounts, DAG.getIntPtrConstant(0));
3834     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3835   }
3836 }
3837
3838 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3839 /// bit-count for each 32-bit element from the operand.  The idea here is
3840 /// to split the vector into 16-bit elements, leverage the 16-bit count
3841 /// routine, and then combine the results.
3842 ///
3843 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3844 /// input    = [v0    v1    ] (vi: 32-bit elements)
3845 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3846 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3847 /// vrev: N0 = [k1 k0 k3 k2 ]
3848 ///            [k0 k1 k2 k3 ]
3849 ///       N1 =+[k1 k0 k3 k2 ]
3850 ///            [k0 k2 k1 k3 ]
3851 ///       N2 =+[k1 k3 k0 k2 ]
3852 ///            [k0    k2    k1    k3    ]
3853 /// Extended =+[k1    k3    k0    k2    ]
3854 ///            [k0    k2    ]
3855 /// Extracted=+[k1    k3    ]
3856 ///
3857 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3858   EVT VT = N->getValueType(0);
3859   SDLoc DL(N);
3860
3861   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3862
3863   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3864   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3865   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3866   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3867   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3868
3869   if (VT.is64BitVector()) {
3870     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3871     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3872                        DAG.getIntPtrConstant(0));
3873   } else {
3874     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3875                                     DAG.getIntPtrConstant(0));
3876     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3877   }
3878 }
3879
3880 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3881                           const ARMSubtarget *ST) {
3882   EVT VT = N->getValueType(0);
3883
3884   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3885   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3886           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3887          "Unexpected type for custom ctpop lowering");
3888
3889   if (VT.getVectorElementType() == MVT::i32)
3890     return lowerCTPOP32BitElements(N, DAG);
3891   else
3892     return lowerCTPOP16BitElements(N, DAG);
3893 }
3894
3895 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3896                           const ARMSubtarget *ST) {
3897   EVT VT = N->getValueType(0);
3898   SDLoc dl(N);
3899
3900   if (!VT.isVector())
3901     return SDValue();
3902
3903   // Lower vector shifts on NEON to use VSHL.
3904   assert(ST->hasNEON() && "unexpected vector shift");
3905
3906   // Left shifts translate directly to the vshiftu intrinsic.
3907   if (N->getOpcode() == ISD::SHL)
3908     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3909                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3910                        N->getOperand(0), N->getOperand(1));
3911
3912   assert((N->getOpcode() == ISD::SRA ||
3913           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3914
3915   // NEON uses the same intrinsics for both left and right shifts.  For
3916   // right shifts, the shift amounts are negative, so negate the vector of
3917   // shift amounts.
3918   EVT ShiftVT = N->getOperand(1).getValueType();
3919   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3920                                      getZeroVector(ShiftVT, DAG, dl),
3921                                      N->getOperand(1));
3922   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3923                              Intrinsic::arm_neon_vshifts :
3924                              Intrinsic::arm_neon_vshiftu);
3925   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3926                      DAG.getConstant(vshiftInt, MVT::i32),
3927                      N->getOperand(0), NegatedCount);
3928 }
3929
3930 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3931                                 const ARMSubtarget *ST) {
3932   EVT VT = N->getValueType(0);
3933   SDLoc dl(N);
3934
3935   // We can get here for a node like i32 = ISD::SHL i32, i64
3936   if (VT != MVT::i64)
3937     return SDValue();
3938
3939   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3940          "Unknown shift to lower!");
3941
3942   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3943   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3944       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3945     return SDValue();
3946
3947   // If we are in thumb mode, we don't have RRX.
3948   if (ST->isThumb1Only()) return SDValue();
3949
3950   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3951   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3952                            DAG.getConstant(0, MVT::i32));
3953   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3954                            DAG.getConstant(1, MVT::i32));
3955
3956   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3957   // captures the result into a carry flag.
3958   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3959   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3960
3961   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3962   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3963
3964   // Merge the pieces into a single i64 value.
3965  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3966 }
3967
3968 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3969   SDValue TmpOp0, TmpOp1;
3970   bool Invert = false;
3971   bool Swap = false;
3972   unsigned Opc = 0;
3973
3974   SDValue Op0 = Op.getOperand(0);
3975   SDValue Op1 = Op.getOperand(1);
3976   SDValue CC = Op.getOperand(2);
3977   EVT VT = Op.getValueType();
3978   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3979   SDLoc dl(Op);
3980
3981   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3982     switch (SetCCOpcode) {
3983     default: llvm_unreachable("Illegal FP comparison");
3984     case ISD::SETUNE:
3985     case ISD::SETNE:  Invert = true; // Fallthrough
3986     case ISD::SETOEQ:
3987     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3988     case ISD::SETOLT:
3989     case ISD::SETLT: Swap = true; // Fallthrough
3990     case ISD::SETOGT:
3991     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3992     case ISD::SETOLE:
3993     case ISD::SETLE:  Swap = true; // Fallthrough
3994     case ISD::SETOGE:
3995     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3996     case ISD::SETUGE: Swap = true; // Fallthrough
3997     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3998     case ISD::SETUGT: Swap = true; // Fallthrough
3999     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4000     case ISD::SETUEQ: Invert = true; // Fallthrough
4001     case ISD::SETONE:
4002       // Expand this to (OLT | OGT).
4003       TmpOp0 = Op0;
4004       TmpOp1 = Op1;
4005       Opc = ISD::OR;
4006       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4007       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4008       break;
4009     case ISD::SETUO: Invert = true; // Fallthrough
4010     case ISD::SETO:
4011       // Expand this to (OLT | OGE).
4012       TmpOp0 = Op0;
4013       TmpOp1 = Op1;
4014       Opc = ISD::OR;
4015       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4016       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4017       break;
4018     }
4019   } else {
4020     // Integer comparisons.
4021     switch (SetCCOpcode) {
4022     default: llvm_unreachable("Illegal integer comparison");
4023     case ISD::SETNE:  Invert = true;
4024     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4025     case ISD::SETLT:  Swap = true;
4026     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4027     case ISD::SETLE:  Swap = true;
4028     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4029     case ISD::SETULT: Swap = true;
4030     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4031     case ISD::SETULE: Swap = true;
4032     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4033     }
4034
4035     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4036     if (Opc == ARMISD::VCEQ) {
4037
4038       SDValue AndOp;
4039       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4040         AndOp = Op0;
4041       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4042         AndOp = Op1;
4043
4044       // Ignore bitconvert.
4045       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4046         AndOp = AndOp.getOperand(0);
4047
4048       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4049         Opc = ARMISD::VTST;
4050         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4051         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4052         Invert = !Invert;
4053       }
4054     }
4055   }
4056
4057   if (Swap)
4058     std::swap(Op0, Op1);
4059
4060   // If one of the operands is a constant vector zero, attempt to fold the
4061   // comparison to a specialized compare-against-zero form.
4062   SDValue SingleOp;
4063   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4064     SingleOp = Op0;
4065   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4066     if (Opc == ARMISD::VCGE)
4067       Opc = ARMISD::VCLEZ;
4068     else if (Opc == ARMISD::VCGT)
4069       Opc = ARMISD::VCLTZ;
4070     SingleOp = Op1;
4071   }
4072
4073   SDValue Result;
4074   if (SingleOp.getNode()) {
4075     switch (Opc) {
4076     case ARMISD::VCEQ:
4077       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4078     case ARMISD::VCGE:
4079       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4080     case ARMISD::VCLEZ:
4081       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4082     case ARMISD::VCGT:
4083       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4084     case ARMISD::VCLTZ:
4085       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4086     default:
4087       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4088     }
4089   } else {
4090      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4091   }
4092
4093   if (Invert)
4094     Result = DAG.getNOT(dl, Result, VT);
4095
4096   return Result;
4097 }
4098
4099 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4100 /// valid vector constant for a NEON instruction with a "modified immediate"
4101 /// operand (e.g., VMOV).  If so, return the encoded value.
4102 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4103                                  unsigned SplatBitSize, SelectionDAG &DAG,
4104                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4105   unsigned OpCmode, Imm;
4106
4107   // SplatBitSize is set to the smallest size that splats the vector, so a
4108   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4109   // immediate instructions others than VMOV do not support the 8-bit encoding
4110   // of a zero vector, and the default encoding of zero is supposed to be the
4111   // 32-bit version.
4112   if (SplatBits == 0)
4113     SplatBitSize = 32;
4114
4115   switch (SplatBitSize) {
4116   case 8:
4117     if (type != VMOVModImm)
4118       return SDValue();
4119     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4120     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4121     OpCmode = 0xe;
4122     Imm = SplatBits;
4123     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4124     break;
4125
4126   case 16:
4127     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4128     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4129     if ((SplatBits & ~0xff) == 0) {
4130       // Value = 0x00nn: Op=x, Cmode=100x.
4131       OpCmode = 0x8;
4132       Imm = SplatBits;
4133       break;
4134     }
4135     if ((SplatBits & ~0xff00) == 0) {
4136       // Value = 0xnn00: Op=x, Cmode=101x.
4137       OpCmode = 0xa;
4138       Imm = SplatBits >> 8;
4139       break;
4140     }
4141     return SDValue();
4142
4143   case 32:
4144     // NEON's 32-bit VMOV supports splat values where:
4145     // * only one byte is nonzero, or
4146     // * the least significant byte is 0xff and the second byte is nonzero, or
4147     // * the least significant 2 bytes are 0xff and the third is nonzero.
4148     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4149     if ((SplatBits & ~0xff) == 0) {
4150       // Value = 0x000000nn: Op=x, Cmode=000x.
4151       OpCmode = 0;
4152       Imm = SplatBits;
4153       break;
4154     }
4155     if ((SplatBits & ~0xff00) == 0) {
4156       // Value = 0x0000nn00: Op=x, Cmode=001x.
4157       OpCmode = 0x2;
4158       Imm = SplatBits >> 8;
4159       break;
4160     }
4161     if ((SplatBits & ~0xff0000) == 0) {
4162       // Value = 0x00nn0000: Op=x, Cmode=010x.
4163       OpCmode = 0x4;
4164       Imm = SplatBits >> 16;
4165       break;
4166     }
4167     if ((SplatBits & ~0xff000000) == 0) {
4168       // Value = 0xnn000000: Op=x, Cmode=011x.
4169       OpCmode = 0x6;
4170       Imm = SplatBits >> 24;
4171       break;
4172     }
4173
4174     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4175     if (type == OtherModImm) return SDValue();
4176
4177     if ((SplatBits & ~0xffff) == 0 &&
4178         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4179       // Value = 0x0000nnff: Op=x, Cmode=1100.
4180       OpCmode = 0xc;
4181       Imm = SplatBits >> 8;
4182       SplatBits |= 0xff;
4183       break;
4184     }
4185
4186     if ((SplatBits & ~0xffffff) == 0 &&
4187         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4188       // Value = 0x00nnffff: Op=x, Cmode=1101.
4189       OpCmode = 0xd;
4190       Imm = SplatBits >> 16;
4191       SplatBits |= 0xffff;
4192       break;
4193     }
4194
4195     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4196     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4197     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4198     // and fall through here to test for a valid 64-bit splat.  But, then the
4199     // caller would also need to check and handle the change in size.
4200     return SDValue();
4201
4202   case 64: {
4203     if (type != VMOVModImm)
4204       return SDValue();
4205     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4206     uint64_t BitMask = 0xff;
4207     uint64_t Val = 0;
4208     unsigned ImmMask = 1;
4209     Imm = 0;
4210     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4211       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4212         Val |= BitMask;
4213         Imm |= ImmMask;
4214       } else if ((SplatBits & BitMask) != 0) {
4215         return SDValue();
4216       }
4217       BitMask <<= 8;
4218       ImmMask <<= 1;
4219     }
4220     // Op=1, Cmode=1110.
4221     OpCmode = 0x1e;
4222     SplatBits = Val;
4223     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4224     break;
4225   }
4226
4227   default:
4228     llvm_unreachable("unexpected size for isNEONModifiedImm");
4229   }
4230
4231   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4232   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4233 }
4234
4235 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4236                                            const ARMSubtarget *ST) const {
4237   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4238     return SDValue();
4239
4240   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4241   assert(Op.getValueType() == MVT::f32 &&
4242          "ConstantFP custom lowering should only occur for f32.");
4243
4244   // Try splatting with a VMOV.f32...
4245   APFloat FPVal = CFP->getValueAPF();
4246   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4247   if (ImmVal != -1) {
4248     SDLoc DL(Op);
4249     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4250     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4251                                       NewVal);
4252     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4253                        DAG.getConstant(0, MVT::i32));
4254   }
4255
4256   // If that fails, try a VMOV.i32
4257   EVT VMovVT;
4258   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4259   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4260                                      VMOVModImm);
4261   if (NewVal != SDValue()) {
4262     SDLoc DL(Op);
4263     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4264                                       NewVal);
4265     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4266                                        VecConstant);
4267     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4268                        DAG.getConstant(0, MVT::i32));
4269   }
4270
4271   // Finally, try a VMVN.i32
4272   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4273                              VMVNModImm);
4274   if (NewVal != SDValue()) {
4275     SDLoc DL(Op);
4276     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4277     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4278                                        VecConstant);
4279     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4280                        DAG.getConstant(0, MVT::i32));
4281   }
4282
4283   return SDValue();
4284 }
4285
4286 // check if an VEXT instruction can handle the shuffle mask when the
4287 // vector sources of the shuffle are the same.
4288 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4289   unsigned NumElts = VT.getVectorNumElements();
4290
4291   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4292   if (M[0] < 0)
4293     return false;
4294
4295   Imm = M[0];
4296
4297   // If this is a VEXT shuffle, the immediate value is the index of the first
4298   // element.  The other shuffle indices must be the successive elements after
4299   // the first one.
4300   unsigned ExpectedElt = Imm;
4301   for (unsigned i = 1; i < NumElts; ++i) {
4302     // Increment the expected index.  If it wraps around, just follow it
4303     // back to index zero and keep going.
4304     ++ExpectedElt;
4305     if (ExpectedElt == NumElts)
4306       ExpectedElt = 0;
4307
4308     if (M[i] < 0) continue; // ignore UNDEF indices
4309     if (ExpectedElt != static_cast<unsigned>(M[i]))
4310       return false;
4311   }
4312
4313   return true;
4314 }
4315
4316
4317 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4318                        bool &ReverseVEXT, unsigned &Imm) {
4319   unsigned NumElts = VT.getVectorNumElements();
4320   ReverseVEXT = false;
4321
4322   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4323   if (M[0] < 0)
4324     return false;
4325
4326   Imm = M[0];
4327
4328   // If this is a VEXT shuffle, the immediate value is the index of the first
4329   // element.  The other shuffle indices must be the successive elements after
4330   // the first one.
4331   unsigned ExpectedElt = Imm;
4332   for (unsigned i = 1; i < NumElts; ++i) {
4333     // Increment the expected index.  If it wraps around, it may still be
4334     // a VEXT but the source vectors must be swapped.
4335     ExpectedElt += 1;
4336     if (ExpectedElt == NumElts * 2) {
4337       ExpectedElt = 0;
4338       ReverseVEXT = true;
4339     }
4340
4341     if (M[i] < 0) continue; // ignore UNDEF indices
4342     if (ExpectedElt != static_cast<unsigned>(M[i]))
4343       return false;
4344   }
4345
4346   // Adjust the index value if the source operands will be swapped.
4347   if (ReverseVEXT)
4348     Imm -= NumElts;
4349
4350   return true;
4351 }
4352
4353 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4354 /// instruction with the specified blocksize.  (The order of the elements
4355 /// within each block of the vector is reversed.)
4356 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4357   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4358          "Only possible block sizes for VREV are: 16, 32, 64");
4359
4360   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4361   if (EltSz == 64)
4362     return false;
4363
4364   unsigned NumElts = VT.getVectorNumElements();
4365   unsigned BlockElts = M[0] + 1;
4366   // If the first shuffle index is UNDEF, be optimistic.
4367   if (M[0] < 0)
4368     BlockElts = BlockSize / EltSz;
4369
4370   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4371     return false;
4372
4373   for (unsigned i = 0; i < NumElts; ++i) {
4374     if (M[i] < 0) continue; // ignore UNDEF indices
4375     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4376       return false;
4377   }
4378
4379   return true;
4380 }
4381
4382 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4383   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4384   // range, then 0 is placed into the resulting vector. So pretty much any mask
4385   // of 8 elements can work here.
4386   return VT == MVT::v8i8 && M.size() == 8;
4387 }
4388
4389 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4390   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4391   if (EltSz == 64)
4392     return false;
4393
4394   unsigned NumElts = VT.getVectorNumElements();
4395   WhichResult = (M[0] == 0 ? 0 : 1);
4396   for (unsigned i = 0; i < NumElts; i += 2) {
4397     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4398         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4399       return false;
4400   }
4401   return true;
4402 }
4403
4404 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4405 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4406 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4407 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4408   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4409   if (EltSz == 64)
4410     return false;
4411
4412   unsigned NumElts = VT.getVectorNumElements();
4413   WhichResult = (M[0] == 0 ? 0 : 1);
4414   for (unsigned i = 0; i < NumElts; i += 2) {
4415     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4416         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4417       return false;
4418   }
4419   return true;
4420 }
4421
4422 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4423   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4424   if (EltSz == 64)
4425     return false;
4426
4427   unsigned NumElts = VT.getVectorNumElements();
4428   WhichResult = (M[0] == 0 ? 0 : 1);
4429   for (unsigned i = 0; i != NumElts; ++i) {
4430     if (M[i] < 0) continue; // ignore UNDEF indices
4431     if ((unsigned) M[i] != 2 * i + WhichResult)
4432       return false;
4433   }
4434
4435   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4436   if (VT.is64BitVector() && EltSz == 32)
4437     return false;
4438
4439   return true;
4440 }
4441
4442 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4443 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4444 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4445 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4446   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4447   if (EltSz == 64)
4448     return false;
4449
4450   unsigned Half = VT.getVectorNumElements() / 2;
4451   WhichResult = (M[0] == 0 ? 0 : 1);
4452   for (unsigned j = 0; j != 2; ++j) {
4453     unsigned Idx = WhichResult;
4454     for (unsigned i = 0; i != Half; ++i) {
4455       int MIdx = M[i + j * Half];
4456       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4457         return false;
4458       Idx += 2;
4459     }
4460   }
4461
4462   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4463   if (VT.is64BitVector() && EltSz == 32)
4464     return false;
4465
4466   return true;
4467 }
4468
4469 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4470   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4471   if (EltSz == 64)
4472     return false;
4473
4474   unsigned NumElts = VT.getVectorNumElements();
4475   WhichResult = (M[0] == 0 ? 0 : 1);
4476   unsigned Idx = WhichResult * NumElts / 2;
4477   for (unsigned i = 0; i != NumElts; i += 2) {
4478     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4479         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4480       return false;
4481     Idx += 1;
4482   }
4483
4484   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4485   if (VT.is64BitVector() && EltSz == 32)
4486     return false;
4487
4488   return true;
4489 }
4490
4491 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4492 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4493 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4494 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4495   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4496   if (EltSz == 64)
4497     return false;
4498
4499   unsigned NumElts = VT.getVectorNumElements();
4500   WhichResult = (M[0] == 0 ? 0 : 1);
4501   unsigned Idx = WhichResult * NumElts / 2;
4502   for (unsigned i = 0; i != NumElts; i += 2) {
4503     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4504         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4505       return false;
4506     Idx += 1;
4507   }
4508
4509   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4510   if (VT.is64BitVector() && EltSz == 32)
4511     return false;
4512
4513   return true;
4514 }
4515
4516 /// \return true if this is a reverse operation on an vector.
4517 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4518   unsigned NumElts = VT.getVectorNumElements();
4519   // Make sure the mask has the right size.
4520   if (NumElts != M.size())
4521       return false;
4522
4523   // Look for <15, ..., 3, -1, 1, 0>.
4524   for (unsigned i = 0; i != NumElts; ++i)
4525     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4526       return false;
4527
4528   return true;
4529 }
4530
4531 // If N is an integer constant that can be moved into a register in one
4532 // instruction, return an SDValue of such a constant (will become a MOV
4533 // instruction).  Otherwise return null.
4534 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4535                                      const ARMSubtarget *ST, SDLoc dl) {
4536   uint64_t Val;
4537   if (!isa<ConstantSDNode>(N))
4538     return SDValue();
4539   Val = cast<ConstantSDNode>(N)->getZExtValue();
4540
4541   if (ST->isThumb1Only()) {
4542     if (Val <= 255 || ~Val <= 255)
4543       return DAG.getConstant(Val, MVT::i32);
4544   } else {
4545     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4546       return DAG.getConstant(Val, MVT::i32);
4547   }
4548   return SDValue();
4549 }
4550
4551 // If this is a case we can't handle, return null and let the default
4552 // expansion code take care of it.
4553 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4554                                              const ARMSubtarget *ST) const {
4555   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4556   SDLoc dl(Op);
4557   EVT VT = Op.getValueType();
4558
4559   APInt SplatBits, SplatUndef;
4560   unsigned SplatBitSize;
4561   bool HasAnyUndefs;
4562   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4563     if (SplatBitSize <= 64) {
4564       // Check if an immediate VMOV works.
4565       EVT VmovVT;
4566       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4567                                       SplatUndef.getZExtValue(), SplatBitSize,
4568                                       DAG, VmovVT, VT.is128BitVector(),
4569                                       VMOVModImm);
4570       if (Val.getNode()) {
4571         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4572         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4573       }
4574
4575       // Try an immediate VMVN.
4576       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4577       Val = isNEONModifiedImm(NegatedImm,
4578                                       SplatUndef.getZExtValue(), SplatBitSize,
4579                                       DAG, VmovVT, VT.is128BitVector(),
4580                                       VMVNModImm);
4581       if (Val.getNode()) {
4582         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4583         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4584       }
4585
4586       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4587       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4588         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4589         if (ImmVal != -1) {
4590           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4591           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4592         }
4593       }
4594     }
4595   }
4596
4597   // Scan through the operands to see if only one value is used.
4598   //
4599   // As an optimisation, even if more than one value is used it may be more
4600   // profitable to splat with one value then change some lanes.
4601   //
4602   // Heuristically we decide to do this if the vector has a "dominant" value,
4603   // defined as splatted to more than half of the lanes.
4604   unsigned NumElts = VT.getVectorNumElements();
4605   bool isOnlyLowElement = true;
4606   bool usesOnlyOneValue = true;
4607   bool hasDominantValue = false;
4608   bool isConstant = true;
4609
4610   // Map of the number of times a particular SDValue appears in the
4611   // element list.
4612   DenseMap<SDValue, unsigned> ValueCounts;
4613   SDValue Value;
4614   for (unsigned i = 0; i < NumElts; ++i) {
4615     SDValue V = Op.getOperand(i);
4616     if (V.getOpcode() == ISD::UNDEF)
4617       continue;
4618     if (i > 0)
4619       isOnlyLowElement = false;
4620     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4621       isConstant = false;
4622
4623     ValueCounts.insert(std::make_pair(V, 0));
4624     unsigned &Count = ValueCounts[V];
4625
4626     // Is this value dominant? (takes up more than half of the lanes)
4627     if (++Count > (NumElts / 2)) {
4628       hasDominantValue = true;
4629       Value = V;
4630     }
4631   }
4632   if (ValueCounts.size() != 1)
4633     usesOnlyOneValue = false;
4634   if (!Value.getNode() && ValueCounts.size() > 0)
4635     Value = ValueCounts.begin()->first;
4636
4637   if (ValueCounts.size() == 0)
4638     return DAG.getUNDEF(VT);
4639
4640   if (isOnlyLowElement)
4641     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4642
4643   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4644
4645   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4646   // i32 and try again.
4647   if (hasDominantValue && EltSize <= 32) {
4648     if (!isConstant) {
4649       SDValue N;
4650
4651       // If we are VDUPing a value that comes directly from a vector, that will
4652       // cause an unnecessary move to and from a GPR, where instead we could
4653       // just use VDUPLANE. We can only do this if the lane being extracted
4654       // is at a constant index, as the VDUP from lane instructions only have
4655       // constant-index forms.
4656       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4657           isa<ConstantSDNode>(Value->getOperand(1))) {
4658         // We need to create a new undef vector to use for the VDUPLANE if the
4659         // size of the vector from which we get the value is different than the
4660         // size of the vector that we need to create. We will insert the element
4661         // such that the register coalescer will remove unnecessary copies.
4662         if (VT != Value->getOperand(0).getValueType()) {
4663           ConstantSDNode *constIndex;
4664           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4665           assert(constIndex && "The index is not a constant!");
4666           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4667                              VT.getVectorNumElements();
4668           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4669                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4670                         Value, DAG.getConstant(index, MVT::i32)),
4671                            DAG.getConstant(index, MVT::i32));
4672         } else
4673           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4674                         Value->getOperand(0), Value->getOperand(1));
4675       } else
4676         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4677
4678       if (!usesOnlyOneValue) {
4679         // The dominant value was splatted as 'N', but we now have to insert
4680         // all differing elements.
4681         for (unsigned I = 0; I < NumElts; ++I) {
4682           if (Op.getOperand(I) == Value)
4683             continue;
4684           SmallVector<SDValue, 3> Ops;
4685           Ops.push_back(N);
4686           Ops.push_back(Op.getOperand(I));
4687           Ops.push_back(DAG.getConstant(I, MVT::i32));
4688           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4689         }
4690       }
4691       return N;
4692     }
4693     if (VT.getVectorElementType().isFloatingPoint()) {
4694       SmallVector<SDValue, 8> Ops;
4695       for (unsigned i = 0; i < NumElts; ++i)
4696         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4697                                   Op.getOperand(i)));
4698       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4699       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4700       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4701       if (Val.getNode())
4702         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4703     }
4704     if (usesOnlyOneValue) {
4705       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4706       if (isConstant && Val.getNode())
4707         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4708     }
4709   }
4710
4711   // If all elements are constants and the case above didn't get hit, fall back
4712   // to the default expansion, which will generate a load from the constant
4713   // pool.
4714   if (isConstant)
4715     return SDValue();
4716
4717   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4718   if (NumElts >= 4) {
4719     SDValue shuffle = ReconstructShuffle(Op, DAG);
4720     if (shuffle != SDValue())
4721       return shuffle;
4722   }
4723
4724   // Vectors with 32- or 64-bit elements can be built by directly assigning
4725   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4726   // will be legalized.
4727   if (EltSize >= 32) {
4728     // Do the expansion with floating-point types, since that is what the VFP
4729     // registers are defined to use, and since i64 is not legal.
4730     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4731     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4732     SmallVector<SDValue, 8> Ops;
4733     for (unsigned i = 0; i < NumElts; ++i)
4734       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4735     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4736     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4737   }
4738
4739   return SDValue();
4740 }
4741
4742 // Gather data to see if the operation can be modelled as a
4743 // shuffle in combination with VEXTs.
4744 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4745                                               SelectionDAG &DAG) const {
4746   SDLoc dl(Op);
4747   EVT VT = Op.getValueType();
4748   unsigned NumElts = VT.getVectorNumElements();
4749
4750   SmallVector<SDValue, 2> SourceVecs;
4751   SmallVector<unsigned, 2> MinElts;
4752   SmallVector<unsigned, 2> MaxElts;
4753
4754   for (unsigned i = 0; i < NumElts; ++i) {
4755     SDValue V = Op.getOperand(i);
4756     if (V.getOpcode() == ISD::UNDEF)
4757       continue;
4758     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4759       // A shuffle can only come from building a vector from various
4760       // elements of other vectors.
4761       return SDValue();
4762     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4763                VT.getVectorElementType()) {
4764       // This code doesn't know how to handle shuffles where the vector
4765       // element types do not match (this happens because type legalization
4766       // promotes the return type of EXTRACT_VECTOR_ELT).
4767       // FIXME: It might be appropriate to extend this code to handle
4768       // mismatched types.
4769       return SDValue();
4770     }
4771
4772     // Record this extraction against the appropriate vector if possible...
4773     SDValue SourceVec = V.getOperand(0);
4774     // If the element number isn't a constant, we can't effectively
4775     // analyze what's going on.
4776     if (!isa<ConstantSDNode>(V.getOperand(1)))
4777       return SDValue();
4778     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4779     bool FoundSource = false;
4780     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4781       if (SourceVecs[j] == SourceVec) {
4782         if (MinElts[j] > EltNo)
4783           MinElts[j] = EltNo;
4784         if (MaxElts[j] < EltNo)
4785           MaxElts[j] = EltNo;
4786         FoundSource = true;
4787         break;
4788       }
4789     }
4790
4791     // Or record a new source if not...
4792     if (!FoundSource) {
4793       SourceVecs.push_back(SourceVec);
4794       MinElts.push_back(EltNo);
4795       MaxElts.push_back(EltNo);
4796     }
4797   }
4798
4799   // Currently only do something sane when at most two source vectors
4800   // involved.
4801   if (SourceVecs.size() > 2)
4802     return SDValue();
4803
4804   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4805   int VEXTOffsets[2] = {0, 0};
4806
4807   // This loop extracts the usage patterns of the source vectors
4808   // and prepares appropriate SDValues for a shuffle if possible.
4809   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4810     if (SourceVecs[i].getValueType() == VT) {
4811       // No VEXT necessary
4812       ShuffleSrcs[i] = SourceVecs[i];
4813       VEXTOffsets[i] = 0;
4814       continue;
4815     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4816       // It probably isn't worth padding out a smaller vector just to
4817       // break it down again in a shuffle.
4818       return SDValue();
4819     }
4820
4821     // Since only 64-bit and 128-bit vectors are legal on ARM and
4822     // we've eliminated the other cases...
4823     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4824            "unexpected vector sizes in ReconstructShuffle");
4825
4826     if (MaxElts[i] - MinElts[i] >= NumElts) {
4827       // Span too large for a VEXT to cope
4828       return SDValue();
4829     }
4830
4831     if (MinElts[i] >= NumElts) {
4832       // The extraction can just take the second half
4833       VEXTOffsets[i] = NumElts;
4834       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4835                                    SourceVecs[i],
4836                                    DAG.getIntPtrConstant(NumElts));
4837     } else if (MaxElts[i] < NumElts) {
4838       // The extraction can just take the first half
4839       VEXTOffsets[i] = 0;
4840       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4841                                    SourceVecs[i],
4842                                    DAG.getIntPtrConstant(0));
4843     } else {
4844       // An actual VEXT is needed
4845       VEXTOffsets[i] = MinElts[i];
4846       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4847                                      SourceVecs[i],
4848                                      DAG.getIntPtrConstant(0));
4849       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4850                                      SourceVecs[i],
4851                                      DAG.getIntPtrConstant(NumElts));
4852       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4853                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4854     }
4855   }
4856
4857   SmallVector<int, 8> Mask;
4858
4859   for (unsigned i = 0; i < NumElts; ++i) {
4860     SDValue Entry = Op.getOperand(i);
4861     if (Entry.getOpcode() == ISD::UNDEF) {
4862       Mask.push_back(-1);
4863       continue;
4864     }
4865
4866     SDValue ExtractVec = Entry.getOperand(0);
4867     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4868                                           .getOperand(1))->getSExtValue();
4869     if (ExtractVec == SourceVecs[0]) {
4870       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4871     } else {
4872       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4873     }
4874   }
4875
4876   // Final check before we try to produce nonsense...
4877   if (isShuffleMaskLegal(Mask, VT))
4878     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4879                                 &Mask[0]);
4880
4881   return SDValue();
4882 }
4883
4884 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4885 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4886 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4887 /// are assumed to be legal.
4888 bool
4889 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4890                                       EVT VT) const {
4891   if (VT.getVectorNumElements() == 4 &&
4892       (VT.is128BitVector() || VT.is64BitVector())) {
4893     unsigned PFIndexes[4];
4894     for (unsigned i = 0; i != 4; ++i) {
4895       if (M[i] < 0)
4896         PFIndexes[i] = 8;
4897       else
4898         PFIndexes[i] = M[i];
4899     }
4900
4901     // Compute the index in the perfect shuffle table.
4902     unsigned PFTableIndex =
4903       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4904     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4905     unsigned Cost = (PFEntry >> 30);
4906
4907     if (Cost <= 4)
4908       return true;
4909   }
4910
4911   bool ReverseVEXT;
4912   unsigned Imm, WhichResult;
4913
4914   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4915   return (EltSize >= 32 ||
4916           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4917           isVREVMask(M, VT, 64) ||
4918           isVREVMask(M, VT, 32) ||
4919           isVREVMask(M, VT, 16) ||
4920           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4921           isVTBLMask(M, VT) ||
4922           isVTRNMask(M, VT, WhichResult) ||
4923           isVUZPMask(M, VT, WhichResult) ||
4924           isVZIPMask(M, VT, WhichResult) ||
4925           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4926           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4927           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4928           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4929 }
4930
4931 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4932 /// the specified operations to build the shuffle.
4933 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4934                                       SDValue RHS, SelectionDAG &DAG,
4935                                       SDLoc dl) {
4936   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4937   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4938   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4939
4940   enum {
4941     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4942     OP_VREV,
4943     OP_VDUP0,
4944     OP_VDUP1,
4945     OP_VDUP2,
4946     OP_VDUP3,
4947     OP_VEXT1,
4948     OP_VEXT2,
4949     OP_VEXT3,
4950     OP_VUZPL, // VUZP, left result
4951     OP_VUZPR, // VUZP, right result
4952     OP_VZIPL, // VZIP, left result
4953     OP_VZIPR, // VZIP, right result
4954     OP_VTRNL, // VTRN, left result
4955     OP_VTRNR  // VTRN, right result
4956   };
4957
4958   if (OpNum == OP_COPY) {
4959     if (LHSID == (1*9+2)*9+3) return LHS;
4960     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4961     return RHS;
4962   }
4963
4964   SDValue OpLHS, OpRHS;
4965   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4966   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4967   EVT VT = OpLHS.getValueType();
4968
4969   switch (OpNum) {
4970   default: llvm_unreachable("Unknown shuffle opcode!");
4971   case OP_VREV:
4972     // VREV divides the vector in half and swaps within the half.
4973     if (VT.getVectorElementType() == MVT::i32 ||
4974         VT.getVectorElementType() == MVT::f32)
4975       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4976     // vrev <4 x i16> -> VREV32
4977     if (VT.getVectorElementType() == MVT::i16)
4978       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4979     // vrev <4 x i8> -> VREV16
4980     assert(VT.getVectorElementType() == MVT::i8);
4981     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4982   case OP_VDUP0:
4983   case OP_VDUP1:
4984   case OP_VDUP2:
4985   case OP_VDUP3:
4986     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4987                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4988   case OP_VEXT1:
4989   case OP_VEXT2:
4990   case OP_VEXT3:
4991     return DAG.getNode(ARMISD::VEXT, dl, VT,
4992                        OpLHS, OpRHS,
4993                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4994   case OP_VUZPL:
4995   case OP_VUZPR:
4996     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4997                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4998   case OP_VZIPL:
4999   case OP_VZIPR:
5000     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5001                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5002   case OP_VTRNL:
5003   case OP_VTRNR:
5004     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5005                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5006   }
5007 }
5008
5009 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5010                                        ArrayRef<int> ShuffleMask,
5011                                        SelectionDAG &DAG) {
5012   // Check to see if we can use the VTBL instruction.
5013   SDValue V1 = Op.getOperand(0);
5014   SDValue V2 = Op.getOperand(1);
5015   SDLoc DL(Op);
5016
5017   SmallVector<SDValue, 8> VTBLMask;
5018   for (ArrayRef<int>::iterator
5019          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5020     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5021
5022   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5023     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5024                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5025                                    &VTBLMask[0], 8));
5026
5027   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5028                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5029                                  &VTBLMask[0], 8));
5030 }
5031
5032 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5033                                                       SelectionDAG &DAG) {
5034   SDLoc DL(Op);
5035   SDValue OpLHS = Op.getOperand(0);
5036   EVT VT = OpLHS.getValueType();
5037
5038   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5039          "Expect an v8i16/v16i8 type");
5040   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5041   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5042   // extract the first 8 bytes into the top double word and the last 8 bytes
5043   // into the bottom double word. The v8i16 case is similar.
5044   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5045   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5046                      DAG.getConstant(ExtractNum, MVT::i32));
5047 }
5048
5049 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5050   SDValue V1 = Op.getOperand(0);
5051   SDValue V2 = Op.getOperand(1);
5052   SDLoc dl(Op);
5053   EVT VT = Op.getValueType();
5054   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5055
5056   // Convert shuffles that are directly supported on NEON to target-specific
5057   // DAG nodes, instead of keeping them as shuffles and matching them again
5058   // during code selection.  This is more efficient and avoids the possibility
5059   // of inconsistencies between legalization and selection.
5060   // FIXME: floating-point vectors should be canonicalized to integer vectors
5061   // of the same time so that they get CSEd properly.
5062   ArrayRef<int> ShuffleMask = SVN->getMask();
5063
5064   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5065   if (EltSize <= 32) {
5066     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5067       int Lane = SVN->getSplatIndex();
5068       // If this is undef splat, generate it via "just" vdup, if possible.
5069       if (Lane == -1) Lane = 0;
5070
5071       // Test if V1 is a SCALAR_TO_VECTOR.
5072       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5073         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5074       }
5075       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5076       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5077       // reaches it).
5078       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5079           !isa<ConstantSDNode>(V1.getOperand(0))) {
5080         bool IsScalarToVector = true;
5081         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5082           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5083             IsScalarToVector = false;
5084             break;
5085           }
5086         if (IsScalarToVector)
5087           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5088       }
5089       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5090                          DAG.getConstant(Lane, MVT::i32));
5091     }
5092
5093     bool ReverseVEXT;
5094     unsigned Imm;
5095     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5096       if (ReverseVEXT)
5097         std::swap(V1, V2);
5098       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5099                          DAG.getConstant(Imm, MVT::i32));
5100     }
5101
5102     if (isVREVMask(ShuffleMask, VT, 64))
5103       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5104     if (isVREVMask(ShuffleMask, VT, 32))
5105       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5106     if (isVREVMask(ShuffleMask, VT, 16))
5107       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5108
5109     if (V2->getOpcode() == ISD::UNDEF &&
5110         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5111       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5112                          DAG.getConstant(Imm, MVT::i32));
5113     }
5114
5115     // Check for Neon shuffles that modify both input vectors in place.
5116     // If both results are used, i.e., if there are two shuffles with the same
5117     // source operands and with masks corresponding to both results of one of
5118     // these operations, DAG memoization will ensure that a single node is
5119     // used for both shuffles.
5120     unsigned WhichResult;
5121     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5122       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5123                          V1, V2).getValue(WhichResult);
5124     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5125       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5126                          V1, V2).getValue(WhichResult);
5127     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5128       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5129                          V1, V2).getValue(WhichResult);
5130
5131     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5132       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5133                          V1, V1).getValue(WhichResult);
5134     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5135       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5136                          V1, V1).getValue(WhichResult);
5137     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5138       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5139                          V1, V1).getValue(WhichResult);
5140   }
5141
5142   // If the shuffle is not directly supported and it has 4 elements, use
5143   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5144   unsigned NumElts = VT.getVectorNumElements();
5145   if (NumElts == 4) {
5146     unsigned PFIndexes[4];
5147     for (unsigned i = 0; i != 4; ++i) {
5148       if (ShuffleMask[i] < 0)
5149         PFIndexes[i] = 8;
5150       else
5151         PFIndexes[i] = ShuffleMask[i];
5152     }
5153
5154     // Compute the index in the perfect shuffle table.
5155     unsigned PFTableIndex =
5156       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5157     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5158     unsigned Cost = (PFEntry >> 30);
5159
5160     if (Cost <= 4)
5161       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5162   }
5163
5164   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5165   if (EltSize >= 32) {
5166     // Do the expansion with floating-point types, since that is what the VFP
5167     // registers are defined to use, and since i64 is not legal.
5168     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5169     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5170     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5171     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5172     SmallVector<SDValue, 8> Ops;
5173     for (unsigned i = 0; i < NumElts; ++i) {
5174       if (ShuffleMask[i] < 0)
5175         Ops.push_back(DAG.getUNDEF(EltVT));
5176       else
5177         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5178                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5179                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5180                                                   MVT::i32)));
5181     }
5182     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5183     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5184   }
5185
5186   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5187     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5188
5189   if (VT == MVT::v8i8) {
5190     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5191     if (NewOp.getNode())
5192       return NewOp;
5193   }
5194
5195   return SDValue();
5196 }
5197
5198 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5199   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5200   SDValue Lane = Op.getOperand(2);
5201   if (!isa<ConstantSDNode>(Lane))
5202     return SDValue();
5203
5204   return Op;
5205 }
5206
5207 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5208   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5209   SDValue Lane = Op.getOperand(1);
5210   if (!isa<ConstantSDNode>(Lane))
5211     return SDValue();
5212
5213   SDValue Vec = Op.getOperand(0);
5214   if (Op.getValueType() == MVT::i32 &&
5215       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5216     SDLoc dl(Op);
5217     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5218   }
5219
5220   return Op;
5221 }
5222
5223 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5224   // The only time a CONCAT_VECTORS operation can have legal types is when
5225   // two 64-bit vectors are concatenated to a 128-bit vector.
5226   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5227          "unexpected CONCAT_VECTORS");
5228   SDLoc dl(Op);
5229   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5230   SDValue Op0 = Op.getOperand(0);
5231   SDValue Op1 = Op.getOperand(1);
5232   if (Op0.getOpcode() != ISD::UNDEF)
5233     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5234                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5235                       DAG.getIntPtrConstant(0));
5236   if (Op1.getOpcode() != ISD::UNDEF)
5237     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5238                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5239                       DAG.getIntPtrConstant(1));
5240   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5241 }
5242
5243 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5244 /// element has been zero/sign-extended, depending on the isSigned parameter,
5245 /// from an integer type half its size.
5246 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5247                                    bool isSigned) {
5248   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5249   EVT VT = N->getValueType(0);
5250   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5251     SDNode *BVN = N->getOperand(0).getNode();
5252     if (BVN->getValueType(0) != MVT::v4i32 ||
5253         BVN->getOpcode() != ISD::BUILD_VECTOR)
5254       return false;
5255     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5256     unsigned HiElt = 1 - LoElt;
5257     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5258     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5259     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5260     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5261     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5262       return false;
5263     if (isSigned) {
5264       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5265           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5266         return true;
5267     } else {
5268       if (Hi0->isNullValue() && Hi1->isNullValue())
5269         return true;
5270     }
5271     return false;
5272   }
5273
5274   if (N->getOpcode() != ISD::BUILD_VECTOR)
5275     return false;
5276
5277   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5278     SDNode *Elt = N->getOperand(i).getNode();
5279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5280       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5281       unsigned HalfSize = EltSize / 2;
5282       if (isSigned) {
5283         if (!isIntN(HalfSize, C->getSExtValue()))
5284           return false;
5285       } else {
5286         if (!isUIntN(HalfSize, C->getZExtValue()))
5287           return false;
5288       }
5289       continue;
5290     }
5291     return false;
5292   }
5293
5294   return true;
5295 }
5296
5297 /// isSignExtended - Check if a node is a vector value that is sign-extended
5298 /// or a constant BUILD_VECTOR with sign-extended elements.
5299 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5300   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5301     return true;
5302   if (isExtendedBUILD_VECTOR(N, DAG, true))
5303     return true;
5304   return false;
5305 }
5306
5307 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5308 /// or a constant BUILD_VECTOR with zero-extended elements.
5309 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5310   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5311     return true;
5312   if (isExtendedBUILD_VECTOR(N, DAG, false))
5313     return true;
5314   return false;
5315 }
5316
5317 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5318   if (OrigVT.getSizeInBits() >= 64)
5319     return OrigVT;
5320
5321   assert(OrigVT.isSimple() && "Expecting a simple value type");
5322
5323   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5324   switch (OrigSimpleTy) {
5325   default: llvm_unreachable("Unexpected Vector Type");
5326   case MVT::v2i8:
5327   case MVT::v2i16:
5328      return MVT::v2i32;
5329   case MVT::v4i8:
5330     return  MVT::v4i16;
5331   }
5332 }
5333
5334 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5335 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5336 /// We insert the required extension here to get the vector to fill a D register.
5337 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5338                                             const EVT &OrigTy,
5339                                             const EVT &ExtTy,
5340                                             unsigned ExtOpcode) {
5341   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5342   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5343   // 64-bits we need to insert a new extension so that it will be 64-bits.
5344   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5345   if (OrigTy.getSizeInBits() >= 64)
5346     return N;
5347
5348   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5349   EVT NewVT = getExtensionTo64Bits(OrigTy);
5350
5351   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5352 }
5353
5354 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5355 /// does not do any sign/zero extension. If the original vector is less
5356 /// than 64 bits, an appropriate extension will be added after the load to
5357 /// reach a total size of 64 bits. We have to add the extension separately
5358 /// because ARM does not have a sign/zero extending load for vectors.
5359 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5360   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5361
5362   // The load already has the right type.
5363   if (ExtendedTy == LD->getMemoryVT())
5364     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5365                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5366                 LD->isNonTemporal(), LD->isInvariant(),
5367                 LD->getAlignment());
5368
5369   // We need to create a zextload/sextload. We cannot just create a load
5370   // followed by a zext/zext node because LowerMUL is also run during normal
5371   // operation legalization where we can't create illegal types.
5372   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5373                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5374                         LD->getMemoryVT(), LD->isVolatile(),
5375                         LD->isNonTemporal(), LD->getAlignment());
5376 }
5377
5378 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5379 /// extending load, or BUILD_VECTOR with extended elements, return the
5380 /// unextended value. The unextended vector should be 64 bits so that it can
5381 /// be used as an operand to a VMULL instruction. If the original vector size
5382 /// before extension is less than 64 bits we add a an extension to resize
5383 /// the vector to 64 bits.
5384 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5385   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5386     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5387                                         N->getOperand(0)->getValueType(0),
5388                                         N->getValueType(0),
5389                                         N->getOpcode());
5390
5391   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5392     return SkipLoadExtensionForVMULL(LD, DAG);
5393
5394   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5395   // have been legalized as a BITCAST from v4i32.
5396   if (N->getOpcode() == ISD::BITCAST) {
5397     SDNode *BVN = N->getOperand(0).getNode();
5398     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5399            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5400     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5401     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5402                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5403   }
5404   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5405   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5406   EVT VT = N->getValueType(0);
5407   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5408   unsigned NumElts = VT.getVectorNumElements();
5409   MVT TruncVT = MVT::getIntegerVT(EltSize);
5410   SmallVector<SDValue, 8> Ops;
5411   for (unsigned i = 0; i != NumElts; ++i) {
5412     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5413     const APInt &CInt = C->getAPIntValue();
5414     // Element types smaller than 32 bits are not legal, so use i32 elements.
5415     // The values are implicitly truncated so sext vs. zext doesn't matter.
5416     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5417   }
5418   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5419                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5420 }
5421
5422 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5423   unsigned Opcode = N->getOpcode();
5424   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5425     SDNode *N0 = N->getOperand(0).getNode();
5426     SDNode *N1 = N->getOperand(1).getNode();
5427     return N0->hasOneUse() && N1->hasOneUse() &&
5428       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5429   }
5430   return false;
5431 }
5432
5433 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5434   unsigned Opcode = N->getOpcode();
5435   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5436     SDNode *N0 = N->getOperand(0).getNode();
5437     SDNode *N1 = N->getOperand(1).getNode();
5438     return N0->hasOneUse() && N1->hasOneUse() &&
5439       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5440   }
5441   return false;
5442 }
5443
5444 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5445   // Multiplications are only custom-lowered for 128-bit vectors so that
5446   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5447   EVT VT = Op.getValueType();
5448   assert(VT.is128BitVector() && VT.isInteger() &&
5449          "unexpected type for custom-lowering ISD::MUL");
5450   SDNode *N0 = Op.getOperand(0).getNode();
5451   SDNode *N1 = Op.getOperand(1).getNode();
5452   unsigned NewOpc = 0;
5453   bool isMLA = false;
5454   bool isN0SExt = isSignExtended(N0, DAG);
5455   bool isN1SExt = isSignExtended(N1, DAG);
5456   if (isN0SExt && isN1SExt)
5457     NewOpc = ARMISD::VMULLs;
5458   else {
5459     bool isN0ZExt = isZeroExtended(N0, DAG);
5460     bool isN1ZExt = isZeroExtended(N1, DAG);
5461     if (isN0ZExt && isN1ZExt)
5462       NewOpc = ARMISD::VMULLu;
5463     else if (isN1SExt || isN1ZExt) {
5464       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5465       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5466       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5467         NewOpc = ARMISD::VMULLs;
5468         isMLA = true;
5469       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5470         NewOpc = ARMISD::VMULLu;
5471         isMLA = true;
5472       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5473         std::swap(N0, N1);
5474         NewOpc = ARMISD::VMULLu;
5475         isMLA = true;
5476       }
5477     }
5478
5479     if (!NewOpc) {
5480       if (VT == MVT::v2i64)
5481         // Fall through to expand this.  It is not legal.
5482         return SDValue();
5483       else
5484         // Other vector multiplications are legal.
5485         return Op;
5486     }
5487   }
5488
5489   // Legalize to a VMULL instruction.
5490   SDLoc DL(Op);
5491   SDValue Op0;
5492   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5493   if (!isMLA) {
5494     Op0 = SkipExtensionForVMULL(N0, DAG);
5495     assert(Op0.getValueType().is64BitVector() &&
5496            Op1.getValueType().is64BitVector() &&
5497            "unexpected types for extended operands to VMULL");
5498     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5499   }
5500
5501   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5502   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5503   //   vmull q0, d4, d6
5504   //   vmlal q0, d5, d6
5505   // is faster than
5506   //   vaddl q0, d4, d5
5507   //   vmovl q1, d6
5508   //   vmul  q0, q0, q1
5509   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5510   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5511   EVT Op1VT = Op1.getValueType();
5512   return DAG.getNode(N0->getOpcode(), DL, VT,
5513                      DAG.getNode(NewOpc, DL, VT,
5514                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5515                      DAG.getNode(NewOpc, DL, VT,
5516                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5517 }
5518
5519 static SDValue
5520 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5521   // Convert to float
5522   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5523   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5524   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5525   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5526   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5527   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5528   // Get reciprocal estimate.
5529   // float4 recip = vrecpeq_f32(yf);
5530   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5531                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5532   // Because char has a smaller range than uchar, we can actually get away
5533   // without any newton steps.  This requires that we use a weird bias
5534   // of 0xb000, however (again, this has been exhaustively tested).
5535   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5536   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5537   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5538   Y = DAG.getConstant(0xb000, MVT::i32);
5539   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5540   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5541   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5542   // Convert back to short.
5543   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5544   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5545   return X;
5546 }
5547
5548 static SDValue
5549 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5550   SDValue N2;
5551   // Convert to float.
5552   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5553   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5554   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5555   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5556   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5557   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5558
5559   // Use reciprocal estimate and one refinement step.
5560   // float4 recip = vrecpeq_f32(yf);
5561   // recip *= vrecpsq_f32(yf, recip);
5562   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5563                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5564   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5565                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5566                    N1, N2);
5567   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5568   // Because short has a smaller range than ushort, we can actually get away
5569   // with only a single newton step.  This requires that we use a weird bias
5570   // of 89, however (again, this has been exhaustively tested).
5571   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5572   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5573   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5574   N1 = DAG.getConstant(0x89, MVT::i32);
5575   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5576   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5577   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5578   // Convert back to integer and return.
5579   // return vmovn_s32(vcvt_s32_f32(result));
5580   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5581   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5582   return N0;
5583 }
5584
5585 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5586   EVT VT = Op.getValueType();
5587   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5588          "unexpected type for custom-lowering ISD::SDIV");
5589
5590   SDLoc dl(Op);
5591   SDValue N0 = Op.getOperand(0);
5592   SDValue N1 = Op.getOperand(1);
5593   SDValue N2, N3;
5594
5595   if (VT == MVT::v8i8) {
5596     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5597     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5598
5599     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5600                      DAG.getIntPtrConstant(4));
5601     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5602                      DAG.getIntPtrConstant(4));
5603     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5604                      DAG.getIntPtrConstant(0));
5605     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5606                      DAG.getIntPtrConstant(0));
5607
5608     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5609     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5610
5611     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5612     N0 = LowerCONCAT_VECTORS(N0, DAG);
5613
5614     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5615     return N0;
5616   }
5617   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5618 }
5619
5620 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5621   EVT VT = Op.getValueType();
5622   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5623          "unexpected type for custom-lowering ISD::UDIV");
5624
5625   SDLoc dl(Op);
5626   SDValue N0 = Op.getOperand(0);
5627   SDValue N1 = Op.getOperand(1);
5628   SDValue N2, N3;
5629
5630   if (VT == MVT::v8i8) {
5631     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5632     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5633
5634     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5635                      DAG.getIntPtrConstant(4));
5636     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5637                      DAG.getIntPtrConstant(4));
5638     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5639                      DAG.getIntPtrConstant(0));
5640     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5641                      DAG.getIntPtrConstant(0));
5642
5643     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5644     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5645
5646     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5647     N0 = LowerCONCAT_VECTORS(N0, DAG);
5648
5649     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5650                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5651                      N0);
5652     return N0;
5653   }
5654
5655   // v4i16 sdiv ... Convert to float.
5656   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5657   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5658   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5659   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5660   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5661   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5662
5663   // Use reciprocal estimate and two refinement steps.
5664   // float4 recip = vrecpeq_f32(yf);
5665   // recip *= vrecpsq_f32(yf, recip);
5666   // recip *= vrecpsq_f32(yf, recip);
5667   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5668                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5669   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5670                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5671                    BN1, N2);
5672   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5673   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5674                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5675                    BN1, N2);
5676   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5677   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5678   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5679   // and that it will never cause us to return an answer too large).
5680   // float4 result = as_float4(as_int4(xf*recip) + 2);
5681   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5682   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5683   N1 = DAG.getConstant(2, MVT::i32);
5684   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5685   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5686   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5687   // Convert back to integer and return.
5688   // return vmovn_u32(vcvt_s32_f32(result));
5689   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5690   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5691   return N0;
5692 }
5693
5694 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5695   EVT VT = Op.getNode()->getValueType(0);
5696   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5697
5698   unsigned Opc;
5699   bool ExtraOp = false;
5700   switch (Op.getOpcode()) {
5701   default: llvm_unreachable("Invalid code");
5702   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5703   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5704   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5705   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5706   }
5707
5708   if (!ExtraOp)
5709     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5710                        Op.getOperand(1));
5711   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5712                      Op.getOperand(1), Op.getOperand(2));
5713 }
5714
5715 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5716   // Monotonic load/store is legal for all targets
5717   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5718     return Op;
5719
5720   // Aquire/Release load/store is not legal for targets without a
5721   // dmb or equivalent available.
5722   return SDValue();
5723 }
5724
5725 static void
5726 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5727                     SelectionDAG &DAG, unsigned NewOp) {
5728   SDLoc dl(Node);
5729   assert (Node->getValueType(0) == MVT::i64 &&
5730           "Only know how to expand i64 atomics");
5731
5732   SmallVector<SDValue, 6> Ops;
5733   Ops.push_back(Node->getOperand(0)); // Chain
5734   Ops.push_back(Node->getOperand(1)); // Ptr
5735   // Low part of Val1
5736   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5737                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5738   // High part of Val1
5739   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5740                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5741   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5742     // High part of Val1
5743     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5744                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5745     // High part of Val2
5746     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5747                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5748   }
5749   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5750   SDValue Result =
5751     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5752                             cast<MemSDNode>(Node)->getMemOperand());
5753   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5754   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5755   Results.push_back(Result.getValue(2));
5756 }
5757
5758 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5759                                     SmallVectorImpl<SDValue> &Results,
5760                                     SelectionDAG &DAG,
5761                                     const ARMSubtarget *Subtarget) {
5762   SDLoc DL(N);
5763   SDValue Cycles32, OutChain;
5764
5765   if (Subtarget->hasPerfMon()) {
5766     // Under Power Management extensions, the cycle-count is:
5767     //    mrc p15, #0, <Rt>, c9, c13, #0
5768     SDValue Ops[] = { N->getOperand(0), // Chain
5769                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5770                       DAG.getConstant(15, MVT::i32),
5771                       DAG.getConstant(0, MVT::i32),
5772                       DAG.getConstant(9, MVT::i32),
5773                       DAG.getConstant(13, MVT::i32),
5774                       DAG.getConstant(0, MVT::i32)
5775     };
5776
5777     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5778                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5779                            array_lengthof(Ops));
5780     OutChain = Cycles32.getValue(1);
5781   } else {
5782     // Intrinsic is defined to return 0 on unsupported platforms. Technically
5783     // there are older ARM CPUs that have implementation-specific ways of
5784     // obtaining this information (FIXME!).
5785     Cycles32 = DAG.getConstant(0, MVT::i32);
5786     OutChain = DAG.getEntryNode();
5787   }
5788
5789
5790   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5791                                  Cycles32, DAG.getConstant(0, MVT::i32));
5792   Results.push_back(Cycles64);
5793   Results.push_back(OutChain);
5794 }
5795
5796 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5797   switch (Op.getOpcode()) {
5798   default: llvm_unreachable("Don't know how to custom lower this!");
5799   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5800   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5801   case ISD::GlobalAddress:
5802     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5803       LowerGlobalAddressELF(Op, DAG);
5804   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5805   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5806   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5807   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5808   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5809   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5810   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5811   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5812   case ISD::SINT_TO_FP:
5813   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5814   case ISD::FP_TO_SINT:
5815   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5816   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5817   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5818   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5819   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5820   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5821   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5822   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5823                                                                Subtarget);
5824   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5825   case ISD::SHL:
5826   case ISD::SRL:
5827   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5828   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5829   case ISD::SRL_PARTS:
5830   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5831   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5832   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5833   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5834   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5835   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5836   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5837   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5838   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5839   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5840   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5841   case ISD::MUL:           return LowerMUL(Op, DAG);
5842   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5843   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5844   case ISD::ADDC:
5845   case ISD::ADDE:
5846   case ISD::SUBC:
5847   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5848   case ISD::ATOMIC_LOAD:
5849   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5850   }
5851 }
5852
5853 /// ReplaceNodeResults - Replace the results of node with an illegal result
5854 /// type with new values built out of custom code.
5855 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5856                                            SmallVectorImpl<SDValue>&Results,
5857                                            SelectionDAG &DAG) const {
5858   SDValue Res;
5859   switch (N->getOpcode()) {
5860   default:
5861     llvm_unreachable("Don't know how to custom expand this!");
5862   case ISD::BITCAST:
5863     Res = ExpandBITCAST(N, DAG);
5864     break;
5865   case ISD::SIGN_EXTEND:
5866   case ISD::ZERO_EXTEND:
5867     Res = ExpandVectorExtension(N, DAG);
5868     break;
5869   case ISD::SRL:
5870   case ISD::SRA:
5871     Res = Expand64BitShift(N, DAG, Subtarget);
5872     break;
5873   case ISD::READCYCLECOUNTER:
5874     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
5875     return;
5876   case ISD::ATOMIC_LOAD_ADD:
5877     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5878     return;
5879   case ISD::ATOMIC_LOAD_AND:
5880     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5881     return;
5882   case ISD::ATOMIC_LOAD_NAND:
5883     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5884     return;
5885   case ISD::ATOMIC_LOAD_OR:
5886     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5887     return;
5888   case ISD::ATOMIC_LOAD_SUB:
5889     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5890     return;
5891   case ISD::ATOMIC_LOAD_XOR:
5892     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5893     return;
5894   case ISD::ATOMIC_SWAP:
5895     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5896     return;
5897   case ISD::ATOMIC_CMP_SWAP:
5898     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5899     return;
5900   case ISD::ATOMIC_LOAD_MIN:
5901     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5902     return;
5903   case ISD::ATOMIC_LOAD_UMIN:
5904     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5905     return;
5906   case ISD::ATOMIC_LOAD_MAX:
5907     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5908     return;
5909   case ISD::ATOMIC_LOAD_UMAX:
5910     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5911     return;
5912   }
5913   if (Res.getNode())
5914     Results.push_back(Res);
5915 }
5916
5917 //===----------------------------------------------------------------------===//
5918 //                           ARM Scheduler Hooks
5919 //===----------------------------------------------------------------------===//
5920
5921 MachineBasicBlock *
5922 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5923                                      MachineBasicBlock *BB,
5924                                      unsigned Size) const {
5925   unsigned dest    = MI->getOperand(0).getReg();
5926   unsigned ptr     = MI->getOperand(1).getReg();
5927   unsigned oldval  = MI->getOperand(2).getReg();
5928   unsigned newval  = MI->getOperand(3).getReg();
5929   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5930   DebugLoc dl = MI->getDebugLoc();
5931   bool isThumb2 = Subtarget->isThumb2();
5932
5933   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5934   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5935     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5936     (const TargetRegisterClass*)&ARM::GPRRegClass);
5937
5938   if (isThumb2) {
5939     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5940     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5941     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5942   }
5943
5944   unsigned ldrOpc, strOpc;
5945   switch (Size) {
5946   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5947   case 1:
5948     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5949     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5950     break;
5951   case 2:
5952     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5953     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5954     break;
5955   case 4:
5956     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5957     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5958     break;
5959   }
5960
5961   MachineFunction *MF = BB->getParent();
5962   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5963   MachineFunction::iterator It = BB;
5964   ++It; // insert the new blocks after the current block
5965
5966   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5967   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5968   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5969   MF->insert(It, loop1MBB);
5970   MF->insert(It, loop2MBB);
5971   MF->insert(It, exitMBB);
5972
5973   // Transfer the remainder of BB and its successor edges to exitMBB.
5974   exitMBB->splice(exitMBB->begin(), BB,
5975                   llvm::next(MachineBasicBlock::iterator(MI)),
5976                   BB->end());
5977   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5978
5979   //  thisMBB:
5980   //   ...
5981   //   fallthrough --> loop1MBB
5982   BB->addSuccessor(loop1MBB);
5983
5984   // loop1MBB:
5985   //   ldrex dest, [ptr]
5986   //   cmp dest, oldval
5987   //   bne exitMBB
5988   BB = loop1MBB;
5989   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5990   if (ldrOpc == ARM::t2LDREX)
5991     MIB.addImm(0);
5992   AddDefaultPred(MIB);
5993   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5994                  .addReg(dest).addReg(oldval));
5995   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5996     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5997   BB->addSuccessor(loop2MBB);
5998   BB->addSuccessor(exitMBB);
5999
6000   // loop2MBB:
6001   //   strex scratch, newval, [ptr]
6002   //   cmp scratch, #0
6003   //   bne loop1MBB
6004   BB = loop2MBB;
6005   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6006   if (strOpc == ARM::t2STREX)
6007     MIB.addImm(0);
6008   AddDefaultPred(MIB);
6009   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6010                  .addReg(scratch).addImm(0));
6011   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6012     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6013   BB->addSuccessor(loop1MBB);
6014   BB->addSuccessor(exitMBB);
6015
6016   //  exitMBB:
6017   //   ...
6018   BB = exitMBB;
6019
6020   MI->eraseFromParent();   // The instruction is gone now.
6021
6022   return BB;
6023 }
6024
6025 MachineBasicBlock *
6026 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6027                                     unsigned Size, unsigned BinOpcode) const {
6028   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6029   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6030
6031   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6032   MachineFunction *MF = BB->getParent();
6033   MachineFunction::iterator It = BB;
6034   ++It;
6035
6036   unsigned dest = MI->getOperand(0).getReg();
6037   unsigned ptr = MI->getOperand(1).getReg();
6038   unsigned incr = MI->getOperand(2).getReg();
6039   DebugLoc dl = MI->getDebugLoc();
6040   bool isThumb2 = Subtarget->isThumb2();
6041
6042   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6043   if (isThumb2) {
6044     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6045     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6046   }
6047
6048   unsigned ldrOpc, strOpc;
6049   switch (Size) {
6050   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6051   case 1:
6052     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6053     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6054     break;
6055   case 2:
6056     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6057     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6058     break;
6059   case 4:
6060     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6061     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6062     break;
6063   }
6064
6065   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6066   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6067   MF->insert(It, loopMBB);
6068   MF->insert(It, exitMBB);
6069
6070   // Transfer the remainder of BB and its successor edges to exitMBB.
6071   exitMBB->splice(exitMBB->begin(), BB,
6072                   llvm::next(MachineBasicBlock::iterator(MI)),
6073                   BB->end());
6074   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6075
6076   const TargetRegisterClass *TRC = isThumb2 ?
6077     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6078     (const TargetRegisterClass*)&ARM::GPRRegClass;
6079   unsigned scratch = MRI.createVirtualRegister(TRC);
6080   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6081
6082   //  thisMBB:
6083   //   ...
6084   //   fallthrough --> loopMBB
6085   BB->addSuccessor(loopMBB);
6086
6087   //  loopMBB:
6088   //   ldrex dest, ptr
6089   //   <binop> scratch2, dest, incr
6090   //   strex scratch, scratch2, ptr
6091   //   cmp scratch, #0
6092   //   bne- loopMBB
6093   //   fallthrough --> exitMBB
6094   BB = loopMBB;
6095   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6096   if (ldrOpc == ARM::t2LDREX)
6097     MIB.addImm(0);
6098   AddDefaultPred(MIB);
6099   if (BinOpcode) {
6100     // operand order needs to go the other way for NAND
6101     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6102       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6103                      addReg(incr).addReg(dest)).addReg(0);
6104     else
6105       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6106                      addReg(dest).addReg(incr)).addReg(0);
6107   }
6108
6109   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6110   if (strOpc == ARM::t2STREX)
6111     MIB.addImm(0);
6112   AddDefaultPred(MIB);
6113   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6114                  .addReg(scratch).addImm(0));
6115   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6116     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6117
6118   BB->addSuccessor(loopMBB);
6119   BB->addSuccessor(exitMBB);
6120
6121   //  exitMBB:
6122   //   ...
6123   BB = exitMBB;
6124
6125   MI->eraseFromParent();   // The instruction is gone now.
6126
6127   return BB;
6128 }
6129
6130 MachineBasicBlock *
6131 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6132                                           MachineBasicBlock *BB,
6133                                           unsigned Size,
6134                                           bool signExtend,
6135                                           ARMCC::CondCodes Cond) const {
6136   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6137
6138   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6139   MachineFunction *MF = BB->getParent();
6140   MachineFunction::iterator It = BB;
6141   ++It;
6142
6143   unsigned dest = MI->getOperand(0).getReg();
6144   unsigned ptr = MI->getOperand(1).getReg();
6145   unsigned incr = MI->getOperand(2).getReg();
6146   unsigned oldval = dest;
6147   DebugLoc dl = MI->getDebugLoc();
6148   bool isThumb2 = Subtarget->isThumb2();
6149
6150   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6151   if (isThumb2) {
6152     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6153     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6154   }
6155
6156   unsigned ldrOpc, strOpc, extendOpc;
6157   switch (Size) {
6158   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6159   case 1:
6160     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6161     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6162     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6163     break;
6164   case 2:
6165     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6166     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6167     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6168     break;
6169   case 4:
6170     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6171     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6172     extendOpc = 0;
6173     break;
6174   }
6175
6176   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6177   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6178   MF->insert(It, loopMBB);
6179   MF->insert(It, exitMBB);
6180
6181   // Transfer the remainder of BB and its successor edges to exitMBB.
6182   exitMBB->splice(exitMBB->begin(), BB,
6183                   llvm::next(MachineBasicBlock::iterator(MI)),
6184                   BB->end());
6185   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6186
6187   const TargetRegisterClass *TRC = isThumb2 ?
6188     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6189     (const TargetRegisterClass*)&ARM::GPRRegClass;
6190   unsigned scratch = MRI.createVirtualRegister(TRC);
6191   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6192
6193   //  thisMBB:
6194   //   ...
6195   //   fallthrough --> loopMBB
6196   BB->addSuccessor(loopMBB);
6197
6198   //  loopMBB:
6199   //   ldrex dest, ptr
6200   //   (sign extend dest, if required)
6201   //   cmp dest, incr
6202   //   cmov.cond scratch2, incr, dest
6203   //   strex scratch, scratch2, ptr
6204   //   cmp scratch, #0
6205   //   bne- loopMBB
6206   //   fallthrough --> exitMBB
6207   BB = loopMBB;
6208   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6209   if (ldrOpc == ARM::t2LDREX)
6210     MIB.addImm(0);
6211   AddDefaultPred(MIB);
6212
6213   // Sign extend the value, if necessary.
6214   if (signExtend && extendOpc) {
6215     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6216     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6217                      .addReg(dest)
6218                      .addImm(0));
6219   }
6220
6221   // Build compare and cmov instructions.
6222   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6223                  .addReg(oldval).addReg(incr));
6224   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6225          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6226
6227   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6228   if (strOpc == ARM::t2STREX)
6229     MIB.addImm(0);
6230   AddDefaultPred(MIB);
6231   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6232                  .addReg(scratch).addImm(0));
6233   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6234     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6235
6236   BB->addSuccessor(loopMBB);
6237   BB->addSuccessor(exitMBB);
6238
6239   //  exitMBB:
6240   //   ...
6241   BB = exitMBB;
6242
6243   MI->eraseFromParent();   // The instruction is gone now.
6244
6245   return BB;
6246 }
6247
6248 MachineBasicBlock *
6249 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6250                                       unsigned Op1, unsigned Op2,
6251                                       bool NeedsCarry, bool IsCmpxchg,
6252                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6253   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6254   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6255
6256   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6257   MachineFunction *MF = BB->getParent();
6258   MachineFunction::iterator It = BB;
6259   ++It;
6260
6261   unsigned destlo = MI->getOperand(0).getReg();
6262   unsigned desthi = MI->getOperand(1).getReg();
6263   unsigned ptr = MI->getOperand(2).getReg();
6264   unsigned vallo = MI->getOperand(3).getReg();
6265   unsigned valhi = MI->getOperand(4).getReg();
6266   DebugLoc dl = MI->getDebugLoc();
6267   bool isThumb2 = Subtarget->isThumb2();
6268
6269   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6270   if (isThumb2) {
6271     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6272     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6273     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6274   }
6275
6276   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6277   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6278   if (IsCmpxchg || IsMinMax)
6279     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6280   if (IsCmpxchg)
6281     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6282   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6283
6284   MF->insert(It, loopMBB);
6285   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6286   if (IsCmpxchg) MF->insert(It, cont2BB);
6287   MF->insert(It, exitMBB);
6288
6289   // Transfer the remainder of BB and its successor edges to exitMBB.
6290   exitMBB->splice(exitMBB->begin(), BB,
6291                   llvm::next(MachineBasicBlock::iterator(MI)),
6292                   BB->end());
6293   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6294
6295   const TargetRegisterClass *TRC = isThumb2 ?
6296     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6297     (const TargetRegisterClass*)&ARM::GPRRegClass;
6298   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6299
6300   //  thisMBB:
6301   //   ...
6302   //   fallthrough --> loopMBB
6303   BB->addSuccessor(loopMBB);
6304
6305   //  loopMBB:
6306   //   ldrexd r2, r3, ptr
6307   //   <binopa> r0, r2, incr
6308   //   <binopb> r1, r3, incr
6309   //   strexd storesuccess, r0, r1, ptr
6310   //   cmp storesuccess, #0
6311   //   bne- loopMBB
6312   //   fallthrough --> exitMBB
6313   BB = loopMBB;
6314
6315   // Load
6316   if (isThumb2) {
6317     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6318                    .addReg(destlo, RegState::Define)
6319                    .addReg(desthi, RegState::Define)
6320                    .addReg(ptr));
6321   } else {
6322     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6323     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6324                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6325     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6326     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6327       .addReg(GPRPair0, 0, ARM::gsub_0);
6328     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6329       .addReg(GPRPair0, 0, ARM::gsub_1);
6330   }
6331
6332   unsigned StoreLo, StoreHi;
6333   if (IsCmpxchg) {
6334     // Add early exit
6335     for (unsigned i = 0; i < 2; i++) {
6336       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6337                                                          ARM::CMPrr))
6338                      .addReg(i == 0 ? destlo : desthi)
6339                      .addReg(i == 0 ? vallo : valhi));
6340       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6341         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6342       BB->addSuccessor(exitMBB);
6343       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6344       BB = (i == 0 ? contBB : cont2BB);
6345     }
6346
6347     // Copy to physregs for strexd
6348     StoreLo = MI->getOperand(5).getReg();
6349     StoreHi = MI->getOperand(6).getReg();
6350   } else if (Op1) {
6351     // Perform binary operation
6352     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6353     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6354                    .addReg(destlo).addReg(vallo))
6355         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6356     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6357     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6358                    .addReg(desthi).addReg(valhi))
6359         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6360
6361     StoreLo = tmpRegLo;
6362     StoreHi = tmpRegHi;
6363   } else {
6364     // Copy to physregs for strexd
6365     StoreLo = vallo;
6366     StoreHi = valhi;
6367   }
6368   if (IsMinMax) {
6369     // Compare and branch to exit block.
6370     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6371       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6372     BB->addSuccessor(exitMBB);
6373     BB->addSuccessor(contBB);
6374     BB = contBB;
6375     StoreLo = vallo;
6376     StoreHi = valhi;
6377   }
6378
6379   // Store
6380   if (isThumb2) {
6381     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6382                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6383   } else {
6384     // Marshal a pair...
6385     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6386     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6387     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6388     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6389     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6390       .addReg(UndefPair)
6391       .addReg(StoreLo)
6392       .addImm(ARM::gsub_0);
6393     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6394       .addReg(r1)
6395       .addReg(StoreHi)
6396       .addImm(ARM::gsub_1);
6397
6398     // ...and store it
6399     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6400                    .addReg(StorePair).addReg(ptr));
6401   }
6402   // Cmp+jump
6403   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6404                  .addReg(storesuccess).addImm(0));
6405   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6406     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6407
6408   BB->addSuccessor(loopMBB);
6409   BB->addSuccessor(exitMBB);
6410
6411   //  exitMBB:
6412   //   ...
6413   BB = exitMBB;
6414
6415   MI->eraseFromParent();   // The instruction is gone now.
6416
6417   return BB;
6418 }
6419
6420 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6421 /// registers the function context.
6422 void ARMTargetLowering::
6423 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6424                        MachineBasicBlock *DispatchBB, int FI) const {
6425   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6426   DebugLoc dl = MI->getDebugLoc();
6427   MachineFunction *MF = MBB->getParent();
6428   MachineRegisterInfo *MRI = &MF->getRegInfo();
6429   MachineConstantPool *MCP = MF->getConstantPool();
6430   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6431   const Function *F = MF->getFunction();
6432
6433   bool isThumb = Subtarget->isThumb();
6434   bool isThumb2 = Subtarget->isThumb2();
6435
6436   unsigned PCLabelId = AFI->createPICLabelUId();
6437   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6438   ARMConstantPoolValue *CPV =
6439     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6440   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6441
6442   const TargetRegisterClass *TRC = isThumb ?
6443     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6444     (const TargetRegisterClass*)&ARM::GPRRegClass;
6445
6446   // Grab constant pool and fixed stack memory operands.
6447   MachineMemOperand *CPMMO =
6448     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6449                              MachineMemOperand::MOLoad, 4, 4);
6450
6451   MachineMemOperand *FIMMOSt =
6452     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6453                              MachineMemOperand::MOStore, 4, 4);
6454
6455   // Load the address of the dispatch MBB into the jump buffer.
6456   if (isThumb2) {
6457     // Incoming value: jbuf
6458     //   ldr.n  r5, LCPI1_1
6459     //   orr    r5, r5, #1
6460     //   add    r5, pc
6461     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6462     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6463     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6464                    .addConstantPoolIndex(CPI)
6465                    .addMemOperand(CPMMO));
6466     // Set the low bit because of thumb mode.
6467     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6468     AddDefaultCC(
6469       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6470                      .addReg(NewVReg1, RegState::Kill)
6471                      .addImm(0x01)));
6472     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6473     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6474       .addReg(NewVReg2, RegState::Kill)
6475       .addImm(PCLabelId);
6476     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6477                    .addReg(NewVReg3, RegState::Kill)
6478                    .addFrameIndex(FI)
6479                    .addImm(36)  // &jbuf[1] :: pc
6480                    .addMemOperand(FIMMOSt));
6481   } else if (isThumb) {
6482     // Incoming value: jbuf
6483     //   ldr.n  r1, LCPI1_4
6484     //   add    r1, pc
6485     //   mov    r2, #1
6486     //   orrs   r1, r2
6487     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6488     //   str    r1, [r2]
6489     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6490     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6491                    .addConstantPoolIndex(CPI)
6492                    .addMemOperand(CPMMO));
6493     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6494     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6495       .addReg(NewVReg1, RegState::Kill)
6496       .addImm(PCLabelId);
6497     // Set the low bit because of thumb mode.
6498     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6499     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6500                    .addReg(ARM::CPSR, RegState::Define)
6501                    .addImm(1));
6502     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6503     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6504                    .addReg(ARM::CPSR, RegState::Define)
6505                    .addReg(NewVReg2, RegState::Kill)
6506                    .addReg(NewVReg3, RegState::Kill));
6507     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6508     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6509                    .addFrameIndex(FI)
6510                    .addImm(36)); // &jbuf[1] :: pc
6511     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6512                    .addReg(NewVReg4, RegState::Kill)
6513                    .addReg(NewVReg5, RegState::Kill)
6514                    .addImm(0)
6515                    .addMemOperand(FIMMOSt));
6516   } else {
6517     // Incoming value: jbuf
6518     //   ldr  r1, LCPI1_1
6519     //   add  r1, pc, r1
6520     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6521     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6522     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6523                    .addConstantPoolIndex(CPI)
6524                    .addImm(0)
6525                    .addMemOperand(CPMMO));
6526     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6527     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6528                    .addReg(NewVReg1, RegState::Kill)
6529                    .addImm(PCLabelId));
6530     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6531                    .addReg(NewVReg2, RegState::Kill)
6532                    .addFrameIndex(FI)
6533                    .addImm(36)  // &jbuf[1] :: pc
6534                    .addMemOperand(FIMMOSt));
6535   }
6536 }
6537
6538 MachineBasicBlock *ARMTargetLowering::
6539 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6540   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6541   DebugLoc dl = MI->getDebugLoc();
6542   MachineFunction *MF = MBB->getParent();
6543   MachineRegisterInfo *MRI = &MF->getRegInfo();
6544   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6545   MachineFrameInfo *MFI = MF->getFrameInfo();
6546   int FI = MFI->getFunctionContextIndex();
6547
6548   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6549     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6550     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6551
6552   // Get a mapping of the call site numbers to all of the landing pads they're
6553   // associated with.
6554   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6555   unsigned MaxCSNum = 0;
6556   MachineModuleInfo &MMI = MF->getMMI();
6557   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6558        ++BB) {
6559     if (!BB->isLandingPad()) continue;
6560
6561     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6562     // pad.
6563     for (MachineBasicBlock::iterator
6564            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6565       if (!II->isEHLabel()) continue;
6566
6567       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6568       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6569
6570       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6571       for (SmallVectorImpl<unsigned>::iterator
6572              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6573            CSI != CSE; ++CSI) {
6574         CallSiteNumToLPad[*CSI].push_back(BB);
6575         MaxCSNum = std::max(MaxCSNum, *CSI);
6576       }
6577       break;
6578     }
6579   }
6580
6581   // Get an ordered list of the machine basic blocks for the jump table.
6582   std::vector<MachineBasicBlock*> LPadList;
6583   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6584   LPadList.reserve(CallSiteNumToLPad.size());
6585   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6586     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6587     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6588            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6589       LPadList.push_back(*II);
6590       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6591     }
6592   }
6593
6594   assert(!LPadList.empty() &&
6595          "No landing pad destinations for the dispatch jump table!");
6596
6597   // Create the jump table and associated information.
6598   MachineJumpTableInfo *JTI =
6599     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6600   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6601   unsigned UId = AFI->createJumpTableUId();
6602   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6603
6604   // Create the MBBs for the dispatch code.
6605
6606   // Shove the dispatch's address into the return slot in the function context.
6607   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6608   DispatchBB->setIsLandingPad();
6609
6610   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6611   unsigned trap_opcode;
6612   if (Subtarget->isThumb())
6613     trap_opcode = ARM::tTRAP;
6614   else
6615     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6616
6617   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6618   DispatchBB->addSuccessor(TrapBB);
6619
6620   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6621   DispatchBB->addSuccessor(DispContBB);
6622
6623   // Insert and MBBs.
6624   MF->insert(MF->end(), DispatchBB);
6625   MF->insert(MF->end(), DispContBB);
6626   MF->insert(MF->end(), TrapBB);
6627
6628   // Insert code into the entry block that creates and registers the function
6629   // context.
6630   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6631
6632   MachineMemOperand *FIMMOLd =
6633     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6634                              MachineMemOperand::MOLoad |
6635                              MachineMemOperand::MOVolatile, 4, 4);
6636
6637   MachineInstrBuilder MIB;
6638   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6639
6640   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6641   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6642
6643   // Add a register mask with no preserved registers.  This results in all
6644   // registers being marked as clobbered.
6645   MIB.addRegMask(RI.getNoPreservedMask());
6646
6647   unsigned NumLPads = LPadList.size();
6648   if (Subtarget->isThumb2()) {
6649     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6650     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6651                    .addFrameIndex(FI)
6652                    .addImm(4)
6653                    .addMemOperand(FIMMOLd));
6654
6655     if (NumLPads < 256) {
6656       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6657                      .addReg(NewVReg1)
6658                      .addImm(LPadList.size()));
6659     } else {
6660       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6661       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6662                      .addImm(NumLPads & 0xFFFF));
6663
6664       unsigned VReg2 = VReg1;
6665       if ((NumLPads & 0xFFFF0000) != 0) {
6666         VReg2 = MRI->createVirtualRegister(TRC);
6667         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6668                        .addReg(VReg1)
6669                        .addImm(NumLPads >> 16));
6670       }
6671
6672       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6673                      .addReg(NewVReg1)
6674                      .addReg(VReg2));
6675     }
6676
6677     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6678       .addMBB(TrapBB)
6679       .addImm(ARMCC::HI)
6680       .addReg(ARM::CPSR);
6681
6682     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6683     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6684                    .addJumpTableIndex(MJTI)
6685                    .addImm(UId));
6686
6687     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6688     AddDefaultCC(
6689       AddDefaultPred(
6690         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6691         .addReg(NewVReg3, RegState::Kill)
6692         .addReg(NewVReg1)
6693         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6694
6695     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6696       .addReg(NewVReg4, RegState::Kill)
6697       .addReg(NewVReg1)
6698       .addJumpTableIndex(MJTI)
6699       .addImm(UId);
6700   } else if (Subtarget->isThumb()) {
6701     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6702     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6703                    .addFrameIndex(FI)
6704                    .addImm(1)
6705                    .addMemOperand(FIMMOLd));
6706
6707     if (NumLPads < 256) {
6708       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6709                      .addReg(NewVReg1)
6710                      .addImm(NumLPads));
6711     } else {
6712       MachineConstantPool *ConstantPool = MF->getConstantPool();
6713       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6714       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6715
6716       // MachineConstantPool wants an explicit alignment.
6717       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6718       if (Align == 0)
6719         Align = getDataLayout()->getTypeAllocSize(C->getType());
6720       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6721
6722       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6723       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6724                      .addReg(VReg1, RegState::Define)
6725                      .addConstantPoolIndex(Idx));
6726       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6727                      .addReg(NewVReg1)
6728                      .addReg(VReg1));
6729     }
6730
6731     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6732       .addMBB(TrapBB)
6733       .addImm(ARMCC::HI)
6734       .addReg(ARM::CPSR);
6735
6736     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6737     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6738                    .addReg(ARM::CPSR, RegState::Define)
6739                    .addReg(NewVReg1)
6740                    .addImm(2));
6741
6742     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6743     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6744                    .addJumpTableIndex(MJTI)
6745                    .addImm(UId));
6746
6747     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6748     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6749                    .addReg(ARM::CPSR, RegState::Define)
6750                    .addReg(NewVReg2, RegState::Kill)
6751                    .addReg(NewVReg3));
6752
6753     MachineMemOperand *JTMMOLd =
6754       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6755                                MachineMemOperand::MOLoad, 4, 4);
6756
6757     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6758     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6759                    .addReg(NewVReg4, RegState::Kill)
6760                    .addImm(0)
6761                    .addMemOperand(JTMMOLd));
6762
6763     unsigned NewVReg6 = NewVReg5;
6764     if (RelocM == Reloc::PIC_) {
6765       NewVReg6 = MRI->createVirtualRegister(TRC);
6766       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6767                      .addReg(ARM::CPSR, RegState::Define)
6768                      .addReg(NewVReg5, RegState::Kill)
6769                      .addReg(NewVReg3));
6770     }
6771
6772     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6773       .addReg(NewVReg6, RegState::Kill)
6774       .addJumpTableIndex(MJTI)
6775       .addImm(UId);
6776   } else {
6777     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6778     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6779                    .addFrameIndex(FI)
6780                    .addImm(4)
6781                    .addMemOperand(FIMMOLd));
6782
6783     if (NumLPads < 256) {
6784       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6785                      .addReg(NewVReg1)
6786                      .addImm(NumLPads));
6787     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6788       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6789       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6790                      .addImm(NumLPads & 0xFFFF));
6791
6792       unsigned VReg2 = VReg1;
6793       if ((NumLPads & 0xFFFF0000) != 0) {
6794         VReg2 = MRI->createVirtualRegister(TRC);
6795         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6796                        .addReg(VReg1)
6797                        .addImm(NumLPads >> 16));
6798       }
6799
6800       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6801                      .addReg(NewVReg1)
6802                      .addReg(VReg2));
6803     } else {
6804       MachineConstantPool *ConstantPool = MF->getConstantPool();
6805       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6806       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6807
6808       // MachineConstantPool wants an explicit alignment.
6809       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6810       if (Align == 0)
6811         Align = getDataLayout()->getTypeAllocSize(C->getType());
6812       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6813
6814       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6815       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6816                      .addReg(VReg1, RegState::Define)
6817                      .addConstantPoolIndex(Idx)
6818                      .addImm(0));
6819       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6820                      .addReg(NewVReg1)
6821                      .addReg(VReg1, RegState::Kill));
6822     }
6823
6824     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6825       .addMBB(TrapBB)
6826       .addImm(ARMCC::HI)
6827       .addReg(ARM::CPSR);
6828
6829     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6830     AddDefaultCC(
6831       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6832                      .addReg(NewVReg1)
6833                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6834     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6835     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6836                    .addJumpTableIndex(MJTI)
6837                    .addImm(UId));
6838
6839     MachineMemOperand *JTMMOLd =
6840       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6841                                MachineMemOperand::MOLoad, 4, 4);
6842     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6843     AddDefaultPred(
6844       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6845       .addReg(NewVReg3, RegState::Kill)
6846       .addReg(NewVReg4)
6847       .addImm(0)
6848       .addMemOperand(JTMMOLd));
6849
6850     if (RelocM == Reloc::PIC_) {
6851       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6852         .addReg(NewVReg5, RegState::Kill)
6853         .addReg(NewVReg4)
6854         .addJumpTableIndex(MJTI)
6855         .addImm(UId);
6856     } else {
6857       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6858         .addReg(NewVReg5, RegState::Kill)
6859         .addJumpTableIndex(MJTI)
6860         .addImm(UId);
6861     }
6862   }
6863
6864   // Add the jump table entries as successors to the MBB.
6865   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6866   for (std::vector<MachineBasicBlock*>::iterator
6867          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6868     MachineBasicBlock *CurMBB = *I;
6869     if (SeenMBBs.insert(CurMBB))
6870       DispContBB->addSuccessor(CurMBB);
6871   }
6872
6873   // N.B. the order the invoke BBs are processed in doesn't matter here.
6874   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6875   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6876   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6877          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6878     MachineBasicBlock *BB = *I;
6879
6880     // Remove the landing pad successor from the invoke block and replace it
6881     // with the new dispatch block.
6882     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6883                                                   BB->succ_end());
6884     while (!Successors.empty()) {
6885       MachineBasicBlock *SMBB = Successors.pop_back_val();
6886       if (SMBB->isLandingPad()) {
6887         BB->removeSuccessor(SMBB);
6888         MBBLPads.push_back(SMBB);
6889       }
6890     }
6891
6892     BB->addSuccessor(DispatchBB);
6893
6894     // Find the invoke call and mark all of the callee-saved registers as
6895     // 'implicit defined' so that they're spilled. This prevents code from
6896     // moving instructions to before the EH block, where they will never be
6897     // executed.
6898     for (MachineBasicBlock::reverse_iterator
6899            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6900       if (!II->isCall()) continue;
6901
6902       DenseMap<unsigned, bool> DefRegs;
6903       for (MachineInstr::mop_iterator
6904              OI = II->operands_begin(), OE = II->operands_end();
6905            OI != OE; ++OI) {
6906         if (!OI->isReg()) continue;
6907         DefRegs[OI->getReg()] = true;
6908       }
6909
6910       MachineInstrBuilder MIB(*MF, &*II);
6911
6912       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6913         unsigned Reg = SavedRegs[i];
6914         if (Subtarget->isThumb2() &&
6915             !ARM::tGPRRegClass.contains(Reg) &&
6916             !ARM::hGPRRegClass.contains(Reg))
6917           continue;
6918         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6919           continue;
6920         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6921           continue;
6922         if (!DefRegs[Reg])
6923           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6924       }
6925
6926       break;
6927     }
6928   }
6929
6930   // Mark all former landing pads as non-landing pads. The dispatch is the only
6931   // landing pad now.
6932   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6933          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6934     (*I)->setIsLandingPad(false);
6935
6936   // The instruction is gone now.
6937   MI->eraseFromParent();
6938
6939   return MBB;
6940 }
6941
6942 static
6943 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6944   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6945        E = MBB->succ_end(); I != E; ++I)
6946     if (*I != Succ)
6947       return *I;
6948   llvm_unreachable("Expecting a BB with two successors!");
6949 }
6950
6951 MachineBasicBlock *ARMTargetLowering::
6952 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6953   // This pseudo instruction has 3 operands: dst, src, size
6954   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6955   // Otherwise, we will generate unrolled scalar copies.
6956   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6957   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6958   MachineFunction::iterator It = BB;
6959   ++It;
6960
6961   unsigned dest = MI->getOperand(0).getReg();
6962   unsigned src = MI->getOperand(1).getReg();
6963   unsigned SizeVal = MI->getOperand(2).getImm();
6964   unsigned Align = MI->getOperand(3).getImm();
6965   DebugLoc dl = MI->getDebugLoc();
6966
6967   bool isThumb2 = Subtarget->isThumb2();
6968   MachineFunction *MF = BB->getParent();
6969   MachineRegisterInfo &MRI = MF->getRegInfo();
6970   unsigned ldrOpc, strOpc, UnitSize = 0;
6971
6972   const TargetRegisterClass *TRC = isThumb2 ?
6973     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6974     (const TargetRegisterClass*)&ARM::GPRRegClass;
6975   const TargetRegisterClass *TRC_Vec = 0;
6976
6977   if (Align & 1) {
6978     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6979     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6980     UnitSize = 1;
6981   } else if (Align & 2) {
6982     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6983     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6984     UnitSize = 2;
6985   } else {
6986     // Check whether we can use NEON instructions.
6987     if (!MF->getFunction()->getAttributes().
6988           hasAttribute(AttributeSet::FunctionIndex,
6989                        Attribute::NoImplicitFloat) &&
6990         Subtarget->hasNEON()) {
6991       if ((Align % 16 == 0) && SizeVal >= 16) {
6992         ldrOpc = ARM::VLD1q32wb_fixed;
6993         strOpc = ARM::VST1q32wb_fixed;
6994         UnitSize = 16;
6995         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6996       }
6997       else if ((Align % 8 == 0) && SizeVal >= 8) {
6998         ldrOpc = ARM::VLD1d32wb_fixed;
6999         strOpc = ARM::VST1d32wb_fixed;
7000         UnitSize = 8;
7001         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7002       }
7003     }
7004     // Can't use NEON instructions.
7005     if (UnitSize == 0) {
7006       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7007       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7008       UnitSize = 4;
7009     }
7010   }
7011
7012   unsigned BytesLeft = SizeVal % UnitSize;
7013   unsigned LoopSize = SizeVal - BytesLeft;
7014
7015   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7016     // Use LDR and STR to copy.
7017     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7018     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7019     unsigned srcIn = src;
7020     unsigned destIn = dest;
7021     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7022       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7023       unsigned srcOut = MRI.createVirtualRegister(TRC);
7024       unsigned destOut = MRI.createVirtualRegister(TRC);
7025       if (UnitSize >= 8) {
7026         AddDefaultPred(BuildMI(*BB, MI, dl,
7027           TII->get(ldrOpc), scratch)
7028           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7029
7030         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7031           .addReg(destIn).addImm(0).addReg(scratch));
7032       } else if (isThumb2) {
7033         AddDefaultPred(BuildMI(*BB, MI, dl,
7034           TII->get(ldrOpc), scratch)
7035           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7036
7037         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7038           .addReg(scratch).addReg(destIn)
7039           .addImm(UnitSize));
7040       } else {
7041         AddDefaultPred(BuildMI(*BB, MI, dl,
7042           TII->get(ldrOpc), scratch)
7043           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7044           .addImm(UnitSize));
7045
7046         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7047           .addReg(scratch).addReg(destIn)
7048           .addReg(0).addImm(UnitSize));
7049       }
7050       srcIn = srcOut;
7051       destIn = destOut;
7052     }
7053
7054     // Handle the leftover bytes with LDRB and STRB.
7055     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7056     // [destOut] = STRB_POST(scratch, destIn, 1)
7057     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7058     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7059     for (unsigned i = 0; i < BytesLeft; i++) {
7060       unsigned scratch = MRI.createVirtualRegister(TRC);
7061       unsigned srcOut = MRI.createVirtualRegister(TRC);
7062       unsigned destOut = MRI.createVirtualRegister(TRC);
7063       if (isThumb2) {
7064         AddDefaultPred(BuildMI(*BB, MI, dl,
7065           TII->get(ldrOpc),scratch)
7066           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7067
7068         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7069           .addReg(scratch).addReg(destIn)
7070           .addReg(0).addImm(1));
7071       } else {
7072         AddDefaultPred(BuildMI(*BB, MI, dl,
7073           TII->get(ldrOpc),scratch)
7074           .addReg(srcOut, RegState::Define).addReg(srcIn)
7075           .addReg(0).addImm(1));
7076
7077         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7078           .addReg(scratch).addReg(destIn)
7079           .addReg(0).addImm(1));
7080       }
7081       srcIn = srcOut;
7082       destIn = destOut;
7083     }
7084     MI->eraseFromParent();   // The instruction is gone now.
7085     return BB;
7086   }
7087
7088   // Expand the pseudo op to a loop.
7089   // thisMBB:
7090   //   ...
7091   //   movw varEnd, # --> with thumb2
7092   //   movt varEnd, #
7093   //   ldrcp varEnd, idx --> without thumb2
7094   //   fallthrough --> loopMBB
7095   // loopMBB:
7096   //   PHI varPhi, varEnd, varLoop
7097   //   PHI srcPhi, src, srcLoop
7098   //   PHI destPhi, dst, destLoop
7099   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7100   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7101   //   subs varLoop, varPhi, #UnitSize
7102   //   bne loopMBB
7103   //   fallthrough --> exitMBB
7104   // exitMBB:
7105   //   epilogue to handle left-over bytes
7106   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7107   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7108   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7109   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7110   MF->insert(It, loopMBB);
7111   MF->insert(It, exitMBB);
7112
7113   // Transfer the remainder of BB and its successor edges to exitMBB.
7114   exitMBB->splice(exitMBB->begin(), BB,
7115                   llvm::next(MachineBasicBlock::iterator(MI)),
7116                   BB->end());
7117   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7118
7119   // Load an immediate to varEnd.
7120   unsigned varEnd = MRI.createVirtualRegister(TRC);
7121   if (isThumb2) {
7122     unsigned VReg1 = varEnd;
7123     if ((LoopSize & 0xFFFF0000) != 0)
7124       VReg1 = MRI.createVirtualRegister(TRC);
7125     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7126                    .addImm(LoopSize & 0xFFFF));
7127
7128     if ((LoopSize & 0xFFFF0000) != 0)
7129       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7130                      .addReg(VReg1)
7131                      .addImm(LoopSize >> 16));
7132   } else {
7133     MachineConstantPool *ConstantPool = MF->getConstantPool();
7134     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7135     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7136
7137     // MachineConstantPool wants an explicit alignment.
7138     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7139     if (Align == 0)
7140       Align = getDataLayout()->getTypeAllocSize(C->getType());
7141     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7142
7143     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7144                    .addReg(varEnd, RegState::Define)
7145                    .addConstantPoolIndex(Idx)
7146                    .addImm(0));
7147   }
7148   BB->addSuccessor(loopMBB);
7149
7150   // Generate the loop body:
7151   //   varPhi = PHI(varLoop, varEnd)
7152   //   srcPhi = PHI(srcLoop, src)
7153   //   destPhi = PHI(destLoop, dst)
7154   MachineBasicBlock *entryBB = BB;
7155   BB = loopMBB;
7156   unsigned varLoop = MRI.createVirtualRegister(TRC);
7157   unsigned varPhi = MRI.createVirtualRegister(TRC);
7158   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7159   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7160   unsigned destLoop = MRI.createVirtualRegister(TRC);
7161   unsigned destPhi = MRI.createVirtualRegister(TRC);
7162
7163   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7164     .addReg(varLoop).addMBB(loopMBB)
7165     .addReg(varEnd).addMBB(entryBB);
7166   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7167     .addReg(srcLoop).addMBB(loopMBB)
7168     .addReg(src).addMBB(entryBB);
7169   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7170     .addReg(destLoop).addMBB(loopMBB)
7171     .addReg(dest).addMBB(entryBB);
7172
7173   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7174   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7175   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7176   if (UnitSize >= 8) {
7177     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7178       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7179
7180     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7181       .addReg(destPhi).addImm(0).addReg(scratch));
7182   } else if (isThumb2) {
7183     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7184       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7185
7186     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7187       .addReg(scratch).addReg(destPhi)
7188       .addImm(UnitSize));
7189   } else {
7190     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7191       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7192       .addImm(UnitSize));
7193
7194     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7195       .addReg(scratch).addReg(destPhi)
7196       .addReg(0).addImm(UnitSize));
7197   }
7198
7199   // Decrement loop variable by UnitSize.
7200   MachineInstrBuilder MIB = BuildMI(BB, dl,
7201     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7202   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7203   MIB->getOperand(5).setReg(ARM::CPSR);
7204   MIB->getOperand(5).setIsDef(true);
7205
7206   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7207     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7208
7209   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7210   BB->addSuccessor(loopMBB);
7211   BB->addSuccessor(exitMBB);
7212
7213   // Add epilogue to handle BytesLeft.
7214   BB = exitMBB;
7215   MachineInstr *StartOfExit = exitMBB->begin();
7216   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7217   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7218
7219   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7220   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7221   unsigned srcIn = srcLoop;
7222   unsigned destIn = destLoop;
7223   for (unsigned i = 0; i < BytesLeft; i++) {
7224     unsigned scratch = MRI.createVirtualRegister(TRC);
7225     unsigned srcOut = MRI.createVirtualRegister(TRC);
7226     unsigned destOut = MRI.createVirtualRegister(TRC);
7227     if (isThumb2) {
7228       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7229         TII->get(ldrOpc),scratch)
7230         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7231
7232       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7233         .addReg(scratch).addReg(destIn)
7234         .addImm(1));
7235     } else {
7236       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7237         TII->get(ldrOpc),scratch)
7238         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7239
7240       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7241         .addReg(scratch).addReg(destIn)
7242         .addReg(0).addImm(1));
7243     }
7244     srcIn = srcOut;
7245     destIn = destOut;
7246   }
7247
7248   MI->eraseFromParent();   // The instruction is gone now.
7249   return BB;
7250 }
7251
7252 MachineBasicBlock *
7253 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7254                                                MachineBasicBlock *BB) const {
7255   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7256   DebugLoc dl = MI->getDebugLoc();
7257   bool isThumb2 = Subtarget->isThumb2();
7258   switch (MI->getOpcode()) {
7259   default: {
7260     MI->dump();
7261     llvm_unreachable("Unexpected instr type to insert");
7262   }
7263   // The Thumb2 pre-indexed stores have the same MI operands, they just
7264   // define them differently in the .td files from the isel patterns, so
7265   // they need pseudos.
7266   case ARM::t2STR_preidx:
7267     MI->setDesc(TII->get(ARM::t2STR_PRE));
7268     return BB;
7269   case ARM::t2STRB_preidx:
7270     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7271     return BB;
7272   case ARM::t2STRH_preidx:
7273     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7274     return BB;
7275
7276   case ARM::STRi_preidx:
7277   case ARM::STRBi_preidx: {
7278     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7279       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7280     // Decode the offset.
7281     unsigned Offset = MI->getOperand(4).getImm();
7282     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7283     Offset = ARM_AM::getAM2Offset(Offset);
7284     if (isSub)
7285       Offset = -Offset;
7286
7287     MachineMemOperand *MMO = *MI->memoperands_begin();
7288     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7289       .addOperand(MI->getOperand(0))  // Rn_wb
7290       .addOperand(MI->getOperand(1))  // Rt
7291       .addOperand(MI->getOperand(2))  // Rn
7292       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7293       .addOperand(MI->getOperand(5))  // pred
7294       .addOperand(MI->getOperand(6))
7295       .addMemOperand(MMO);
7296     MI->eraseFromParent();
7297     return BB;
7298   }
7299   case ARM::STRr_preidx:
7300   case ARM::STRBr_preidx:
7301   case ARM::STRH_preidx: {
7302     unsigned NewOpc;
7303     switch (MI->getOpcode()) {
7304     default: llvm_unreachable("unexpected opcode!");
7305     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7306     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7307     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7308     }
7309     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7310     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7311       MIB.addOperand(MI->getOperand(i));
7312     MI->eraseFromParent();
7313     return BB;
7314   }
7315   case ARM::ATOMIC_LOAD_ADD_I8:
7316      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7317   case ARM::ATOMIC_LOAD_ADD_I16:
7318      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7319   case ARM::ATOMIC_LOAD_ADD_I32:
7320      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7321
7322   case ARM::ATOMIC_LOAD_AND_I8:
7323      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7324   case ARM::ATOMIC_LOAD_AND_I16:
7325      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7326   case ARM::ATOMIC_LOAD_AND_I32:
7327      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7328
7329   case ARM::ATOMIC_LOAD_OR_I8:
7330      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7331   case ARM::ATOMIC_LOAD_OR_I16:
7332      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7333   case ARM::ATOMIC_LOAD_OR_I32:
7334      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7335
7336   case ARM::ATOMIC_LOAD_XOR_I8:
7337      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7338   case ARM::ATOMIC_LOAD_XOR_I16:
7339      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7340   case ARM::ATOMIC_LOAD_XOR_I32:
7341      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7342
7343   case ARM::ATOMIC_LOAD_NAND_I8:
7344      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7345   case ARM::ATOMIC_LOAD_NAND_I16:
7346      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7347   case ARM::ATOMIC_LOAD_NAND_I32:
7348      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7349
7350   case ARM::ATOMIC_LOAD_SUB_I8:
7351      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7352   case ARM::ATOMIC_LOAD_SUB_I16:
7353      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7354   case ARM::ATOMIC_LOAD_SUB_I32:
7355      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7356
7357   case ARM::ATOMIC_LOAD_MIN_I8:
7358      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7359   case ARM::ATOMIC_LOAD_MIN_I16:
7360      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7361   case ARM::ATOMIC_LOAD_MIN_I32:
7362      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7363
7364   case ARM::ATOMIC_LOAD_MAX_I8:
7365      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7366   case ARM::ATOMIC_LOAD_MAX_I16:
7367      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7368   case ARM::ATOMIC_LOAD_MAX_I32:
7369      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7370
7371   case ARM::ATOMIC_LOAD_UMIN_I8:
7372      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7373   case ARM::ATOMIC_LOAD_UMIN_I16:
7374      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7375   case ARM::ATOMIC_LOAD_UMIN_I32:
7376      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7377
7378   case ARM::ATOMIC_LOAD_UMAX_I8:
7379      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7380   case ARM::ATOMIC_LOAD_UMAX_I16:
7381      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7382   case ARM::ATOMIC_LOAD_UMAX_I32:
7383      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7384
7385   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7386   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7387   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7388
7389   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7390   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7391   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7392
7393
7394   case ARM::ATOMADD6432:
7395     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7396                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7397                               /*NeedsCarry*/ true);
7398   case ARM::ATOMSUB6432:
7399     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7400                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7401                               /*NeedsCarry*/ true);
7402   case ARM::ATOMOR6432:
7403     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7404                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7405   case ARM::ATOMXOR6432:
7406     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7407                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7408   case ARM::ATOMAND6432:
7409     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7410                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7411   case ARM::ATOMSWAP6432:
7412     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7413   case ARM::ATOMCMPXCHG6432:
7414     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7415                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7416                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7417   case ARM::ATOMMIN6432:
7418     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7419                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7420                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7421                               /*IsMinMax*/ true, ARMCC::LT);
7422   case ARM::ATOMMAX6432:
7423     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7424                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7425                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7426                               /*IsMinMax*/ true, ARMCC::GE);
7427   case ARM::ATOMUMIN6432:
7428     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7429                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7430                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7431                               /*IsMinMax*/ true, ARMCC::LO);
7432   case ARM::ATOMUMAX6432:
7433     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7434                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7435                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7436                               /*IsMinMax*/ true, ARMCC::HS);
7437
7438   case ARM::tMOVCCr_pseudo: {
7439     // To "insert" a SELECT_CC instruction, we actually have to insert the
7440     // diamond control-flow pattern.  The incoming instruction knows the
7441     // destination vreg to set, the condition code register to branch on, the
7442     // true/false values to select between, and a branch opcode to use.
7443     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7444     MachineFunction::iterator It = BB;
7445     ++It;
7446
7447     //  thisMBB:
7448     //  ...
7449     //   TrueVal = ...
7450     //   cmpTY ccX, r1, r2
7451     //   bCC copy1MBB
7452     //   fallthrough --> copy0MBB
7453     MachineBasicBlock *thisMBB  = BB;
7454     MachineFunction *F = BB->getParent();
7455     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7456     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7457     F->insert(It, copy0MBB);
7458     F->insert(It, sinkMBB);
7459
7460     // Transfer the remainder of BB and its successor edges to sinkMBB.
7461     sinkMBB->splice(sinkMBB->begin(), BB,
7462                     llvm::next(MachineBasicBlock::iterator(MI)),
7463                     BB->end());
7464     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7465
7466     BB->addSuccessor(copy0MBB);
7467     BB->addSuccessor(sinkMBB);
7468
7469     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7470       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7471
7472     //  copy0MBB:
7473     //   %FalseValue = ...
7474     //   # fallthrough to sinkMBB
7475     BB = copy0MBB;
7476
7477     // Update machine-CFG edges
7478     BB->addSuccessor(sinkMBB);
7479
7480     //  sinkMBB:
7481     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7482     //  ...
7483     BB = sinkMBB;
7484     BuildMI(*BB, BB->begin(), dl,
7485             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7486       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7487       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7488
7489     MI->eraseFromParent();   // The pseudo instruction is gone now.
7490     return BB;
7491   }
7492
7493   case ARM::BCCi64:
7494   case ARM::BCCZi64: {
7495     // If there is an unconditional branch to the other successor, remove it.
7496     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7497
7498     // Compare both parts that make up the double comparison separately for
7499     // equality.
7500     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7501
7502     unsigned LHS1 = MI->getOperand(1).getReg();
7503     unsigned LHS2 = MI->getOperand(2).getReg();
7504     if (RHSisZero) {
7505       AddDefaultPred(BuildMI(BB, dl,
7506                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7507                      .addReg(LHS1).addImm(0));
7508       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7509         .addReg(LHS2).addImm(0)
7510         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7511     } else {
7512       unsigned RHS1 = MI->getOperand(3).getReg();
7513       unsigned RHS2 = MI->getOperand(4).getReg();
7514       AddDefaultPred(BuildMI(BB, dl,
7515                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7516                      .addReg(LHS1).addReg(RHS1));
7517       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7518         .addReg(LHS2).addReg(RHS2)
7519         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7520     }
7521
7522     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7523     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7524     if (MI->getOperand(0).getImm() == ARMCC::NE)
7525       std::swap(destMBB, exitMBB);
7526
7527     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7528       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7529     if (isThumb2)
7530       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7531     else
7532       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7533
7534     MI->eraseFromParent();   // The pseudo instruction is gone now.
7535     return BB;
7536   }
7537
7538   case ARM::Int_eh_sjlj_setjmp:
7539   case ARM::Int_eh_sjlj_setjmp_nofp:
7540   case ARM::tInt_eh_sjlj_setjmp:
7541   case ARM::t2Int_eh_sjlj_setjmp:
7542   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7543     EmitSjLjDispatchBlock(MI, BB);
7544     return BB;
7545
7546   case ARM::ABS:
7547   case ARM::t2ABS: {
7548     // To insert an ABS instruction, we have to insert the
7549     // diamond control-flow pattern.  The incoming instruction knows the
7550     // source vreg to test against 0, the destination vreg to set,
7551     // the condition code register to branch on, the
7552     // true/false values to select between, and a branch opcode to use.
7553     // It transforms
7554     //     V1 = ABS V0
7555     // into
7556     //     V2 = MOVS V0
7557     //     BCC                      (branch to SinkBB if V0 >= 0)
7558     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7559     //     SinkBB: V1 = PHI(V2, V3)
7560     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7561     MachineFunction::iterator BBI = BB;
7562     ++BBI;
7563     MachineFunction *Fn = BB->getParent();
7564     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7565     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7566     Fn->insert(BBI, RSBBB);
7567     Fn->insert(BBI, SinkBB);
7568
7569     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7570     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7571     bool isThumb2 = Subtarget->isThumb2();
7572     MachineRegisterInfo &MRI = Fn->getRegInfo();
7573     // In Thumb mode S must not be specified if source register is the SP or
7574     // PC and if destination register is the SP, so restrict register class
7575     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7576       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7577       (const TargetRegisterClass*)&ARM::GPRRegClass);
7578
7579     // Transfer the remainder of BB and its successor edges to sinkMBB.
7580     SinkBB->splice(SinkBB->begin(), BB,
7581       llvm::next(MachineBasicBlock::iterator(MI)),
7582       BB->end());
7583     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7584
7585     BB->addSuccessor(RSBBB);
7586     BB->addSuccessor(SinkBB);
7587
7588     // fall through to SinkMBB
7589     RSBBB->addSuccessor(SinkBB);
7590
7591     // insert a cmp at the end of BB
7592     AddDefaultPred(BuildMI(BB, dl,
7593                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7594                    .addReg(ABSSrcReg).addImm(0));
7595
7596     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7597     BuildMI(BB, dl,
7598       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7599       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7600
7601     // insert rsbri in RSBBB
7602     // Note: BCC and rsbri will be converted into predicated rsbmi
7603     // by if-conversion pass
7604     BuildMI(*RSBBB, RSBBB->begin(), dl,
7605       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7606       .addReg(ABSSrcReg, RegState::Kill)
7607       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7608
7609     // insert PHI in SinkBB,
7610     // reuse ABSDstReg to not change uses of ABS instruction
7611     BuildMI(*SinkBB, SinkBB->begin(), dl,
7612       TII->get(ARM::PHI), ABSDstReg)
7613       .addReg(NewRsbDstReg).addMBB(RSBBB)
7614       .addReg(ABSSrcReg).addMBB(BB);
7615
7616     // remove ABS instruction
7617     MI->eraseFromParent();
7618
7619     // return last added BB
7620     return SinkBB;
7621   }
7622   case ARM::COPY_STRUCT_BYVAL_I32:
7623     ++NumLoopByVals;
7624     return EmitStructByval(MI, BB);
7625   }
7626 }
7627
7628 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7629                                                       SDNode *Node) const {
7630   if (!MI->hasPostISelHook()) {
7631     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7632            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7633     return;
7634   }
7635
7636   const MCInstrDesc *MCID = &MI->getDesc();
7637   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7638   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7639   // operand is still set to noreg. If needed, set the optional operand's
7640   // register to CPSR, and remove the redundant implicit def.
7641   //
7642   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7643
7644   // Rename pseudo opcodes.
7645   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7646   if (NewOpc) {
7647     const ARMBaseInstrInfo *TII =
7648       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7649     MCID = &TII->get(NewOpc);
7650
7651     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7652            "converted opcode should be the same except for cc_out");
7653
7654     MI->setDesc(*MCID);
7655
7656     // Add the optional cc_out operand
7657     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7658   }
7659   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7660
7661   // Any ARM instruction that sets the 's' bit should specify an optional
7662   // "cc_out" operand in the last operand position.
7663   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7664     assert(!NewOpc && "Optional cc_out operand required");
7665     return;
7666   }
7667   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7668   // since we already have an optional CPSR def.
7669   bool definesCPSR = false;
7670   bool deadCPSR = false;
7671   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7672        i != e; ++i) {
7673     const MachineOperand &MO = MI->getOperand(i);
7674     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7675       definesCPSR = true;
7676       if (MO.isDead())
7677         deadCPSR = true;
7678       MI->RemoveOperand(i);
7679       break;
7680     }
7681   }
7682   if (!definesCPSR) {
7683     assert(!NewOpc && "Optional cc_out operand required");
7684     return;
7685   }
7686   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7687   if (deadCPSR) {
7688     assert(!MI->getOperand(ccOutIdx).getReg() &&
7689            "expect uninitialized optional cc_out operand");
7690     return;
7691   }
7692
7693   // If this instruction was defined with an optional CPSR def and its dag node
7694   // had a live implicit CPSR def, then activate the optional CPSR def.
7695   MachineOperand &MO = MI->getOperand(ccOutIdx);
7696   MO.setReg(ARM::CPSR);
7697   MO.setIsDef(true);
7698 }
7699
7700 //===----------------------------------------------------------------------===//
7701 //                           ARM Optimization Hooks
7702 //===----------------------------------------------------------------------===//
7703
7704 // Helper function that checks if N is a null or all ones constant.
7705 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7706   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7707   if (!C)
7708     return false;
7709   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7710 }
7711
7712 // Return true if N is conditionally 0 or all ones.
7713 // Detects these expressions where cc is an i1 value:
7714 //
7715 //   (select cc 0, y)   [AllOnes=0]
7716 //   (select cc y, 0)   [AllOnes=0]
7717 //   (zext cc)          [AllOnes=0]
7718 //   (sext cc)          [AllOnes=0/1]
7719 //   (select cc -1, y)  [AllOnes=1]
7720 //   (select cc y, -1)  [AllOnes=1]
7721 //
7722 // Invert is set when N is the null/all ones constant when CC is false.
7723 // OtherOp is set to the alternative value of N.
7724 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7725                                        SDValue &CC, bool &Invert,
7726                                        SDValue &OtherOp,
7727                                        SelectionDAG &DAG) {
7728   switch (N->getOpcode()) {
7729   default: return false;
7730   case ISD::SELECT: {
7731     CC = N->getOperand(0);
7732     SDValue N1 = N->getOperand(1);
7733     SDValue N2 = N->getOperand(2);
7734     if (isZeroOrAllOnes(N1, AllOnes)) {
7735       Invert = false;
7736       OtherOp = N2;
7737       return true;
7738     }
7739     if (isZeroOrAllOnes(N2, AllOnes)) {
7740       Invert = true;
7741       OtherOp = N1;
7742       return true;
7743     }
7744     return false;
7745   }
7746   case ISD::ZERO_EXTEND:
7747     // (zext cc) can never be the all ones value.
7748     if (AllOnes)
7749       return false;
7750     // Fall through.
7751   case ISD::SIGN_EXTEND: {
7752     EVT VT = N->getValueType(0);
7753     CC = N->getOperand(0);
7754     if (CC.getValueType() != MVT::i1)
7755       return false;
7756     Invert = !AllOnes;
7757     if (AllOnes)
7758       // When looking for an AllOnes constant, N is an sext, and the 'other'
7759       // value is 0.
7760       OtherOp = DAG.getConstant(0, VT);
7761     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7762       // When looking for a 0 constant, N can be zext or sext.
7763       OtherOp = DAG.getConstant(1, VT);
7764     else
7765       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7766     return true;
7767   }
7768   }
7769 }
7770
7771 // Combine a constant select operand into its use:
7772 //
7773 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7774 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7775 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7776 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7777 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7778 //
7779 // The transform is rejected if the select doesn't have a constant operand that
7780 // is null, or all ones when AllOnes is set.
7781 //
7782 // Also recognize sext/zext from i1:
7783 //
7784 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7785 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7786 //
7787 // These transformations eventually create predicated instructions.
7788 //
7789 // @param N       The node to transform.
7790 // @param Slct    The N operand that is a select.
7791 // @param OtherOp The other N operand (x above).
7792 // @param DCI     Context.
7793 // @param AllOnes Require the select constant to be all ones instead of null.
7794 // @returns The new node, or SDValue() on failure.
7795 static
7796 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7797                             TargetLowering::DAGCombinerInfo &DCI,
7798                             bool AllOnes = false) {
7799   SelectionDAG &DAG = DCI.DAG;
7800   EVT VT = N->getValueType(0);
7801   SDValue NonConstantVal;
7802   SDValue CCOp;
7803   bool SwapSelectOps;
7804   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7805                                   NonConstantVal, DAG))
7806     return SDValue();
7807
7808   // Slct is now know to be the desired identity constant when CC is true.
7809   SDValue TrueVal = OtherOp;
7810   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7811                                  OtherOp, NonConstantVal);
7812   // Unless SwapSelectOps says CC should be false.
7813   if (SwapSelectOps)
7814     std::swap(TrueVal, FalseVal);
7815
7816   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7817                      CCOp, TrueVal, FalseVal);
7818 }
7819
7820 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7821 static
7822 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7823                                        TargetLowering::DAGCombinerInfo &DCI) {
7824   SDValue N0 = N->getOperand(0);
7825   SDValue N1 = N->getOperand(1);
7826   if (N0.getNode()->hasOneUse()) {
7827     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7828     if (Result.getNode())
7829       return Result;
7830   }
7831   if (N1.getNode()->hasOneUse()) {
7832     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7833     if (Result.getNode())
7834       return Result;
7835   }
7836   return SDValue();
7837 }
7838
7839 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7840 // (only after legalization).
7841 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7842                                  TargetLowering::DAGCombinerInfo &DCI,
7843                                  const ARMSubtarget *Subtarget) {
7844
7845   // Only perform optimization if after legalize, and if NEON is available. We
7846   // also expected both operands to be BUILD_VECTORs.
7847   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7848       || N0.getOpcode() != ISD::BUILD_VECTOR
7849       || N1.getOpcode() != ISD::BUILD_VECTOR)
7850     return SDValue();
7851
7852   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7853   EVT VT = N->getValueType(0);
7854   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7855     return SDValue();
7856
7857   // Check that the vector operands are of the right form.
7858   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7859   // operands, where N is the size of the formed vector.
7860   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7861   // index such that we have a pair wise add pattern.
7862
7863   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7864   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7865     return SDValue();
7866   SDValue Vec = N0->getOperand(0)->getOperand(0);
7867   SDNode *V = Vec.getNode();
7868   unsigned nextIndex = 0;
7869
7870   // For each operands to the ADD which are BUILD_VECTORs,
7871   // check to see if each of their operands are an EXTRACT_VECTOR with
7872   // the same vector and appropriate index.
7873   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7874     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7875         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7876
7877       SDValue ExtVec0 = N0->getOperand(i);
7878       SDValue ExtVec1 = N1->getOperand(i);
7879
7880       // First operand is the vector, verify its the same.
7881       if (V != ExtVec0->getOperand(0).getNode() ||
7882           V != ExtVec1->getOperand(0).getNode())
7883         return SDValue();
7884
7885       // Second is the constant, verify its correct.
7886       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7887       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7888
7889       // For the constant, we want to see all the even or all the odd.
7890       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7891           || C1->getZExtValue() != nextIndex+1)
7892         return SDValue();
7893
7894       // Increment index.
7895       nextIndex+=2;
7896     } else
7897       return SDValue();
7898   }
7899
7900   // Create VPADDL node.
7901   SelectionDAG &DAG = DCI.DAG;
7902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7903
7904   // Build operand list.
7905   SmallVector<SDValue, 8> Ops;
7906   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7907                                 TLI.getPointerTy()));
7908
7909   // Input is the vector.
7910   Ops.push_back(Vec);
7911
7912   // Get widened type and narrowed type.
7913   MVT widenType;
7914   unsigned numElem = VT.getVectorNumElements();
7915   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7916     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7917     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7918     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7919     default:
7920       llvm_unreachable("Invalid vector element type for padd optimization.");
7921   }
7922
7923   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7924                             widenType, &Ops[0], Ops.size());
7925   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
7926 }
7927
7928 static SDValue findMUL_LOHI(SDValue V) {
7929   if (V->getOpcode() == ISD::UMUL_LOHI ||
7930       V->getOpcode() == ISD::SMUL_LOHI)
7931     return V;
7932   return SDValue();
7933 }
7934
7935 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7936                                      TargetLowering::DAGCombinerInfo &DCI,
7937                                      const ARMSubtarget *Subtarget) {
7938
7939   if (Subtarget->isThumb1Only()) return SDValue();
7940
7941   // Only perform the checks after legalize when the pattern is available.
7942   if (DCI.isBeforeLegalize()) return SDValue();
7943
7944   // Look for multiply add opportunities.
7945   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7946   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7947   // a glue link from the first add to the second add.
7948   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7949   // a S/UMLAL instruction.
7950   //          loAdd   UMUL_LOHI
7951   //            \    / :lo    \ :hi
7952   //             \  /          \          [no multiline comment]
7953   //              ADDC         |  hiAdd
7954   //                 \ :glue  /  /
7955   //                  \      /  /
7956   //                    ADDE
7957   //
7958   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7959   SDValue AddcOp0 = AddcNode->getOperand(0);
7960   SDValue AddcOp1 = AddcNode->getOperand(1);
7961
7962   // Check if the two operands are from the same mul_lohi node.
7963   if (AddcOp0.getNode() == AddcOp1.getNode())
7964     return SDValue();
7965
7966   assert(AddcNode->getNumValues() == 2 &&
7967          AddcNode->getValueType(0) == MVT::i32 &&
7968          "Expect ADDC with two result values. First: i32");
7969
7970   // Check that we have a glued ADDC node.
7971   if (AddcNode->getValueType(1) != MVT::Glue)
7972     return SDValue();
7973
7974   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7975   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7976       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7977       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7978       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7979     return SDValue();
7980
7981   // Look for the glued ADDE.
7982   SDNode* AddeNode = AddcNode->getGluedUser();
7983   if (AddeNode == NULL)
7984     return SDValue();
7985
7986   // Make sure it is really an ADDE.
7987   if (AddeNode->getOpcode() != ISD::ADDE)
7988     return SDValue();
7989
7990   assert(AddeNode->getNumOperands() == 3 &&
7991          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7992          "ADDE node has the wrong inputs");
7993
7994   // Check for the triangle shape.
7995   SDValue AddeOp0 = AddeNode->getOperand(0);
7996   SDValue AddeOp1 = AddeNode->getOperand(1);
7997
7998   // Make sure that the ADDE operands are not coming from the same node.
7999   if (AddeOp0.getNode() == AddeOp1.getNode())
8000     return SDValue();
8001
8002   // Find the MUL_LOHI node walking up ADDE's operands.
8003   bool IsLeftOperandMUL = false;
8004   SDValue MULOp = findMUL_LOHI(AddeOp0);
8005   if (MULOp == SDValue())
8006    MULOp = findMUL_LOHI(AddeOp1);
8007   else
8008     IsLeftOperandMUL = true;
8009   if (MULOp == SDValue())
8010      return SDValue();
8011
8012   // Figure out the right opcode.
8013   unsigned Opc = MULOp->getOpcode();
8014   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8015
8016   // Figure out the high and low input values to the MLAL node.
8017   SDValue* HiMul = &MULOp;
8018   SDValue* HiAdd = NULL;
8019   SDValue* LoMul = NULL;
8020   SDValue* LowAdd = NULL;
8021
8022   if (IsLeftOperandMUL)
8023     HiAdd = &AddeOp1;
8024   else
8025     HiAdd = &AddeOp0;
8026
8027
8028   if (AddcOp0->getOpcode() == Opc) {
8029     LoMul = &AddcOp0;
8030     LowAdd = &AddcOp1;
8031   }
8032   if (AddcOp1->getOpcode() == Opc) {
8033     LoMul = &AddcOp1;
8034     LowAdd = &AddcOp0;
8035   }
8036
8037   if (LoMul == NULL)
8038     return SDValue();
8039
8040   if (LoMul->getNode() != HiMul->getNode())
8041     return SDValue();
8042
8043   // Create the merged node.
8044   SelectionDAG &DAG = DCI.DAG;
8045
8046   // Build operand list.
8047   SmallVector<SDValue, 8> Ops;
8048   Ops.push_back(LoMul->getOperand(0));
8049   Ops.push_back(LoMul->getOperand(1));
8050   Ops.push_back(*LowAdd);
8051   Ops.push_back(*HiAdd);
8052
8053   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8054                                  DAG.getVTList(MVT::i32, MVT::i32),
8055                                  &Ops[0], Ops.size());
8056
8057   // Replace the ADDs' nodes uses by the MLA node's values.
8058   SDValue HiMLALResult(MLALNode.getNode(), 1);
8059   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8060
8061   SDValue LoMLALResult(MLALNode.getNode(), 0);
8062   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8063
8064   // Return original node to notify the driver to stop replacing.
8065   SDValue resNode(AddcNode, 0);
8066   return resNode;
8067 }
8068
8069 /// PerformADDCCombine - Target-specific dag combine transform from
8070 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8071 static SDValue PerformADDCCombine(SDNode *N,
8072                                  TargetLowering::DAGCombinerInfo &DCI,
8073                                  const ARMSubtarget *Subtarget) {
8074
8075   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8076
8077 }
8078
8079 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8080 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8081 /// called with the default operands, and if that fails, with commuted
8082 /// operands.
8083 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8084                                           TargetLowering::DAGCombinerInfo &DCI,
8085                                           const ARMSubtarget *Subtarget){
8086
8087   // Attempt to create vpaddl for this add.
8088   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8089   if (Result.getNode())
8090     return Result;
8091
8092   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8093   if (N0.getNode()->hasOneUse()) {
8094     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8095     if (Result.getNode()) return Result;
8096   }
8097   return SDValue();
8098 }
8099
8100 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8101 ///
8102 static SDValue PerformADDCombine(SDNode *N,
8103                                  TargetLowering::DAGCombinerInfo &DCI,
8104                                  const ARMSubtarget *Subtarget) {
8105   SDValue N0 = N->getOperand(0);
8106   SDValue N1 = N->getOperand(1);
8107
8108   // First try with the default operand order.
8109   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8110   if (Result.getNode())
8111     return Result;
8112
8113   // If that didn't work, try again with the operands commuted.
8114   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8115 }
8116
8117 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8118 ///
8119 static SDValue PerformSUBCombine(SDNode *N,
8120                                  TargetLowering::DAGCombinerInfo &DCI) {
8121   SDValue N0 = N->getOperand(0);
8122   SDValue N1 = N->getOperand(1);
8123
8124   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8125   if (N1.getNode()->hasOneUse()) {
8126     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8127     if (Result.getNode()) return Result;
8128   }
8129
8130   return SDValue();
8131 }
8132
8133 /// PerformVMULCombine
8134 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8135 /// special multiplier accumulator forwarding.
8136 ///   vmul d3, d0, d2
8137 ///   vmla d3, d1, d2
8138 /// is faster than
8139 ///   vadd d3, d0, d1
8140 ///   vmul d3, d3, d2
8141 static SDValue PerformVMULCombine(SDNode *N,
8142                                   TargetLowering::DAGCombinerInfo &DCI,
8143                                   const ARMSubtarget *Subtarget) {
8144   if (!Subtarget->hasVMLxForwarding())
8145     return SDValue();
8146
8147   SelectionDAG &DAG = DCI.DAG;
8148   SDValue N0 = N->getOperand(0);
8149   SDValue N1 = N->getOperand(1);
8150   unsigned Opcode = N0.getOpcode();
8151   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8152       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8153     Opcode = N1.getOpcode();
8154     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8155         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8156       return SDValue();
8157     std::swap(N0, N1);
8158   }
8159
8160   EVT VT = N->getValueType(0);
8161   SDLoc DL(N);
8162   SDValue N00 = N0->getOperand(0);
8163   SDValue N01 = N0->getOperand(1);
8164   return DAG.getNode(Opcode, DL, VT,
8165                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8166                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8167 }
8168
8169 static SDValue PerformMULCombine(SDNode *N,
8170                                  TargetLowering::DAGCombinerInfo &DCI,
8171                                  const ARMSubtarget *Subtarget) {
8172   SelectionDAG &DAG = DCI.DAG;
8173
8174   if (Subtarget->isThumb1Only())
8175     return SDValue();
8176
8177   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8178     return SDValue();
8179
8180   EVT VT = N->getValueType(0);
8181   if (VT.is64BitVector() || VT.is128BitVector())
8182     return PerformVMULCombine(N, DCI, Subtarget);
8183   if (VT != MVT::i32)
8184     return SDValue();
8185
8186   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8187   if (!C)
8188     return SDValue();
8189
8190   int64_t MulAmt = C->getSExtValue();
8191   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8192
8193   ShiftAmt = ShiftAmt & (32 - 1);
8194   SDValue V = N->getOperand(0);
8195   SDLoc DL(N);
8196
8197   SDValue Res;
8198   MulAmt >>= ShiftAmt;
8199
8200   if (MulAmt >= 0) {
8201     if (isPowerOf2_32(MulAmt - 1)) {
8202       // (mul x, 2^N + 1) => (add (shl x, N), x)
8203       Res = DAG.getNode(ISD::ADD, DL, VT,
8204                         V,
8205                         DAG.getNode(ISD::SHL, DL, VT,
8206                                     V,
8207                                     DAG.getConstant(Log2_32(MulAmt - 1),
8208                                                     MVT::i32)));
8209     } else if (isPowerOf2_32(MulAmt + 1)) {
8210       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8211       Res = DAG.getNode(ISD::SUB, DL, VT,
8212                         DAG.getNode(ISD::SHL, DL, VT,
8213                                     V,
8214                                     DAG.getConstant(Log2_32(MulAmt + 1),
8215                                                     MVT::i32)),
8216                         V);
8217     } else
8218       return SDValue();
8219   } else {
8220     uint64_t MulAmtAbs = -MulAmt;
8221     if (isPowerOf2_32(MulAmtAbs + 1)) {
8222       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8223       Res = DAG.getNode(ISD::SUB, DL, VT,
8224                         V,
8225                         DAG.getNode(ISD::SHL, DL, VT,
8226                                     V,
8227                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8228                                                     MVT::i32)));
8229     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8230       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8231       Res = DAG.getNode(ISD::ADD, DL, VT,
8232                         V,
8233                         DAG.getNode(ISD::SHL, DL, VT,
8234                                     V,
8235                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8236                                                     MVT::i32)));
8237       Res = DAG.getNode(ISD::SUB, DL, VT,
8238                         DAG.getConstant(0, MVT::i32),Res);
8239
8240     } else
8241       return SDValue();
8242   }
8243
8244   if (ShiftAmt != 0)
8245     Res = DAG.getNode(ISD::SHL, DL, VT,
8246                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8247
8248   // Do not add new nodes to DAG combiner worklist.
8249   DCI.CombineTo(N, Res, false);
8250   return SDValue();
8251 }
8252
8253 static SDValue PerformANDCombine(SDNode *N,
8254                                  TargetLowering::DAGCombinerInfo &DCI,
8255                                  const ARMSubtarget *Subtarget) {
8256
8257   // Attempt to use immediate-form VBIC
8258   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8259   SDLoc dl(N);
8260   EVT VT = N->getValueType(0);
8261   SelectionDAG &DAG = DCI.DAG;
8262
8263   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8264     return SDValue();
8265
8266   APInt SplatBits, SplatUndef;
8267   unsigned SplatBitSize;
8268   bool HasAnyUndefs;
8269   if (BVN &&
8270       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8271     if (SplatBitSize <= 64) {
8272       EVT VbicVT;
8273       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8274                                       SplatUndef.getZExtValue(), SplatBitSize,
8275                                       DAG, VbicVT, VT.is128BitVector(),
8276                                       OtherModImm);
8277       if (Val.getNode()) {
8278         SDValue Input =
8279           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8280         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8281         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8282       }
8283     }
8284   }
8285
8286   if (!Subtarget->isThumb1Only()) {
8287     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8288     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8289     if (Result.getNode())
8290       return Result;
8291   }
8292
8293   return SDValue();
8294 }
8295
8296 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8297 static SDValue PerformORCombine(SDNode *N,
8298                                 TargetLowering::DAGCombinerInfo &DCI,
8299                                 const ARMSubtarget *Subtarget) {
8300   // Attempt to use immediate-form VORR
8301   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8302   SDLoc dl(N);
8303   EVT VT = N->getValueType(0);
8304   SelectionDAG &DAG = DCI.DAG;
8305
8306   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8307     return SDValue();
8308
8309   APInt SplatBits, SplatUndef;
8310   unsigned SplatBitSize;
8311   bool HasAnyUndefs;
8312   if (BVN && Subtarget->hasNEON() &&
8313       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8314     if (SplatBitSize <= 64) {
8315       EVT VorrVT;
8316       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8317                                       SplatUndef.getZExtValue(), SplatBitSize,
8318                                       DAG, VorrVT, VT.is128BitVector(),
8319                                       OtherModImm);
8320       if (Val.getNode()) {
8321         SDValue Input =
8322           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8323         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8324         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8325       }
8326     }
8327   }
8328
8329   if (!Subtarget->isThumb1Only()) {
8330     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8331     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8332     if (Result.getNode())
8333       return Result;
8334   }
8335
8336   // The code below optimizes (or (and X, Y), Z).
8337   // The AND operand needs to have a single user to make these optimizations
8338   // profitable.
8339   SDValue N0 = N->getOperand(0);
8340   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8341     return SDValue();
8342   SDValue N1 = N->getOperand(1);
8343
8344   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8345   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8346       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8347     APInt SplatUndef;
8348     unsigned SplatBitSize;
8349     bool HasAnyUndefs;
8350
8351     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8352     APInt SplatBits0;
8353     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8354                                   HasAnyUndefs) && !HasAnyUndefs) {
8355       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8356       APInt SplatBits1;
8357       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8358                                     HasAnyUndefs) && !HasAnyUndefs &&
8359           SplatBits0 == ~SplatBits1) {
8360         // Canonicalize the vector type to make instruction selection simpler.
8361         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8362         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8363                                      N0->getOperand(1), N0->getOperand(0),
8364                                      N1->getOperand(0));
8365         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8366       }
8367     }
8368   }
8369
8370   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8371   // reasonable.
8372
8373   // BFI is only available on V6T2+
8374   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8375     return SDValue();
8376
8377   SDLoc DL(N);
8378   // 1) or (and A, mask), val => ARMbfi A, val, mask
8379   //      iff (val & mask) == val
8380   //
8381   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8382   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8383   //          && mask == ~mask2
8384   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8385   //          && ~mask == mask2
8386   //  (i.e., copy a bitfield value into another bitfield of the same width)
8387
8388   if (VT != MVT::i32)
8389     return SDValue();
8390
8391   SDValue N00 = N0.getOperand(0);
8392
8393   // The value and the mask need to be constants so we can verify this is
8394   // actually a bitfield set. If the mask is 0xffff, we can do better
8395   // via a movt instruction, so don't use BFI in that case.
8396   SDValue MaskOp = N0.getOperand(1);
8397   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8398   if (!MaskC)
8399     return SDValue();
8400   unsigned Mask = MaskC->getZExtValue();
8401   if (Mask == 0xffff)
8402     return SDValue();
8403   SDValue Res;
8404   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8405   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8406   if (N1C) {
8407     unsigned Val = N1C->getZExtValue();
8408     if ((Val & ~Mask) != Val)
8409       return SDValue();
8410
8411     if (ARM::isBitFieldInvertedMask(Mask)) {
8412       Val >>= countTrailingZeros(~Mask);
8413
8414       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8415                         DAG.getConstant(Val, MVT::i32),
8416                         DAG.getConstant(Mask, MVT::i32));
8417
8418       // Do not add new nodes to DAG combiner worklist.
8419       DCI.CombineTo(N, Res, false);
8420       return SDValue();
8421     }
8422   } else if (N1.getOpcode() == ISD::AND) {
8423     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8424     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8425     if (!N11C)
8426       return SDValue();
8427     unsigned Mask2 = N11C->getZExtValue();
8428
8429     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8430     // as is to match.
8431     if (ARM::isBitFieldInvertedMask(Mask) &&
8432         (Mask == ~Mask2)) {
8433       // The pack halfword instruction works better for masks that fit it,
8434       // so use that when it's available.
8435       if (Subtarget->hasT2ExtractPack() &&
8436           (Mask == 0xffff || Mask == 0xffff0000))
8437         return SDValue();
8438       // 2a
8439       unsigned amt = countTrailingZeros(Mask2);
8440       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8441                         DAG.getConstant(amt, MVT::i32));
8442       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8443                         DAG.getConstant(Mask, MVT::i32));
8444       // Do not add new nodes to DAG combiner worklist.
8445       DCI.CombineTo(N, Res, false);
8446       return SDValue();
8447     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8448                (~Mask == Mask2)) {
8449       // The pack halfword instruction works better for masks that fit it,
8450       // so use that when it's available.
8451       if (Subtarget->hasT2ExtractPack() &&
8452           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8453         return SDValue();
8454       // 2b
8455       unsigned lsb = countTrailingZeros(Mask);
8456       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8457                         DAG.getConstant(lsb, MVT::i32));
8458       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8459                         DAG.getConstant(Mask2, MVT::i32));
8460       // Do not add new nodes to DAG combiner worklist.
8461       DCI.CombineTo(N, Res, false);
8462       return SDValue();
8463     }
8464   }
8465
8466   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8467       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8468       ARM::isBitFieldInvertedMask(~Mask)) {
8469     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8470     // where lsb(mask) == #shamt and masked bits of B are known zero.
8471     SDValue ShAmt = N00.getOperand(1);
8472     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8473     unsigned LSB = countTrailingZeros(Mask);
8474     if (ShAmtC != LSB)
8475       return SDValue();
8476
8477     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8478                       DAG.getConstant(~Mask, MVT::i32));
8479
8480     // Do not add new nodes to DAG combiner worklist.
8481     DCI.CombineTo(N, Res, false);
8482   }
8483
8484   return SDValue();
8485 }
8486
8487 static SDValue PerformXORCombine(SDNode *N,
8488                                  TargetLowering::DAGCombinerInfo &DCI,
8489                                  const ARMSubtarget *Subtarget) {
8490   EVT VT = N->getValueType(0);
8491   SelectionDAG &DAG = DCI.DAG;
8492
8493   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8494     return SDValue();
8495
8496   if (!Subtarget->isThumb1Only()) {
8497     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8498     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8499     if (Result.getNode())
8500       return Result;
8501   }
8502
8503   return SDValue();
8504 }
8505
8506 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8507 /// the bits being cleared by the AND are not demanded by the BFI.
8508 static SDValue PerformBFICombine(SDNode *N,
8509                                  TargetLowering::DAGCombinerInfo &DCI) {
8510   SDValue N1 = N->getOperand(1);
8511   if (N1.getOpcode() == ISD::AND) {
8512     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8513     if (!N11C)
8514       return SDValue();
8515     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8516     unsigned LSB = countTrailingZeros(~InvMask);
8517     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8518     unsigned Mask = (1 << Width)-1;
8519     unsigned Mask2 = N11C->getZExtValue();
8520     if ((Mask & (~Mask2)) == 0)
8521       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8522                              N->getOperand(0), N1.getOperand(0),
8523                              N->getOperand(2));
8524   }
8525   return SDValue();
8526 }
8527
8528 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8529 /// ARMISD::VMOVRRD.
8530 static SDValue PerformVMOVRRDCombine(SDNode *N,
8531                                      TargetLowering::DAGCombinerInfo &DCI) {
8532   // vmovrrd(vmovdrr x, y) -> x,y
8533   SDValue InDouble = N->getOperand(0);
8534   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8535     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8536
8537   // vmovrrd(load f64) -> (load i32), (load i32)
8538   SDNode *InNode = InDouble.getNode();
8539   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8540       InNode->getValueType(0) == MVT::f64 &&
8541       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8542       !cast<LoadSDNode>(InNode)->isVolatile()) {
8543     // TODO: Should this be done for non-FrameIndex operands?
8544     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8545
8546     SelectionDAG &DAG = DCI.DAG;
8547     SDLoc DL(LD);
8548     SDValue BasePtr = LD->getBasePtr();
8549     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8550                                  LD->getPointerInfo(), LD->isVolatile(),
8551                                  LD->isNonTemporal(), LD->isInvariant(),
8552                                  LD->getAlignment());
8553
8554     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8555                                     DAG.getConstant(4, MVT::i32));
8556     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8557                                  LD->getPointerInfo(), LD->isVolatile(),
8558                                  LD->isNonTemporal(), LD->isInvariant(),
8559                                  std::min(4U, LD->getAlignment() / 2));
8560
8561     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8562     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8563     DCI.RemoveFromWorklist(LD);
8564     DAG.DeleteNode(LD);
8565     return Result;
8566   }
8567
8568   return SDValue();
8569 }
8570
8571 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8572 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8573 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8574   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8575   SDValue Op0 = N->getOperand(0);
8576   SDValue Op1 = N->getOperand(1);
8577   if (Op0.getOpcode() == ISD::BITCAST)
8578     Op0 = Op0.getOperand(0);
8579   if (Op1.getOpcode() == ISD::BITCAST)
8580     Op1 = Op1.getOperand(0);
8581   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8582       Op0.getNode() == Op1.getNode() &&
8583       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8584     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8585                        N->getValueType(0), Op0.getOperand(0));
8586   return SDValue();
8587 }
8588
8589 /// PerformSTORECombine - Target-specific dag combine xforms for
8590 /// ISD::STORE.
8591 static SDValue PerformSTORECombine(SDNode *N,
8592                                    TargetLowering::DAGCombinerInfo &DCI) {
8593   StoreSDNode *St = cast<StoreSDNode>(N);
8594   if (St->isVolatile())
8595     return SDValue();
8596
8597   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8598   // pack all of the elements in one place.  Next, store to memory in fewer
8599   // chunks.
8600   SDValue StVal = St->getValue();
8601   EVT VT = StVal.getValueType();
8602   if (St->isTruncatingStore() && VT.isVector()) {
8603     SelectionDAG &DAG = DCI.DAG;
8604     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8605     EVT StVT = St->getMemoryVT();
8606     unsigned NumElems = VT.getVectorNumElements();
8607     assert(StVT != VT && "Cannot truncate to the same type");
8608     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8609     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8610
8611     // From, To sizes and ElemCount must be pow of two
8612     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8613
8614     // We are going to use the original vector elt for storing.
8615     // Accumulated smaller vector elements must be a multiple of the store size.
8616     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8617
8618     unsigned SizeRatio  = FromEltSz / ToEltSz;
8619     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8620
8621     // Create a type on which we perform the shuffle.
8622     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8623                                      NumElems*SizeRatio);
8624     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8625
8626     SDLoc DL(St);
8627     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8628     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8629     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8630
8631     // Can't shuffle using an illegal type.
8632     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8633
8634     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8635                                 DAG.getUNDEF(WideVec.getValueType()),
8636                                 ShuffleVec.data());
8637     // At this point all of the data is stored at the bottom of the
8638     // register. We now need to save it to mem.
8639
8640     // Find the largest store unit
8641     MVT StoreType = MVT::i8;
8642     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8643          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8644       MVT Tp = (MVT::SimpleValueType)tp;
8645       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8646         StoreType = Tp;
8647     }
8648     // Didn't find a legal store type.
8649     if (!TLI.isTypeLegal(StoreType))
8650       return SDValue();
8651
8652     // Bitcast the original vector into a vector of store-size units
8653     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8654             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8655     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8656     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8657     SmallVector<SDValue, 8> Chains;
8658     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8659                                         TLI.getPointerTy());
8660     SDValue BasePtr = St->getBasePtr();
8661
8662     // Perform one or more big stores into memory.
8663     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8664     for (unsigned I = 0; I < E; I++) {
8665       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8666                                    StoreType, ShuffWide,
8667                                    DAG.getIntPtrConstant(I));
8668       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8669                                 St->getPointerInfo(), St->isVolatile(),
8670                                 St->isNonTemporal(), St->getAlignment());
8671       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8672                             Increment);
8673       Chains.push_back(Ch);
8674     }
8675     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8676                        Chains.size());
8677   }
8678
8679   if (!ISD::isNormalStore(St))
8680     return SDValue();
8681
8682   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8683   // ARM stores of arguments in the same cache line.
8684   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8685       StVal.getNode()->hasOneUse()) {
8686     SelectionDAG  &DAG = DCI.DAG;
8687     SDLoc DL(St);
8688     SDValue BasePtr = St->getBasePtr();
8689     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8690                                   StVal.getNode()->getOperand(0), BasePtr,
8691                                   St->getPointerInfo(), St->isVolatile(),
8692                                   St->isNonTemporal(), St->getAlignment());
8693
8694     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8695                                     DAG.getConstant(4, MVT::i32));
8696     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8697                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8698                         St->isNonTemporal(),
8699                         std::min(4U, St->getAlignment() / 2));
8700   }
8701
8702   if (StVal.getValueType() != MVT::i64 ||
8703       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8704     return SDValue();
8705
8706   // Bitcast an i64 store extracted from a vector to f64.
8707   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8708   SelectionDAG &DAG = DCI.DAG;
8709   SDLoc dl(StVal);
8710   SDValue IntVec = StVal.getOperand(0);
8711   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8712                                  IntVec.getValueType().getVectorNumElements());
8713   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8714   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8715                                Vec, StVal.getOperand(1));
8716   dl = SDLoc(N);
8717   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8718   // Make the DAGCombiner fold the bitcasts.
8719   DCI.AddToWorklist(Vec.getNode());
8720   DCI.AddToWorklist(ExtElt.getNode());
8721   DCI.AddToWorklist(V.getNode());
8722   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8723                       St->getPointerInfo(), St->isVolatile(),
8724                       St->isNonTemporal(), St->getAlignment(),
8725                       St->getTBAAInfo());
8726 }
8727
8728 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8729 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8730 /// i64 vector to have f64 elements, since the value can then be loaded
8731 /// directly into a VFP register.
8732 static bool hasNormalLoadOperand(SDNode *N) {
8733   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8734   for (unsigned i = 0; i < NumElts; ++i) {
8735     SDNode *Elt = N->getOperand(i).getNode();
8736     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8737       return true;
8738   }
8739   return false;
8740 }
8741
8742 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8743 /// ISD::BUILD_VECTOR.
8744 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8745                                           TargetLowering::DAGCombinerInfo &DCI){
8746   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8747   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8748   // into a pair of GPRs, which is fine when the value is used as a scalar,
8749   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8750   SelectionDAG &DAG = DCI.DAG;
8751   if (N->getNumOperands() == 2) {
8752     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8753     if (RV.getNode())
8754       return RV;
8755   }
8756
8757   // Load i64 elements as f64 values so that type legalization does not split
8758   // them up into i32 values.
8759   EVT VT = N->getValueType(0);
8760   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8761     return SDValue();
8762   SDLoc dl(N);
8763   SmallVector<SDValue, 8> Ops;
8764   unsigned NumElts = VT.getVectorNumElements();
8765   for (unsigned i = 0; i < NumElts; ++i) {
8766     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8767     Ops.push_back(V);
8768     // Make the DAGCombiner fold the bitcast.
8769     DCI.AddToWorklist(V.getNode());
8770   }
8771   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8772   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8773   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8774 }
8775
8776 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8777 static SDValue
8778 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8779   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8780   // At that time, we may have inserted bitcasts from integer to float.
8781   // If these bitcasts have survived DAGCombine, change the lowering of this
8782   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8783   // force to use floating point types.
8784
8785   // Make sure we can change the type of the vector.
8786   // This is possible iff:
8787   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8788   //    1.1. Vector is used only once.
8789   //    1.2. Use is a bit convert to an integer type.
8790   // 2. The size of its operands are 32-bits (64-bits are not legal).
8791   EVT VT = N->getValueType(0);
8792   EVT EltVT = VT.getVectorElementType();
8793
8794   // Check 1.1. and 2.
8795   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8796     return SDValue();
8797
8798   // By construction, the input type must be float.
8799   assert(EltVT == MVT::f32 && "Unexpected type!");
8800
8801   // Check 1.2.
8802   SDNode *Use = *N->use_begin();
8803   if (Use->getOpcode() != ISD::BITCAST ||
8804       Use->getValueType(0).isFloatingPoint())
8805     return SDValue();
8806
8807   // Check profitability.
8808   // Model is, if more than half of the relevant operands are bitcast from
8809   // i32, turn the build_vector into a sequence of insert_vector_elt.
8810   // Relevant operands are everything that is not statically
8811   // (i.e., at compile time) bitcasted.
8812   unsigned NumOfBitCastedElts = 0;
8813   unsigned NumElts = VT.getVectorNumElements();
8814   unsigned NumOfRelevantElts = NumElts;
8815   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8816     SDValue Elt = N->getOperand(Idx);
8817     if (Elt->getOpcode() == ISD::BITCAST) {
8818       // Assume only bit cast to i32 will go away.
8819       if (Elt->getOperand(0).getValueType() == MVT::i32)
8820         ++NumOfBitCastedElts;
8821     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8822       // Constants are statically casted, thus do not count them as
8823       // relevant operands.
8824       --NumOfRelevantElts;
8825   }
8826
8827   // Check if more than half of the elements require a non-free bitcast.
8828   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8829     return SDValue();
8830
8831   SelectionDAG &DAG = DCI.DAG;
8832   // Create the new vector type.
8833   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8834   // Check if the type is legal.
8835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8836   if (!TLI.isTypeLegal(VecVT))
8837     return SDValue();
8838
8839   // Combine:
8840   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8841   // => BITCAST INSERT_VECTOR_ELT
8842   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8843   //                      (BITCAST EN), N.
8844   SDValue Vec = DAG.getUNDEF(VecVT);
8845   SDLoc dl(N);
8846   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8847     SDValue V = N->getOperand(Idx);
8848     if (V.getOpcode() == ISD::UNDEF)
8849       continue;
8850     if (V.getOpcode() == ISD::BITCAST &&
8851         V->getOperand(0).getValueType() == MVT::i32)
8852       // Fold obvious case.
8853       V = V.getOperand(0);
8854     else {
8855       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
8856       // Make the DAGCombiner fold the bitcasts.
8857       DCI.AddToWorklist(V.getNode());
8858     }
8859     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8860     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8861   }
8862   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8863   // Make the DAGCombiner fold the bitcasts.
8864   DCI.AddToWorklist(Vec.getNode());
8865   return Vec;
8866 }
8867
8868 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8869 /// ISD::INSERT_VECTOR_ELT.
8870 static SDValue PerformInsertEltCombine(SDNode *N,
8871                                        TargetLowering::DAGCombinerInfo &DCI) {
8872   // Bitcast an i64 load inserted into a vector to f64.
8873   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8874   EVT VT = N->getValueType(0);
8875   SDNode *Elt = N->getOperand(1).getNode();
8876   if (VT.getVectorElementType() != MVT::i64 ||
8877       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8878     return SDValue();
8879
8880   SelectionDAG &DAG = DCI.DAG;
8881   SDLoc dl(N);
8882   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8883                                  VT.getVectorNumElements());
8884   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8885   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8886   // Make the DAGCombiner fold the bitcasts.
8887   DCI.AddToWorklist(Vec.getNode());
8888   DCI.AddToWorklist(V.getNode());
8889   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8890                                Vec, V, N->getOperand(2));
8891   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8892 }
8893
8894 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8895 /// ISD::VECTOR_SHUFFLE.
8896 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8897   // The LLVM shufflevector instruction does not require the shuffle mask
8898   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8899   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8900   // operands do not match the mask length, they are extended by concatenating
8901   // them with undef vectors.  That is probably the right thing for other
8902   // targets, but for NEON it is better to concatenate two double-register
8903   // size vector operands into a single quad-register size vector.  Do that
8904   // transformation here:
8905   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8906   //   shuffle(concat(v1, v2), undef)
8907   SDValue Op0 = N->getOperand(0);
8908   SDValue Op1 = N->getOperand(1);
8909   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8910       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8911       Op0.getNumOperands() != 2 ||
8912       Op1.getNumOperands() != 2)
8913     return SDValue();
8914   SDValue Concat0Op1 = Op0.getOperand(1);
8915   SDValue Concat1Op1 = Op1.getOperand(1);
8916   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8917       Concat1Op1.getOpcode() != ISD::UNDEF)
8918     return SDValue();
8919   // Skip the transformation if any of the types are illegal.
8920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8921   EVT VT = N->getValueType(0);
8922   if (!TLI.isTypeLegal(VT) ||
8923       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8924       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8925     return SDValue();
8926
8927   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8928                                   Op0.getOperand(0), Op1.getOperand(0));
8929   // Translate the shuffle mask.
8930   SmallVector<int, 16> NewMask;
8931   unsigned NumElts = VT.getVectorNumElements();
8932   unsigned HalfElts = NumElts/2;
8933   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8934   for (unsigned n = 0; n < NumElts; ++n) {
8935     int MaskElt = SVN->getMaskElt(n);
8936     int NewElt = -1;
8937     if (MaskElt < (int)HalfElts)
8938       NewElt = MaskElt;
8939     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8940       NewElt = HalfElts + MaskElt - NumElts;
8941     NewMask.push_back(NewElt);
8942   }
8943   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8944                               DAG.getUNDEF(VT), NewMask.data());
8945 }
8946
8947 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8948 /// NEON load/store intrinsics to merge base address updates.
8949 static SDValue CombineBaseUpdate(SDNode *N,
8950                                  TargetLowering::DAGCombinerInfo &DCI) {
8951   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8952     return SDValue();
8953
8954   SelectionDAG &DAG = DCI.DAG;
8955   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8956                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8957   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8958   SDValue Addr = N->getOperand(AddrOpIdx);
8959
8960   // Search for a use of the address operand that is an increment.
8961   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8962          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8963     SDNode *User = *UI;
8964     if (User->getOpcode() != ISD::ADD ||
8965         UI.getUse().getResNo() != Addr.getResNo())
8966       continue;
8967
8968     // Check that the add is independent of the load/store.  Otherwise, folding
8969     // it would create a cycle.
8970     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8971       continue;
8972
8973     // Find the new opcode for the updating load/store.
8974     bool isLoad = true;
8975     bool isLaneOp = false;
8976     unsigned NewOpc = 0;
8977     unsigned NumVecs = 0;
8978     if (isIntrinsic) {
8979       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8980       switch (IntNo) {
8981       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8982       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8983         NumVecs = 1; break;
8984       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8985         NumVecs = 2; break;
8986       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8987         NumVecs = 3; break;
8988       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8989         NumVecs = 4; break;
8990       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8991         NumVecs = 2; isLaneOp = true; break;
8992       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8993         NumVecs = 3; isLaneOp = true; break;
8994       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8995         NumVecs = 4; isLaneOp = true; break;
8996       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8997         NumVecs = 1; isLoad = false; break;
8998       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8999         NumVecs = 2; isLoad = false; break;
9000       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9001         NumVecs = 3; isLoad = false; break;
9002       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9003         NumVecs = 4; isLoad = false; break;
9004       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9005         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9006       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9007         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9008       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9009         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9010       }
9011     } else {
9012       isLaneOp = true;
9013       switch (N->getOpcode()) {
9014       default: llvm_unreachable("unexpected opcode for Neon base update");
9015       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9016       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9017       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9018       }
9019     }
9020
9021     // Find the size of memory referenced by the load/store.
9022     EVT VecTy;
9023     if (isLoad)
9024       VecTy = N->getValueType(0);
9025     else
9026       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9027     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9028     if (isLaneOp)
9029       NumBytes /= VecTy.getVectorNumElements();
9030
9031     // If the increment is a constant, it must match the memory ref size.
9032     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9033     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9034       uint64_t IncVal = CInc->getZExtValue();
9035       if (IncVal != NumBytes)
9036         continue;
9037     } else if (NumBytes >= 3 * 16) {
9038       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9039       // separate instructions that make it harder to use a non-constant update.
9040       continue;
9041     }
9042
9043     // Create the new updating load/store node.
9044     EVT Tys[6];
9045     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9046     unsigned n;
9047     for (n = 0; n < NumResultVecs; ++n)
9048       Tys[n] = VecTy;
9049     Tys[n++] = MVT::i32;
9050     Tys[n] = MVT::Other;
9051     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9052     SmallVector<SDValue, 8> Ops;
9053     Ops.push_back(N->getOperand(0)); // incoming chain
9054     Ops.push_back(N->getOperand(AddrOpIdx));
9055     Ops.push_back(Inc);
9056     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9057       Ops.push_back(N->getOperand(i));
9058     }
9059     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9060     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9061                                            Ops.data(), Ops.size(),
9062                                            MemInt->getMemoryVT(),
9063                                            MemInt->getMemOperand());
9064
9065     // Update the uses.
9066     std::vector<SDValue> NewResults;
9067     for (unsigned i = 0; i < NumResultVecs; ++i) {
9068       NewResults.push_back(SDValue(UpdN.getNode(), i));
9069     }
9070     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9071     DCI.CombineTo(N, NewResults);
9072     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9073
9074     break;
9075   }
9076   return SDValue();
9077 }
9078
9079 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9080 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9081 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9082 /// return true.
9083 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9084   SelectionDAG &DAG = DCI.DAG;
9085   EVT VT = N->getValueType(0);
9086   // vldN-dup instructions only support 64-bit vectors for N > 1.
9087   if (!VT.is64BitVector())
9088     return false;
9089
9090   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9091   SDNode *VLD = N->getOperand(0).getNode();
9092   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9093     return false;
9094   unsigned NumVecs = 0;
9095   unsigned NewOpc = 0;
9096   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9097   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9098     NumVecs = 2;
9099     NewOpc = ARMISD::VLD2DUP;
9100   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9101     NumVecs = 3;
9102     NewOpc = ARMISD::VLD3DUP;
9103   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9104     NumVecs = 4;
9105     NewOpc = ARMISD::VLD4DUP;
9106   } else {
9107     return false;
9108   }
9109
9110   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9111   // numbers match the load.
9112   unsigned VLDLaneNo =
9113     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9114   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9115        UI != UE; ++UI) {
9116     // Ignore uses of the chain result.
9117     if (UI.getUse().getResNo() == NumVecs)
9118       continue;
9119     SDNode *User = *UI;
9120     if (User->getOpcode() != ARMISD::VDUPLANE ||
9121         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9122       return false;
9123   }
9124
9125   // Create the vldN-dup node.
9126   EVT Tys[5];
9127   unsigned n;
9128   for (n = 0; n < NumVecs; ++n)
9129     Tys[n] = VT;
9130   Tys[n] = MVT::Other;
9131   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9132   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9133   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9134   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9135                                            Ops, 2, VLDMemInt->getMemoryVT(),
9136                                            VLDMemInt->getMemOperand());
9137
9138   // Update the uses.
9139   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9140        UI != UE; ++UI) {
9141     unsigned ResNo = UI.getUse().getResNo();
9142     // Ignore uses of the chain result.
9143     if (ResNo == NumVecs)
9144       continue;
9145     SDNode *User = *UI;
9146     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9147   }
9148
9149   // Now the vldN-lane intrinsic is dead except for its chain result.
9150   // Update uses of the chain.
9151   std::vector<SDValue> VLDDupResults;
9152   for (unsigned n = 0; n < NumVecs; ++n)
9153     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9154   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9155   DCI.CombineTo(VLD, VLDDupResults);
9156
9157   return true;
9158 }
9159
9160 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9161 /// ARMISD::VDUPLANE.
9162 static SDValue PerformVDUPLANECombine(SDNode *N,
9163                                       TargetLowering::DAGCombinerInfo &DCI) {
9164   SDValue Op = N->getOperand(0);
9165
9166   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9167   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9168   if (CombineVLDDUP(N, DCI))
9169     return SDValue(N, 0);
9170
9171   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9172   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9173   while (Op.getOpcode() == ISD::BITCAST)
9174     Op = Op.getOperand(0);
9175   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9176     return SDValue();
9177
9178   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9179   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9180   // The canonical VMOV for a zero vector uses a 32-bit element size.
9181   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9182   unsigned EltBits;
9183   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9184     EltSize = 8;
9185   EVT VT = N->getValueType(0);
9186   if (EltSize > VT.getVectorElementType().getSizeInBits())
9187     return SDValue();
9188
9189   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9190 }
9191
9192 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9193 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9194 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9195 {
9196   integerPart cN;
9197   integerPart c0 = 0;
9198   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9199        I != E; I++) {
9200     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9201     if (!C)
9202       return false;
9203
9204     bool isExact;
9205     APFloat APF = C->getValueAPF();
9206     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9207         != APFloat::opOK || !isExact)
9208       return false;
9209
9210     c0 = (I == 0) ? cN : c0;
9211     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9212       return false;
9213   }
9214   C = c0;
9215   return true;
9216 }
9217
9218 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9219 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9220 /// when the VMUL has a constant operand that is a power of 2.
9221 ///
9222 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9223 ///  vmul.f32        d16, d17, d16
9224 ///  vcvt.s32.f32    d16, d16
9225 /// becomes:
9226 ///  vcvt.s32.f32    d16, d16, #3
9227 static SDValue PerformVCVTCombine(SDNode *N,
9228                                   TargetLowering::DAGCombinerInfo &DCI,
9229                                   const ARMSubtarget *Subtarget) {
9230   SelectionDAG &DAG = DCI.DAG;
9231   SDValue Op = N->getOperand(0);
9232
9233   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9234       Op.getOpcode() != ISD::FMUL)
9235     return SDValue();
9236
9237   uint64_t C;
9238   SDValue N0 = Op->getOperand(0);
9239   SDValue ConstVec = Op->getOperand(1);
9240   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9241
9242   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9243       !isConstVecPow2(ConstVec, isSigned, C))
9244     return SDValue();
9245
9246   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9247   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9248   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9249     // These instructions only exist converting from f32 to i32. We can handle
9250     // smaller integers by generating an extra truncate, but larger ones would
9251     // be lossy.
9252     return SDValue();
9253   }
9254
9255   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9256     Intrinsic::arm_neon_vcvtfp2fxu;
9257   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9258   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9259                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9260                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9261                                  DAG.getConstant(Log2_64(C), MVT::i32));
9262
9263   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9264     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9265
9266   return FixConv;
9267 }
9268
9269 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9270 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9271 /// when the VDIV has a constant operand that is a power of 2.
9272 ///
9273 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9274 ///  vcvt.f32.s32    d16, d16
9275 ///  vdiv.f32        d16, d17, d16
9276 /// becomes:
9277 ///  vcvt.f32.s32    d16, d16, #3
9278 static SDValue PerformVDIVCombine(SDNode *N,
9279                                   TargetLowering::DAGCombinerInfo &DCI,
9280                                   const ARMSubtarget *Subtarget) {
9281   SelectionDAG &DAG = DCI.DAG;
9282   SDValue Op = N->getOperand(0);
9283   unsigned OpOpcode = Op.getNode()->getOpcode();
9284
9285   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9286       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9287     return SDValue();
9288
9289   uint64_t C;
9290   SDValue ConstVec = N->getOperand(1);
9291   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9292
9293   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9294       !isConstVecPow2(ConstVec, isSigned, C))
9295     return SDValue();
9296
9297   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9298   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9299   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9300     // These instructions only exist converting from i32 to f32. We can handle
9301     // smaller integers by generating an extra extend, but larger ones would
9302     // be lossy.
9303     return SDValue();
9304   }
9305
9306   SDValue ConvInput = Op.getOperand(0);
9307   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9308   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9309     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9310                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9311                             ConvInput);
9312
9313   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9314     Intrinsic::arm_neon_vcvtfxu2fp;
9315   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9316                      Op.getValueType(),
9317                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9318                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9319 }
9320
9321 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9322 /// operand of a vector shift operation, where all the elements of the
9323 /// build_vector must have the same constant integer value.
9324 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9325   // Ignore bit_converts.
9326   while (Op.getOpcode() == ISD::BITCAST)
9327     Op = Op.getOperand(0);
9328   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9329   APInt SplatBits, SplatUndef;
9330   unsigned SplatBitSize;
9331   bool HasAnyUndefs;
9332   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9333                                       HasAnyUndefs, ElementBits) ||
9334       SplatBitSize > ElementBits)
9335     return false;
9336   Cnt = SplatBits.getSExtValue();
9337   return true;
9338 }
9339
9340 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9341 /// operand of a vector shift left operation.  That value must be in the range:
9342 ///   0 <= Value < ElementBits for a left shift; or
9343 ///   0 <= Value <= ElementBits for a long left shift.
9344 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9345   assert(VT.isVector() && "vector shift count is not a vector type");
9346   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9347   if (! getVShiftImm(Op, ElementBits, Cnt))
9348     return false;
9349   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9350 }
9351
9352 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9353 /// operand of a vector shift right operation.  For a shift opcode, the value
9354 /// is positive, but for an intrinsic the value count must be negative. The
9355 /// absolute value must be in the range:
9356 ///   1 <= |Value| <= ElementBits for a right shift; or
9357 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9358 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9359                          int64_t &Cnt) {
9360   assert(VT.isVector() && "vector shift count is not a vector type");
9361   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9362   if (! getVShiftImm(Op, ElementBits, Cnt))
9363     return false;
9364   if (isIntrinsic)
9365     Cnt = -Cnt;
9366   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9367 }
9368
9369 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9370 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9371   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9372   switch (IntNo) {
9373   default:
9374     // Don't do anything for most intrinsics.
9375     break;
9376
9377   // Vector shifts: check for immediate versions and lower them.
9378   // Note: This is done during DAG combining instead of DAG legalizing because
9379   // the build_vectors for 64-bit vector element shift counts are generally
9380   // not legal, and it is hard to see their values after they get legalized to
9381   // loads from a constant pool.
9382   case Intrinsic::arm_neon_vshifts:
9383   case Intrinsic::arm_neon_vshiftu:
9384   case Intrinsic::arm_neon_vshiftls:
9385   case Intrinsic::arm_neon_vshiftlu:
9386   case Intrinsic::arm_neon_vshiftn:
9387   case Intrinsic::arm_neon_vrshifts:
9388   case Intrinsic::arm_neon_vrshiftu:
9389   case Intrinsic::arm_neon_vrshiftn:
9390   case Intrinsic::arm_neon_vqshifts:
9391   case Intrinsic::arm_neon_vqshiftu:
9392   case Intrinsic::arm_neon_vqshiftsu:
9393   case Intrinsic::arm_neon_vqshiftns:
9394   case Intrinsic::arm_neon_vqshiftnu:
9395   case Intrinsic::arm_neon_vqshiftnsu:
9396   case Intrinsic::arm_neon_vqrshiftns:
9397   case Intrinsic::arm_neon_vqrshiftnu:
9398   case Intrinsic::arm_neon_vqrshiftnsu: {
9399     EVT VT = N->getOperand(1).getValueType();
9400     int64_t Cnt;
9401     unsigned VShiftOpc = 0;
9402
9403     switch (IntNo) {
9404     case Intrinsic::arm_neon_vshifts:
9405     case Intrinsic::arm_neon_vshiftu:
9406       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9407         VShiftOpc = ARMISD::VSHL;
9408         break;
9409       }
9410       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9411         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9412                      ARMISD::VSHRs : ARMISD::VSHRu);
9413         break;
9414       }
9415       return SDValue();
9416
9417     case Intrinsic::arm_neon_vshiftls:
9418     case Intrinsic::arm_neon_vshiftlu:
9419       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9420         break;
9421       llvm_unreachable("invalid shift count for vshll intrinsic");
9422
9423     case Intrinsic::arm_neon_vrshifts:
9424     case Intrinsic::arm_neon_vrshiftu:
9425       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9426         break;
9427       return SDValue();
9428
9429     case Intrinsic::arm_neon_vqshifts:
9430     case Intrinsic::arm_neon_vqshiftu:
9431       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9432         break;
9433       return SDValue();
9434
9435     case Intrinsic::arm_neon_vqshiftsu:
9436       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9437         break;
9438       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9439
9440     case Intrinsic::arm_neon_vshiftn:
9441     case Intrinsic::arm_neon_vrshiftn:
9442     case Intrinsic::arm_neon_vqshiftns:
9443     case Intrinsic::arm_neon_vqshiftnu:
9444     case Intrinsic::arm_neon_vqshiftnsu:
9445     case Intrinsic::arm_neon_vqrshiftns:
9446     case Intrinsic::arm_neon_vqrshiftnu:
9447     case Intrinsic::arm_neon_vqrshiftnsu:
9448       // Narrowing shifts require an immediate right shift.
9449       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9450         break;
9451       llvm_unreachable("invalid shift count for narrowing vector shift "
9452                        "intrinsic");
9453
9454     default:
9455       llvm_unreachable("unhandled vector shift");
9456     }
9457
9458     switch (IntNo) {
9459     case Intrinsic::arm_neon_vshifts:
9460     case Intrinsic::arm_neon_vshiftu:
9461       // Opcode already set above.
9462       break;
9463     case Intrinsic::arm_neon_vshiftls:
9464     case Intrinsic::arm_neon_vshiftlu:
9465       if (Cnt == VT.getVectorElementType().getSizeInBits())
9466         VShiftOpc = ARMISD::VSHLLi;
9467       else
9468         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9469                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9470       break;
9471     case Intrinsic::arm_neon_vshiftn:
9472       VShiftOpc = ARMISD::VSHRN; break;
9473     case Intrinsic::arm_neon_vrshifts:
9474       VShiftOpc = ARMISD::VRSHRs; break;
9475     case Intrinsic::arm_neon_vrshiftu:
9476       VShiftOpc = ARMISD::VRSHRu; break;
9477     case Intrinsic::arm_neon_vrshiftn:
9478       VShiftOpc = ARMISD::VRSHRN; break;
9479     case Intrinsic::arm_neon_vqshifts:
9480       VShiftOpc = ARMISD::VQSHLs; break;
9481     case Intrinsic::arm_neon_vqshiftu:
9482       VShiftOpc = ARMISD::VQSHLu; break;
9483     case Intrinsic::arm_neon_vqshiftsu:
9484       VShiftOpc = ARMISD::VQSHLsu; break;
9485     case Intrinsic::arm_neon_vqshiftns:
9486       VShiftOpc = ARMISD::VQSHRNs; break;
9487     case Intrinsic::arm_neon_vqshiftnu:
9488       VShiftOpc = ARMISD::VQSHRNu; break;
9489     case Intrinsic::arm_neon_vqshiftnsu:
9490       VShiftOpc = ARMISD::VQSHRNsu; break;
9491     case Intrinsic::arm_neon_vqrshiftns:
9492       VShiftOpc = ARMISD::VQRSHRNs; break;
9493     case Intrinsic::arm_neon_vqrshiftnu:
9494       VShiftOpc = ARMISD::VQRSHRNu; break;
9495     case Intrinsic::arm_neon_vqrshiftnsu:
9496       VShiftOpc = ARMISD::VQRSHRNsu; break;
9497     }
9498
9499     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9500                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9501   }
9502
9503   case Intrinsic::arm_neon_vshiftins: {
9504     EVT VT = N->getOperand(1).getValueType();
9505     int64_t Cnt;
9506     unsigned VShiftOpc = 0;
9507
9508     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9509       VShiftOpc = ARMISD::VSLI;
9510     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9511       VShiftOpc = ARMISD::VSRI;
9512     else {
9513       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9514     }
9515
9516     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9517                        N->getOperand(1), N->getOperand(2),
9518                        DAG.getConstant(Cnt, MVT::i32));
9519   }
9520
9521   case Intrinsic::arm_neon_vqrshifts:
9522   case Intrinsic::arm_neon_vqrshiftu:
9523     // No immediate versions of these to check for.
9524     break;
9525   }
9526
9527   return SDValue();
9528 }
9529
9530 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9531 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9532 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9533 /// vector element shift counts are generally not legal, and it is hard to see
9534 /// their values after they get legalized to loads from a constant pool.
9535 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9536                                    const ARMSubtarget *ST) {
9537   EVT VT = N->getValueType(0);
9538   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9539     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9540     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9541     SDValue N1 = N->getOperand(1);
9542     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9543       SDValue N0 = N->getOperand(0);
9544       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9545           DAG.MaskedValueIsZero(N0.getOperand(0),
9546                                 APInt::getHighBitsSet(32, 16)))
9547         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9548     }
9549   }
9550
9551   // Nothing to be done for scalar shifts.
9552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9553   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9554     return SDValue();
9555
9556   assert(ST->hasNEON() && "unexpected vector shift");
9557   int64_t Cnt;
9558
9559   switch (N->getOpcode()) {
9560   default: llvm_unreachable("unexpected shift opcode");
9561
9562   case ISD::SHL:
9563     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9564       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9565                          DAG.getConstant(Cnt, MVT::i32));
9566     break;
9567
9568   case ISD::SRA:
9569   case ISD::SRL:
9570     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9571       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9572                             ARMISD::VSHRs : ARMISD::VSHRu);
9573       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9574                          DAG.getConstant(Cnt, MVT::i32));
9575     }
9576   }
9577   return SDValue();
9578 }
9579
9580 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9581 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9582 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9583                                     const ARMSubtarget *ST) {
9584   SDValue N0 = N->getOperand(0);
9585
9586   // Check for sign- and zero-extensions of vector extract operations of 8-
9587   // and 16-bit vector elements.  NEON supports these directly.  They are
9588   // handled during DAG combining because type legalization will promote them
9589   // to 32-bit types and it is messy to recognize the operations after that.
9590   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9591     SDValue Vec = N0.getOperand(0);
9592     SDValue Lane = N0.getOperand(1);
9593     EVT VT = N->getValueType(0);
9594     EVT EltVT = N0.getValueType();
9595     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9596
9597     if (VT == MVT::i32 &&
9598         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9599         TLI.isTypeLegal(Vec.getValueType()) &&
9600         isa<ConstantSDNode>(Lane)) {
9601
9602       unsigned Opc = 0;
9603       switch (N->getOpcode()) {
9604       default: llvm_unreachable("unexpected opcode");
9605       case ISD::SIGN_EXTEND:
9606         Opc = ARMISD::VGETLANEs;
9607         break;
9608       case ISD::ZERO_EXTEND:
9609       case ISD::ANY_EXTEND:
9610         Opc = ARMISD::VGETLANEu;
9611         break;
9612       }
9613       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9614     }
9615   }
9616
9617   return SDValue();
9618 }
9619
9620 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9621 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9622 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9623                                        const ARMSubtarget *ST) {
9624   // If the target supports NEON, try to use vmax/vmin instructions for f32
9625   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9626   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9627   // a NaN; only do the transformation when it matches that behavior.
9628
9629   // For now only do this when using NEON for FP operations; if using VFP, it
9630   // is not obvious that the benefit outweighs the cost of switching to the
9631   // NEON pipeline.
9632   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9633       N->getValueType(0) != MVT::f32)
9634     return SDValue();
9635
9636   SDValue CondLHS = N->getOperand(0);
9637   SDValue CondRHS = N->getOperand(1);
9638   SDValue LHS = N->getOperand(2);
9639   SDValue RHS = N->getOperand(3);
9640   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9641
9642   unsigned Opcode = 0;
9643   bool IsReversed;
9644   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9645     IsReversed = false; // x CC y ? x : y
9646   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9647     IsReversed = true ; // x CC y ? y : x
9648   } else {
9649     return SDValue();
9650   }
9651
9652   bool IsUnordered;
9653   switch (CC) {
9654   default: break;
9655   case ISD::SETOLT:
9656   case ISD::SETOLE:
9657   case ISD::SETLT:
9658   case ISD::SETLE:
9659   case ISD::SETULT:
9660   case ISD::SETULE:
9661     // If LHS is NaN, an ordered comparison will be false and the result will
9662     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9663     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9664     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9665     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9666       break;
9667     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9668     // will return -0, so vmin can only be used for unsafe math or if one of
9669     // the operands is known to be nonzero.
9670     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9671         !DAG.getTarget().Options.UnsafeFPMath &&
9672         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9673       break;
9674     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9675     break;
9676
9677   case ISD::SETOGT:
9678   case ISD::SETOGE:
9679   case ISD::SETGT:
9680   case ISD::SETGE:
9681   case ISD::SETUGT:
9682   case ISD::SETUGE:
9683     // If LHS is NaN, an ordered comparison will be false and the result will
9684     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9685     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9686     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9687     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9688       break;
9689     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9690     // will return +0, so vmax can only be used for unsafe math or if one of
9691     // the operands is known to be nonzero.
9692     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9693         !DAG.getTarget().Options.UnsafeFPMath &&
9694         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9695       break;
9696     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9697     break;
9698   }
9699
9700   if (!Opcode)
9701     return SDValue();
9702   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9703 }
9704
9705 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9706 SDValue
9707 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9708   SDValue Cmp = N->getOperand(4);
9709   if (Cmp.getOpcode() != ARMISD::CMPZ)
9710     // Only looking at EQ and NE cases.
9711     return SDValue();
9712
9713   EVT VT = N->getValueType(0);
9714   SDLoc dl(N);
9715   SDValue LHS = Cmp.getOperand(0);
9716   SDValue RHS = Cmp.getOperand(1);
9717   SDValue FalseVal = N->getOperand(0);
9718   SDValue TrueVal = N->getOperand(1);
9719   SDValue ARMcc = N->getOperand(2);
9720   ARMCC::CondCodes CC =
9721     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9722
9723   // Simplify
9724   //   mov     r1, r0
9725   //   cmp     r1, x
9726   //   mov     r0, y
9727   //   moveq   r0, x
9728   // to
9729   //   cmp     r0, x
9730   //   movne   r0, y
9731   //
9732   //   mov     r1, r0
9733   //   cmp     r1, x
9734   //   mov     r0, x
9735   //   movne   r0, y
9736   // to
9737   //   cmp     r0, x
9738   //   movne   r0, y
9739   /// FIXME: Turn this into a target neutral optimization?
9740   SDValue Res;
9741   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9742     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9743                       N->getOperand(3), Cmp);
9744   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9745     SDValue ARMcc;
9746     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9747     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9748                       N->getOperand(3), NewCmp);
9749   }
9750
9751   if (Res.getNode()) {
9752     APInt KnownZero, KnownOne;
9753     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9754     // Capture demanded bits information that would be otherwise lost.
9755     if (KnownZero == 0xfffffffe)
9756       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9757                         DAG.getValueType(MVT::i1));
9758     else if (KnownZero == 0xffffff00)
9759       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9760                         DAG.getValueType(MVT::i8));
9761     else if (KnownZero == 0xffff0000)
9762       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9763                         DAG.getValueType(MVT::i16));
9764   }
9765
9766   return Res;
9767 }
9768
9769 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9770                                              DAGCombinerInfo &DCI) const {
9771   switch (N->getOpcode()) {
9772   default: break;
9773   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9774   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9775   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9776   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9777   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9778   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9779   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9780   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9781   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9782   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9783   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9784   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9785   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9786   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9787   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9788   case ISD::FP_TO_SINT:
9789   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9790   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9791   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9792   case ISD::SHL:
9793   case ISD::SRA:
9794   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9795   case ISD::SIGN_EXTEND:
9796   case ISD::ZERO_EXTEND:
9797   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9798   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9799   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9800   case ARMISD::VLD2DUP:
9801   case ARMISD::VLD3DUP:
9802   case ARMISD::VLD4DUP:
9803     return CombineBaseUpdate(N, DCI);
9804   case ARMISD::BUILD_VECTOR:
9805     return PerformARMBUILD_VECTORCombine(N, DCI);
9806   case ISD::INTRINSIC_VOID:
9807   case ISD::INTRINSIC_W_CHAIN:
9808     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9809     case Intrinsic::arm_neon_vld1:
9810     case Intrinsic::arm_neon_vld2:
9811     case Intrinsic::arm_neon_vld3:
9812     case Intrinsic::arm_neon_vld4:
9813     case Intrinsic::arm_neon_vld2lane:
9814     case Intrinsic::arm_neon_vld3lane:
9815     case Intrinsic::arm_neon_vld4lane:
9816     case Intrinsic::arm_neon_vst1:
9817     case Intrinsic::arm_neon_vst2:
9818     case Intrinsic::arm_neon_vst3:
9819     case Intrinsic::arm_neon_vst4:
9820     case Intrinsic::arm_neon_vst2lane:
9821     case Intrinsic::arm_neon_vst3lane:
9822     case Intrinsic::arm_neon_vst4lane:
9823       return CombineBaseUpdate(N, DCI);
9824     default: break;
9825     }
9826     break;
9827   }
9828   return SDValue();
9829 }
9830
9831 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9832                                                           EVT VT) const {
9833   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9834 }
9835
9836 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9837   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9838   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9839
9840   switch (VT.getSimpleVT().SimpleTy) {
9841   default:
9842     return false;
9843   case MVT::i8:
9844   case MVT::i16:
9845   case MVT::i32: {
9846     // Unaligned access can use (for example) LRDB, LRDH, LDR
9847     if (AllowsUnaligned) {
9848       if (Fast)
9849         *Fast = Subtarget->hasV7Ops();
9850       return true;
9851     }
9852     return false;
9853   }
9854   case MVT::f64:
9855   case MVT::v2f64: {
9856     // For any little-endian targets with neon, we can support unaligned ld/st
9857     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9858     // A big-endian target may also explictly support unaligned accesses
9859     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9860       if (Fast)
9861         *Fast = true;
9862       return true;
9863     }
9864     return false;
9865   }
9866   }
9867 }
9868
9869 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9870                        unsigned AlignCheck) {
9871   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9872           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9873 }
9874
9875 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9876                                            unsigned DstAlign, unsigned SrcAlign,
9877                                            bool IsMemset, bool ZeroMemset,
9878                                            bool MemcpyStrSrc,
9879                                            MachineFunction &MF) const {
9880   const Function *F = MF.getFunction();
9881
9882   // See if we can use NEON instructions for this...
9883   if ((!IsMemset || ZeroMemset) &&
9884       Subtarget->hasNEON() &&
9885       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9886                                        Attribute::NoImplicitFloat)) {
9887     bool Fast;
9888     if (Size >= 16 &&
9889         (memOpAlign(SrcAlign, DstAlign, 16) ||
9890          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9891       return MVT::v2f64;
9892     } else if (Size >= 8 &&
9893                (memOpAlign(SrcAlign, DstAlign, 8) ||
9894                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9895       return MVT::f64;
9896     }
9897   }
9898
9899   // Lowering to i32/i16 if the size permits.
9900   if (Size >= 4)
9901     return MVT::i32;
9902   else if (Size >= 2)
9903     return MVT::i16;
9904
9905   // Let the target-independent logic figure it out.
9906   return MVT::Other;
9907 }
9908
9909 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9910   if (Val.getOpcode() != ISD::LOAD)
9911     return false;
9912
9913   EVT VT1 = Val.getValueType();
9914   if (!VT1.isSimple() || !VT1.isInteger() ||
9915       !VT2.isSimple() || !VT2.isInteger())
9916     return false;
9917
9918   switch (VT1.getSimpleVT().SimpleTy) {
9919   default: break;
9920   case MVT::i1:
9921   case MVT::i8:
9922   case MVT::i16:
9923     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9924     return true;
9925   }
9926
9927   return false;
9928 }
9929
9930 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9931   if (V < 0)
9932     return false;
9933
9934   unsigned Scale = 1;
9935   switch (VT.getSimpleVT().SimpleTy) {
9936   default: return false;
9937   case MVT::i1:
9938   case MVT::i8:
9939     // Scale == 1;
9940     break;
9941   case MVT::i16:
9942     // Scale == 2;
9943     Scale = 2;
9944     break;
9945   case MVT::i32:
9946     // Scale == 4;
9947     Scale = 4;
9948     break;
9949   }
9950
9951   if ((V & (Scale - 1)) != 0)
9952     return false;
9953   V /= Scale;
9954   return V == (V & ((1LL << 5) - 1));
9955 }
9956
9957 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9958                                       const ARMSubtarget *Subtarget) {
9959   bool isNeg = false;
9960   if (V < 0) {
9961     isNeg = true;
9962     V = - V;
9963   }
9964
9965   switch (VT.getSimpleVT().SimpleTy) {
9966   default: return false;
9967   case MVT::i1:
9968   case MVT::i8:
9969   case MVT::i16:
9970   case MVT::i32:
9971     // + imm12 or - imm8
9972     if (isNeg)
9973       return V == (V & ((1LL << 8) - 1));
9974     return V == (V & ((1LL << 12) - 1));
9975   case MVT::f32:
9976   case MVT::f64:
9977     // Same as ARM mode. FIXME: NEON?
9978     if (!Subtarget->hasVFP2())
9979       return false;
9980     if ((V & 3) != 0)
9981       return false;
9982     V >>= 2;
9983     return V == (V & ((1LL << 8) - 1));
9984   }
9985 }
9986
9987 /// isLegalAddressImmediate - Return true if the integer value can be used
9988 /// as the offset of the target addressing mode for load / store of the
9989 /// given type.
9990 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9991                                     const ARMSubtarget *Subtarget) {
9992   if (V == 0)
9993     return true;
9994
9995   if (!VT.isSimple())
9996     return false;
9997
9998   if (Subtarget->isThumb1Only())
9999     return isLegalT1AddressImmediate(V, VT);
10000   else if (Subtarget->isThumb2())
10001     return isLegalT2AddressImmediate(V, VT, Subtarget);
10002
10003   // ARM mode.
10004   if (V < 0)
10005     V = - V;
10006   switch (VT.getSimpleVT().SimpleTy) {
10007   default: return false;
10008   case MVT::i1:
10009   case MVT::i8:
10010   case MVT::i32:
10011     // +- imm12
10012     return V == (V & ((1LL << 12) - 1));
10013   case MVT::i16:
10014     // +- imm8
10015     return V == (V & ((1LL << 8) - 1));
10016   case MVT::f32:
10017   case MVT::f64:
10018     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10019       return false;
10020     if ((V & 3) != 0)
10021       return false;
10022     V >>= 2;
10023     return V == (V & ((1LL << 8) - 1));
10024   }
10025 }
10026
10027 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10028                                                       EVT VT) const {
10029   int Scale = AM.Scale;
10030   if (Scale < 0)
10031     return false;
10032
10033   switch (VT.getSimpleVT().SimpleTy) {
10034   default: return false;
10035   case MVT::i1:
10036   case MVT::i8:
10037   case MVT::i16:
10038   case MVT::i32:
10039     if (Scale == 1)
10040       return true;
10041     // r + r << imm
10042     Scale = Scale & ~1;
10043     return Scale == 2 || Scale == 4 || Scale == 8;
10044   case MVT::i64:
10045     // r + r
10046     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10047       return true;
10048     return false;
10049   case MVT::isVoid:
10050     // Note, we allow "void" uses (basically, uses that aren't loads or
10051     // stores), because arm allows folding a scale into many arithmetic
10052     // operations.  This should be made more precise and revisited later.
10053
10054     // Allow r << imm, but the imm has to be a multiple of two.
10055     if (Scale & 1) return false;
10056     return isPowerOf2_32(Scale);
10057   }
10058 }
10059
10060 /// isLegalAddressingMode - Return true if the addressing mode represented
10061 /// by AM is legal for this target, for a load/store of the specified type.
10062 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10063                                               Type *Ty) const {
10064   EVT VT = getValueType(Ty, true);
10065   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10066     return false;
10067
10068   // Can never fold addr of global into load/store.
10069   if (AM.BaseGV)
10070     return false;
10071
10072   switch (AM.Scale) {
10073   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10074     break;
10075   case 1:
10076     if (Subtarget->isThumb1Only())
10077       return false;
10078     // FALL THROUGH.
10079   default:
10080     // ARM doesn't support any R+R*scale+imm addr modes.
10081     if (AM.BaseOffs)
10082       return false;
10083
10084     if (!VT.isSimple())
10085       return false;
10086
10087     if (Subtarget->isThumb2())
10088       return isLegalT2ScaledAddressingMode(AM, VT);
10089
10090     int Scale = AM.Scale;
10091     switch (VT.getSimpleVT().SimpleTy) {
10092     default: return false;
10093     case MVT::i1:
10094     case MVT::i8:
10095     case MVT::i32:
10096       if (Scale < 0) Scale = -Scale;
10097       if (Scale == 1)
10098         return true;
10099       // r + r << imm
10100       return isPowerOf2_32(Scale & ~1);
10101     case MVT::i16:
10102     case MVT::i64:
10103       // r + r
10104       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10105         return true;
10106       return false;
10107
10108     case MVT::isVoid:
10109       // Note, we allow "void" uses (basically, uses that aren't loads or
10110       // stores), because arm allows folding a scale into many arithmetic
10111       // operations.  This should be made more precise and revisited later.
10112
10113       // Allow r << imm, but the imm has to be a multiple of two.
10114       if (Scale & 1) return false;
10115       return isPowerOf2_32(Scale);
10116     }
10117   }
10118   return true;
10119 }
10120
10121 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10122 /// icmp immediate, that is the target has icmp instructions which can compare
10123 /// a register against the immediate without having to materialize the
10124 /// immediate into a register.
10125 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10126   // Thumb2 and ARM modes can use cmn for negative immediates.
10127   if (!Subtarget->isThumb())
10128     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10129   if (Subtarget->isThumb2())
10130     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10131   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10132   return Imm >= 0 && Imm <= 255;
10133 }
10134
10135 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10136 /// *or sub* immediate, that is the target has add or sub instructions which can
10137 /// add a register with the immediate without having to materialize the
10138 /// immediate into a register.
10139 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10140   // Same encoding for add/sub, just flip the sign.
10141   int64_t AbsImm = llvm::abs64(Imm);
10142   if (!Subtarget->isThumb())
10143     return ARM_AM::getSOImmVal(AbsImm) != -1;
10144   if (Subtarget->isThumb2())
10145     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10146   // Thumb1 only has 8-bit unsigned immediate.
10147   return AbsImm >= 0 && AbsImm <= 255;
10148 }
10149
10150 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10151                                       bool isSEXTLoad, SDValue &Base,
10152                                       SDValue &Offset, bool &isInc,
10153                                       SelectionDAG &DAG) {
10154   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10155     return false;
10156
10157   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10158     // AddressingMode 3
10159     Base = Ptr->getOperand(0);
10160     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10161       int RHSC = (int)RHS->getZExtValue();
10162       if (RHSC < 0 && RHSC > -256) {
10163         assert(Ptr->getOpcode() == ISD::ADD);
10164         isInc = false;
10165         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10166         return true;
10167       }
10168     }
10169     isInc = (Ptr->getOpcode() == ISD::ADD);
10170     Offset = Ptr->getOperand(1);
10171     return true;
10172   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10173     // AddressingMode 2
10174     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10175       int RHSC = (int)RHS->getZExtValue();
10176       if (RHSC < 0 && RHSC > -0x1000) {
10177         assert(Ptr->getOpcode() == ISD::ADD);
10178         isInc = false;
10179         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10180         Base = Ptr->getOperand(0);
10181         return true;
10182       }
10183     }
10184
10185     if (Ptr->getOpcode() == ISD::ADD) {
10186       isInc = true;
10187       ARM_AM::ShiftOpc ShOpcVal=
10188         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10189       if (ShOpcVal != ARM_AM::no_shift) {
10190         Base = Ptr->getOperand(1);
10191         Offset = Ptr->getOperand(0);
10192       } else {
10193         Base = Ptr->getOperand(0);
10194         Offset = Ptr->getOperand(1);
10195       }
10196       return true;
10197     }
10198
10199     isInc = (Ptr->getOpcode() == ISD::ADD);
10200     Base = Ptr->getOperand(0);
10201     Offset = Ptr->getOperand(1);
10202     return true;
10203   }
10204
10205   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10206   return false;
10207 }
10208
10209 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10210                                      bool isSEXTLoad, SDValue &Base,
10211                                      SDValue &Offset, bool &isInc,
10212                                      SelectionDAG &DAG) {
10213   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10214     return false;
10215
10216   Base = Ptr->getOperand(0);
10217   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10218     int RHSC = (int)RHS->getZExtValue();
10219     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10220       assert(Ptr->getOpcode() == ISD::ADD);
10221       isInc = false;
10222       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10223       return true;
10224     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10225       isInc = Ptr->getOpcode() == ISD::ADD;
10226       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10227       return true;
10228     }
10229   }
10230
10231   return false;
10232 }
10233
10234 /// getPreIndexedAddressParts - returns true by value, base pointer and
10235 /// offset pointer and addressing mode by reference if the node's address
10236 /// can be legally represented as pre-indexed load / store address.
10237 bool
10238 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10239                                              SDValue &Offset,
10240                                              ISD::MemIndexedMode &AM,
10241                                              SelectionDAG &DAG) const {
10242   if (Subtarget->isThumb1Only())
10243     return false;
10244
10245   EVT VT;
10246   SDValue Ptr;
10247   bool isSEXTLoad = false;
10248   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10249     Ptr = LD->getBasePtr();
10250     VT  = LD->getMemoryVT();
10251     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10252   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10253     Ptr = ST->getBasePtr();
10254     VT  = ST->getMemoryVT();
10255   } else
10256     return false;
10257
10258   bool isInc;
10259   bool isLegal = false;
10260   if (Subtarget->isThumb2())
10261     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10262                                        Offset, isInc, DAG);
10263   else
10264     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10265                                         Offset, isInc, DAG);
10266   if (!isLegal)
10267     return false;
10268
10269   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10270   return true;
10271 }
10272
10273 /// getPostIndexedAddressParts - returns true by value, base pointer and
10274 /// offset pointer and addressing mode by reference if this node can be
10275 /// combined with a load / store to form a post-indexed load / store.
10276 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10277                                                    SDValue &Base,
10278                                                    SDValue &Offset,
10279                                                    ISD::MemIndexedMode &AM,
10280                                                    SelectionDAG &DAG) const {
10281   if (Subtarget->isThumb1Only())
10282     return false;
10283
10284   EVT VT;
10285   SDValue Ptr;
10286   bool isSEXTLoad = false;
10287   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10288     VT  = LD->getMemoryVT();
10289     Ptr = LD->getBasePtr();
10290     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10291   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10292     VT  = ST->getMemoryVT();
10293     Ptr = ST->getBasePtr();
10294   } else
10295     return false;
10296
10297   bool isInc;
10298   bool isLegal = false;
10299   if (Subtarget->isThumb2())
10300     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10301                                        isInc, DAG);
10302   else
10303     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10304                                         isInc, DAG);
10305   if (!isLegal)
10306     return false;
10307
10308   if (Ptr != Base) {
10309     // Swap base ptr and offset to catch more post-index load / store when
10310     // it's legal. In Thumb2 mode, offset must be an immediate.
10311     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10312         !Subtarget->isThumb2())
10313       std::swap(Base, Offset);
10314
10315     // Post-indexed load / store update the base pointer.
10316     if (Ptr != Base)
10317       return false;
10318   }
10319
10320   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10321   return true;
10322 }
10323
10324 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10325                                                        APInt &KnownZero,
10326                                                        APInt &KnownOne,
10327                                                        const SelectionDAG &DAG,
10328                                                        unsigned Depth) const {
10329   unsigned BitWidth = KnownOne.getBitWidth();
10330   KnownZero = KnownOne = APInt(BitWidth, 0);
10331   switch (Op.getOpcode()) {
10332   default: break;
10333   case ARMISD::ADDC:
10334   case ARMISD::ADDE:
10335   case ARMISD::SUBC:
10336   case ARMISD::SUBE:
10337     // These nodes' second result is a boolean
10338     if (Op.getResNo() == 0)
10339       break;
10340     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10341     break;
10342   case ARMISD::CMOV: {
10343     // Bits are known zero/one if known on the LHS and RHS.
10344     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10345     if (KnownZero == 0 && KnownOne == 0) return;
10346
10347     APInt KnownZeroRHS, KnownOneRHS;
10348     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10349     KnownZero &= KnownZeroRHS;
10350     KnownOne  &= KnownOneRHS;
10351     return;
10352   }
10353   }
10354 }
10355
10356 //===----------------------------------------------------------------------===//
10357 //                           ARM Inline Assembly Support
10358 //===----------------------------------------------------------------------===//
10359
10360 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10361   // Looking for "rev" which is V6+.
10362   if (!Subtarget->hasV6Ops())
10363     return false;
10364
10365   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10366   std::string AsmStr = IA->getAsmString();
10367   SmallVector<StringRef, 4> AsmPieces;
10368   SplitString(AsmStr, AsmPieces, ";\n");
10369
10370   switch (AsmPieces.size()) {
10371   default: return false;
10372   case 1:
10373     AsmStr = AsmPieces[0];
10374     AsmPieces.clear();
10375     SplitString(AsmStr, AsmPieces, " \t,");
10376
10377     // rev $0, $1
10378     if (AsmPieces.size() == 3 &&
10379         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10380         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10381       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10382       if (Ty && Ty->getBitWidth() == 32)
10383         return IntrinsicLowering::LowerToByteSwap(CI);
10384     }
10385     break;
10386   }
10387
10388   return false;
10389 }
10390
10391 /// getConstraintType - Given a constraint letter, return the type of
10392 /// constraint it is for this target.
10393 ARMTargetLowering::ConstraintType
10394 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10395   if (Constraint.size() == 1) {
10396     switch (Constraint[0]) {
10397     default:  break;
10398     case 'l': return C_RegisterClass;
10399     case 'w': return C_RegisterClass;
10400     case 'h': return C_RegisterClass;
10401     case 'x': return C_RegisterClass;
10402     case 't': return C_RegisterClass;
10403     case 'j': return C_Other; // Constant for movw.
10404       // An address with a single base register. Due to the way we
10405       // currently handle addresses it is the same as an 'r' memory constraint.
10406     case 'Q': return C_Memory;
10407     }
10408   } else if (Constraint.size() == 2) {
10409     switch (Constraint[0]) {
10410     default: break;
10411     // All 'U+' constraints are addresses.
10412     case 'U': return C_Memory;
10413     }
10414   }
10415   return TargetLowering::getConstraintType(Constraint);
10416 }
10417
10418 /// Examine constraint type and operand type and determine a weight value.
10419 /// This object must already have been set up with the operand type
10420 /// and the current alternative constraint selected.
10421 TargetLowering::ConstraintWeight
10422 ARMTargetLowering::getSingleConstraintMatchWeight(
10423     AsmOperandInfo &info, const char *constraint) const {
10424   ConstraintWeight weight = CW_Invalid;
10425   Value *CallOperandVal = info.CallOperandVal;
10426     // If we don't have a value, we can't do a match,
10427     // but allow it at the lowest weight.
10428   if (CallOperandVal == NULL)
10429     return CW_Default;
10430   Type *type = CallOperandVal->getType();
10431   // Look at the constraint type.
10432   switch (*constraint) {
10433   default:
10434     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10435     break;
10436   case 'l':
10437     if (type->isIntegerTy()) {
10438       if (Subtarget->isThumb())
10439         weight = CW_SpecificReg;
10440       else
10441         weight = CW_Register;
10442     }
10443     break;
10444   case 'w':
10445     if (type->isFloatingPointTy())
10446       weight = CW_Register;
10447     break;
10448   }
10449   return weight;
10450 }
10451
10452 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10453 RCPair
10454 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10455                                                 MVT VT) const {
10456   if (Constraint.size() == 1) {
10457     // GCC ARM Constraint Letters
10458     switch (Constraint[0]) {
10459     case 'l': // Low regs or general regs.
10460       if (Subtarget->isThumb())
10461         return RCPair(0U, &ARM::tGPRRegClass);
10462       return RCPair(0U, &ARM::GPRRegClass);
10463     case 'h': // High regs or no regs.
10464       if (Subtarget->isThumb())
10465         return RCPair(0U, &ARM::hGPRRegClass);
10466       break;
10467     case 'r':
10468       return RCPair(0U, &ARM::GPRRegClass);
10469     case 'w':
10470       if (VT == MVT::f32)
10471         return RCPair(0U, &ARM::SPRRegClass);
10472       if (VT.getSizeInBits() == 64)
10473         return RCPair(0U, &ARM::DPRRegClass);
10474       if (VT.getSizeInBits() == 128)
10475         return RCPair(0U, &ARM::QPRRegClass);
10476       break;
10477     case 'x':
10478       if (VT == MVT::f32)
10479         return RCPair(0U, &ARM::SPR_8RegClass);
10480       if (VT.getSizeInBits() == 64)
10481         return RCPair(0U, &ARM::DPR_8RegClass);
10482       if (VT.getSizeInBits() == 128)
10483         return RCPair(0U, &ARM::QPR_8RegClass);
10484       break;
10485     case 't':
10486       if (VT == MVT::f32)
10487         return RCPair(0U, &ARM::SPRRegClass);
10488       break;
10489     }
10490   }
10491   if (StringRef("{cc}").equals_lower(Constraint))
10492     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10493
10494   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10495 }
10496
10497 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10498 /// vector.  If it is invalid, don't add anything to Ops.
10499 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10500                                                      std::string &Constraint,
10501                                                      std::vector<SDValue>&Ops,
10502                                                      SelectionDAG &DAG) const {
10503   SDValue Result(0, 0);
10504
10505   // Currently only support length 1 constraints.
10506   if (Constraint.length() != 1) return;
10507
10508   char ConstraintLetter = Constraint[0];
10509   switch (ConstraintLetter) {
10510   default: break;
10511   case 'j':
10512   case 'I': case 'J': case 'K': case 'L':
10513   case 'M': case 'N': case 'O':
10514     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10515     if (!C)
10516       return;
10517
10518     int64_t CVal64 = C->getSExtValue();
10519     int CVal = (int) CVal64;
10520     // None of these constraints allow values larger than 32 bits.  Check
10521     // that the value fits in an int.
10522     if (CVal != CVal64)
10523       return;
10524
10525     switch (ConstraintLetter) {
10526       case 'j':
10527         // Constant suitable for movw, must be between 0 and
10528         // 65535.
10529         if (Subtarget->hasV6T2Ops())
10530           if (CVal >= 0 && CVal <= 65535)
10531             break;
10532         return;
10533       case 'I':
10534         if (Subtarget->isThumb1Only()) {
10535           // This must be a constant between 0 and 255, for ADD
10536           // immediates.
10537           if (CVal >= 0 && CVal <= 255)
10538             break;
10539         } else if (Subtarget->isThumb2()) {
10540           // A constant that can be used as an immediate value in a
10541           // data-processing instruction.
10542           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10543             break;
10544         } else {
10545           // A constant that can be used as an immediate value in a
10546           // data-processing instruction.
10547           if (ARM_AM::getSOImmVal(CVal) != -1)
10548             break;
10549         }
10550         return;
10551
10552       case 'J':
10553         if (Subtarget->isThumb()) {  // FIXME thumb2
10554           // This must be a constant between -255 and -1, for negated ADD
10555           // immediates. This can be used in GCC with an "n" modifier that
10556           // prints the negated value, for use with SUB instructions. It is
10557           // not useful otherwise but is implemented for compatibility.
10558           if (CVal >= -255 && CVal <= -1)
10559             break;
10560         } else {
10561           // This must be a constant between -4095 and 4095. It is not clear
10562           // what this constraint is intended for. Implemented for
10563           // compatibility with GCC.
10564           if (CVal >= -4095 && CVal <= 4095)
10565             break;
10566         }
10567         return;
10568
10569       case 'K':
10570         if (Subtarget->isThumb1Only()) {
10571           // A 32-bit value where only one byte has a nonzero value. Exclude
10572           // zero to match GCC. This constraint is used by GCC internally for
10573           // constants that can be loaded with a move/shift combination.
10574           // It is not useful otherwise but is implemented for compatibility.
10575           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10576             break;
10577         } else if (Subtarget->isThumb2()) {
10578           // A constant whose bitwise inverse can be used as an immediate
10579           // value in a data-processing instruction. This can be used in GCC
10580           // with a "B" modifier that prints the inverted value, for use with
10581           // BIC and MVN instructions. It is not useful otherwise but is
10582           // implemented for compatibility.
10583           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10584             break;
10585         } else {
10586           // A constant whose bitwise inverse can be used as an immediate
10587           // value in a data-processing instruction. This can be used in GCC
10588           // with a "B" modifier that prints the inverted value, for use with
10589           // BIC and MVN instructions. It is not useful otherwise but is
10590           // implemented for compatibility.
10591           if (ARM_AM::getSOImmVal(~CVal) != -1)
10592             break;
10593         }
10594         return;
10595
10596       case 'L':
10597         if (Subtarget->isThumb1Only()) {
10598           // This must be a constant between -7 and 7,
10599           // for 3-operand ADD/SUB immediate instructions.
10600           if (CVal >= -7 && CVal < 7)
10601             break;
10602         } else if (Subtarget->isThumb2()) {
10603           // A constant whose negation can be used as an immediate value in a
10604           // data-processing instruction. This can be used in GCC with an "n"
10605           // modifier that prints the negated value, for use with SUB
10606           // instructions. It is not useful otherwise but is implemented for
10607           // compatibility.
10608           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10609             break;
10610         } else {
10611           // A constant whose negation can be used as an immediate value in a
10612           // data-processing instruction. This can be used in GCC with an "n"
10613           // modifier that prints the negated value, for use with SUB
10614           // instructions. It is not useful otherwise but is implemented for
10615           // compatibility.
10616           if (ARM_AM::getSOImmVal(-CVal) != -1)
10617             break;
10618         }
10619         return;
10620
10621       case 'M':
10622         if (Subtarget->isThumb()) { // FIXME thumb2
10623           // This must be a multiple of 4 between 0 and 1020, for
10624           // ADD sp + immediate.
10625           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10626             break;
10627         } else {
10628           // A power of two or a constant between 0 and 32.  This is used in
10629           // GCC for the shift amount on shifted register operands, but it is
10630           // useful in general for any shift amounts.
10631           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10632             break;
10633         }
10634         return;
10635
10636       case 'N':
10637         if (Subtarget->isThumb()) {  // FIXME thumb2
10638           // This must be a constant between 0 and 31, for shift amounts.
10639           if (CVal >= 0 && CVal <= 31)
10640             break;
10641         }
10642         return;
10643
10644       case 'O':
10645         if (Subtarget->isThumb()) {  // FIXME thumb2
10646           // This must be a multiple of 4 between -508 and 508, for
10647           // ADD/SUB sp = sp + immediate.
10648           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10649             break;
10650         }
10651         return;
10652     }
10653     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10654     break;
10655   }
10656
10657   if (Result.getNode()) {
10658     Ops.push_back(Result);
10659     return;
10660   }
10661   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10662 }
10663
10664 bool
10665 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10666   // The ARM target isn't yet aware of offsets.
10667   return false;
10668 }
10669
10670 bool ARM::isBitFieldInvertedMask(unsigned v) {
10671   if (v == 0xffffffff)
10672     return false;
10673
10674   // there can be 1's on either or both "outsides", all the "inside"
10675   // bits must be 0's
10676   unsigned TO = CountTrailingOnes_32(v);
10677   unsigned LO = CountLeadingOnes_32(v);
10678   v = (v >> TO) << TO;
10679   v = (v << LO) >> LO;
10680   return v == 0;
10681 }
10682
10683 /// isFPImmLegal - Returns true if the target can instruction select the
10684 /// specified FP immediate natively. If false, the legalizer will
10685 /// materialize the FP immediate as a load from a constant pool.
10686 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10687   if (!Subtarget->hasVFP3())
10688     return false;
10689   if (VT == MVT::f32)
10690     return ARM_AM::getFP32Imm(Imm) != -1;
10691   if (VT == MVT::f64)
10692     return ARM_AM::getFP64Imm(Imm) != -1;
10693   return false;
10694 }
10695
10696 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10697 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10698 /// specified in the intrinsic calls.
10699 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10700                                            const CallInst &I,
10701                                            unsigned Intrinsic) const {
10702   switch (Intrinsic) {
10703   case Intrinsic::arm_neon_vld1:
10704   case Intrinsic::arm_neon_vld2:
10705   case Intrinsic::arm_neon_vld3:
10706   case Intrinsic::arm_neon_vld4:
10707   case Intrinsic::arm_neon_vld2lane:
10708   case Intrinsic::arm_neon_vld3lane:
10709   case Intrinsic::arm_neon_vld4lane: {
10710     Info.opc = ISD::INTRINSIC_W_CHAIN;
10711     // Conservatively set memVT to the entire set of vectors loaded.
10712     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10713     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10714     Info.ptrVal = I.getArgOperand(0);
10715     Info.offset = 0;
10716     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10717     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10718     Info.vol = false; // volatile loads with NEON intrinsics not supported
10719     Info.readMem = true;
10720     Info.writeMem = false;
10721     return true;
10722   }
10723   case Intrinsic::arm_neon_vst1:
10724   case Intrinsic::arm_neon_vst2:
10725   case Intrinsic::arm_neon_vst3:
10726   case Intrinsic::arm_neon_vst4:
10727   case Intrinsic::arm_neon_vst2lane:
10728   case Intrinsic::arm_neon_vst3lane:
10729   case Intrinsic::arm_neon_vst4lane: {
10730     Info.opc = ISD::INTRINSIC_VOID;
10731     // Conservatively set memVT to the entire set of vectors stored.
10732     unsigned NumElts = 0;
10733     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10734       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10735       if (!ArgTy->isVectorTy())
10736         break;
10737       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10738     }
10739     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10740     Info.ptrVal = I.getArgOperand(0);
10741     Info.offset = 0;
10742     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10743     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10744     Info.vol = false; // volatile stores with NEON intrinsics not supported
10745     Info.readMem = false;
10746     Info.writeMem = true;
10747     return true;
10748   }
10749   case Intrinsic::arm_strexd: {
10750     Info.opc = ISD::INTRINSIC_W_CHAIN;
10751     Info.memVT = MVT::i64;
10752     Info.ptrVal = I.getArgOperand(2);
10753     Info.offset = 0;
10754     Info.align = 8;
10755     Info.vol = true;
10756     Info.readMem = false;
10757     Info.writeMem = true;
10758     return true;
10759   }
10760   case Intrinsic::arm_ldrexd: {
10761     Info.opc = ISD::INTRINSIC_W_CHAIN;
10762     Info.memVT = MVT::i64;
10763     Info.ptrVal = I.getArgOperand(0);
10764     Info.offset = 0;
10765     Info.align = 8;
10766     Info.vol = true;
10767     Info.readMem = true;
10768     Info.writeMem = false;
10769     return true;
10770   }
10771   default:
10772     break;
10773   }
10774
10775   return false;
10776 }