DAGCombiner: Turn divs of vector splats into vectorized multiplications.
[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 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <utility>
50 using namespace llvm;
51
52 #define DEBUG_TYPE "arm-isel"
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 cl::opt<bool>
59 EnableARMLongCalls("arm-long-calls", cl::Hidden,
60   cl::desc("Generate calls via indirect call instructions"),
61   cl::init(false));
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
73                LLVMContext &C, ParmContext PC)
74         : CCState(CC, isVarArg, MF, TM, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145 }
146
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148   addRegisterClass(VT, &ARM::DPRRegClass);
149   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
150 }
151
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPairRegClass);
154   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
155 }
156
157 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
158   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
159     return new TargetLoweringObjectFileMachO();
160
161   return new ARMElfTargetObjectFile();
162 }
163
164 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
165     : TargetLowering(TM, createTLOF(TM)) {
166   Subtarget = &TM.getSubtarget<ARMSubtarget>();
167   RegInfo = TM.getRegisterInfo();
168   Itins = TM.getInstrItineraryData();
169
170   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
171
172   if (Subtarget->isTargetMachO()) {
173     // Uses VFP for Thumb libfuncs if available.
174     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
175         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
176       // Single-precision floating-point arithmetic.
177       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
178       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
179       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
180       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
181
182       // Double-precision floating-point arithmetic.
183       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
184       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
185       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
186       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
187
188       // Single-precision comparisons.
189       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
190       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
191       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
192       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
193       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
194       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
195       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
196       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
197
198       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
205       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
206
207       // Double-precision comparisons.
208       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
209       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
210       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
211       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
212       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
213       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
214       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
215       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
216
217       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
224       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
225
226       // Floating-point to integer conversions.
227       // i64 conversions are done via library routines even when generating VFP
228       // instructions, so use the same ones.
229       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
231       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
233
234       // Conversions between floating types.
235       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
236       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
237
238       // Integer to floating-point conversions.
239       // i64 conversions are done via library routines even when generating VFP
240       // instructions, so use the same ones.
241       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
242       // e.g., __floatunsidf vs. __floatunssidfvfp.
243       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
245       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
247     }
248   }
249
250   // These libcalls are not available in 32-bit.
251   setLibcallName(RTLIB::SHL_I128, nullptr);
252   setLibcallName(RTLIB::SRL_I128, nullptr);
253   setLibcallName(RTLIB::SRA_I128, nullptr);
254
255   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
256       !Subtarget->isTargetWindows()) {
257     // Double-precision floating-point arithmetic helper functions
258     // RTABI chapter 4.1.2, Table 2
259     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
260     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
261     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
262     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
263     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
264     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
265     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
267
268     // Double-precision floating-point comparison helper functions
269     // RTABI chapter 4.1.2, Table 3
270     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
271     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
272     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
274     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
275     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
276     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
277     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
279     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
281     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
282     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
283     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
284     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
286     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
287     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
288     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
294
295     // Single-precision floating-point arithmetic helper functions
296     // RTABI chapter 4.1.2, Table 4
297     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
298     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
299     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
300     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
301     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
302     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
303     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
305
306     // Single-precision floating-point comparison helper functions
307     // RTABI chapter 4.1.2, Table 5
308     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
309     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
310     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
312     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
313     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
314     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
315     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
317     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
319     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
320     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
321     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
322     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
324     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
325     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
326     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
332
333     // Floating-point to integer conversions.
334     // RTABI chapter 4.1.2, Table 6
335     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
336     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
337     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
339     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
340     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
343     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
344     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
351
352     // Conversions between floating types.
353     // RTABI chapter 4.1.2, Table 7
354     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
355     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
356     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
358
359     // Integer to floating-point conversions.
360     // RTABI chapter 4.1.2, Table 8
361     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
362     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
363     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
364     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
365     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
366     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
367     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
368     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
369     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
370     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
377
378     // Long long helper functions
379     // RTABI chapter 4.2, Table 9
380     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
381     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
382     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
383     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
384     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
385     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
390
391     // Integer division functions
392     // RTABI chapter 4.3.1
393     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
394     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
395     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
397     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
398     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
399     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
401     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
402     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
403     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
409
410     // Memory operations
411     // RTABI chapter 4.3.4
412     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
413     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
414     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
415     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
416     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
417     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
418   }
419
420   // Use divmod compiler-rt calls for iOS 5.0 and later.
421   if (Subtarget->getTargetTriple().isiOS() &&
422       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
423     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
424     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
425   }
426
427   if (Subtarget->isThumb1Only())
428     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
429   else
430     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
431   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
432       !Subtarget->isThumb1Only()) {
433     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
434     if (!Subtarget->isFPOnlySP())
435       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
436
437     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
438   }
439
440   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
441        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
442     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
444       setTruncStoreAction((MVT::SimpleValueType)VT,
445                           (MVT::SimpleValueType)InnerVT, Expand);
446     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
447     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
448     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
449
450     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
451     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
452     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
453     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
454   }
455
456   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
511
512     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
527
528     // Mark v2f32 intrinsics.
529     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
544
545     // Neon does not support some operations on v1i64 and v2i64 types.
546     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547     // Custom handling for some quad-vector types to detect VMULL.
548     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551     // Custom handling for some vector types to avoid expensive expansions
552     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559     // a destination type that is wider than the source, and nor does
560     // it have a FP_TO_[SU]INT instruction with a narrower destination than
561     // source.
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
566
567     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
568     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
569
570     // NEON does not have single instruction CTPOP for vectors with element
571     // types wider than 8-bits.  However, custom lowering can leverage the
572     // v8i8/v16i8 vcnt instruction.
573     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
574     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
575     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
576     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
577
578     // NEON only has FMA instructions as of VFP4.
579     if (!Subtarget->hasVFP4()) {
580       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
582     }
583
584     setTargetDAGCombine(ISD::INTRINSIC_VOID);
585     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587     setTargetDAGCombine(ISD::SHL);
588     setTargetDAGCombine(ISD::SRL);
589     setTargetDAGCombine(ISD::SRA);
590     setTargetDAGCombine(ISD::SIGN_EXTEND);
591     setTargetDAGCombine(ISD::ZERO_EXTEND);
592     setTargetDAGCombine(ISD::ANY_EXTEND);
593     setTargetDAGCombine(ISD::SELECT_CC);
594     setTargetDAGCombine(ISD::BUILD_VECTOR);
595     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597     setTargetDAGCombine(ISD::STORE);
598     setTargetDAGCombine(ISD::FP_TO_SINT);
599     setTargetDAGCombine(ISD::FP_TO_UINT);
600     setTargetDAGCombine(ISD::FDIV);
601
602     // It is legal to extload from v4i8 to v4i16 or v4i32.
603     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604                   MVT::v4i16, MVT::v2i16,
605                   MVT::v2i32};
606     for (unsigned i = 0; i < 6; ++i) {
607       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
610     }
611   }
612
613   // ARM and Thumb2 support UMLAL/SMLAL.
614   if (!Subtarget->isThumb1Only())
615     setTargetDAGCombine(ISD::ADDC);
616
617
618   computeRegisterProperties();
619
620   // ARM does not have f32 extending load.
621   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
622
623   // ARM does not have i1 sign extending load.
624   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
625
626   // ARM supports all 4 flavors of integer indexed load / store.
627   if (!Subtarget->isThumb1Only()) {
628     for (unsigned im = (unsigned)ISD::PRE_INC;
629          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630       setIndexedLoadAction(im,  MVT::i1,  Legal);
631       setIndexedLoadAction(im,  MVT::i8,  Legal);
632       setIndexedLoadAction(im,  MVT::i16, Legal);
633       setIndexedLoadAction(im,  MVT::i32, Legal);
634       setIndexedStoreAction(im, MVT::i1,  Legal);
635       setIndexedStoreAction(im, MVT::i8,  Legal);
636       setIndexedStoreAction(im, MVT::i16, Legal);
637       setIndexedStoreAction(im, MVT::i32, Legal);
638     }
639   }
640
641   // i64 operation support.
642   setOperationAction(ISD::MUL,     MVT::i64, Expand);
643   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
644   if (Subtarget->isThumb1Only()) {
645     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
647   }
648   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650     setOperationAction(ISD::MULHS, MVT::i32, Expand);
651
652   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655   setOperationAction(ISD::SRL,       MVT::i64, Custom);
656   setOperationAction(ISD::SRA,       MVT::i64, Custom);
657
658   if (!Subtarget->isThumb1Only()) {
659     // FIXME: We should do this for Thumb1 as well.
660     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
661     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
662     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
663     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
664   }
665
666   // ARM does not have ROTL.
667   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
668   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
669   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
672
673   // These just redirect to CTTZ and CTLZ on ARM.
674   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
675   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
676
677   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
678
679   // Only ARMv6 has BSWAP.
680   if (!Subtarget->hasV6Ops())
681     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
682
683   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685     // These are expanded into libcalls if the cpu doesn't have HW divider.
686     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
687     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
688   }
689
690   // FIXME: Also set divmod for SREM on EABI
691   setOperationAction(ISD::SREM,  MVT::i32, Expand);
692   setOperationAction(ISD::UREM,  MVT::i32, Expand);
693   // Register based DivRem for AEABI (RTABI 4.2)
694   if (Subtarget->isTargetAEABI()) {
695     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
696     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
700     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
703
704     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
712
713     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
715   } else {
716     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
718   }
719
720   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
721   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
722   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
725
726   setOperationAction(ISD::TRAP, MVT::Other, Legal);
727
728   // Use the default implementation.
729   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
730   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
731   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
732   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
733   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
734   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
735
736   if (!Subtarget->isTargetMachO()) {
737     // Non-MachO platforms may return values in these registers via the
738     // personality function.
739     setExceptionPointerRegister(ARM::R0);
740     setExceptionSelectorRegister(ARM::R1);
741   }
742
743   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745   // the default expansion.
746   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
748     // to ldrex/strex loops already.
749     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
750
751     // On v8, we have particularly efficient implementations of atomic fences
752     // if they can be combined with nearby atomic loads and stores.
753     if (!Subtarget->hasV8Ops()) {
754       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
755       setInsertFencesForAtomic(true);
756     }
757   } else {
758     // If there's anything we can use as a barrier, go through custom lowering
759     // for ATOMIC_FENCE.
760     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
761                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
762
763     // Set them all for expansion, which will force libcalls.
764     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
765     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
766     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
767     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
768     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
769     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
770     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
771     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
772     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
773     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
774     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
775     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
776     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
777     // Unordered/Monotonic case.
778     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
779     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
780   }
781
782   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
783
784   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
785   if (!Subtarget->hasV6Ops()) {
786     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
787     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
788   }
789   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
790
791   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
792       !Subtarget->isThumb1Only()) {
793     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
794     // iff target supports vfp2.
795     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
796     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
797   }
798
799   // We want to custom lower some of our intrinsics.
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
801   if (Subtarget->isTargetDarwin()) {
802     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
803     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
804     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
805   }
806
807   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
808   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
809   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
810   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
811   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
812   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
813   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
814   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
815   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
816
817   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
818   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
819   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
820   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
821   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
822
823   // We don't support sin/cos/fmod/copysign/pow
824   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
825   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
826   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
827   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
828   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
829   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
830   setOperationAction(ISD::FREM,      MVT::f64, Expand);
831   setOperationAction(ISD::FREM,      MVT::f32, Expand);
832   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
833       !Subtarget->isThumb1Only()) {
834     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
835     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
836   }
837   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
838   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
839
840   if (!Subtarget->hasVFP4()) {
841     setOperationAction(ISD::FMA, MVT::f64, Expand);
842     setOperationAction(ISD::FMA, MVT::f32, Expand);
843   }
844
845   // Various VFP goodness
846   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
847     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
848     if (Subtarget->hasVFP2()) {
849       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
850       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
851       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
852       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
853     }
854     // Special handling for half-precision FP.
855     if (!Subtarget->hasFP16()) {
856       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
857       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
858     }
859   }
860
861   // Combine sin / cos into one node or libcall if possible.
862   if (Subtarget->hasSinCos()) {
863     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
864     setLibcallName(RTLIB::SINCOS_F64, "sincos");
865     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
866       // For iOS, we don't want to the normal expansion of a libcall to
867       // sincos. We want to issue a libcall to __sincos_stret.
868       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
869       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
870     }
871   }
872
873   // We have target-specific dag combine patterns for the following nodes:
874   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
875   setTargetDAGCombine(ISD::ADD);
876   setTargetDAGCombine(ISD::SUB);
877   setTargetDAGCombine(ISD::MUL);
878   setTargetDAGCombine(ISD::AND);
879   setTargetDAGCombine(ISD::OR);
880   setTargetDAGCombine(ISD::XOR);
881
882   if (Subtarget->hasV6Ops())
883     setTargetDAGCombine(ISD::SRL);
884
885   setStackPointerRegisterToSaveRestore(ARM::SP);
886
887   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
888       !Subtarget->hasVFP2())
889     setSchedulingPreference(Sched::RegPressure);
890   else
891     setSchedulingPreference(Sched::Hybrid);
892
893   //// temporary - rewrite interface to use type
894   MaxStoresPerMemset = 8;
895   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
896   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
897   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
898   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
899   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
900
901   // On ARM arguments smaller than 4 bytes are extended, so all arguments
902   // are at least 4 bytes aligned.
903   setMinStackArgumentAlignment(4);
904
905   // Prefer likely predicted branches to selects on out-of-order cores.
906   PredictableSelectIsExpensive = Subtarget->isLikeA9();
907
908   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
909 }
910
911 // FIXME: It might make sense to define the representative register class as the
912 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
913 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
914 // SPR's representative would be DPR_VFP2. This should work well if register
915 // pressure tracking were modified such that a register use would increment the
916 // pressure of the register class's representative and all of it's super
917 // classes' representatives transitively. We have not implemented this because
918 // of the difficulty prior to coalescing of modeling operand register classes
919 // due to the common occurrence of cross class copies and subregister insertions
920 // and extractions.
921 std::pair<const TargetRegisterClass*, uint8_t>
922 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
923   const TargetRegisterClass *RRC = nullptr;
924   uint8_t Cost = 1;
925   switch (VT.SimpleTy) {
926   default:
927     return TargetLowering::findRepresentativeClass(VT);
928   // Use DPR as representative register class for all floating point
929   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
930   // the cost is 1 for both f32 and f64.
931   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
932   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
933     RRC = &ARM::DPRRegClass;
934     // When NEON is used for SP, only half of the register file is available
935     // because operations that define both SP and DP results will be constrained
936     // to the VFP2 class (D0-D15). We currently model this constraint prior to
937     // coalescing by double-counting the SP regs. See the FIXME above.
938     if (Subtarget->useNEONForSinglePrecisionFP())
939       Cost = 2;
940     break;
941   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
942   case MVT::v4f32: case MVT::v2f64:
943     RRC = &ARM::DPRRegClass;
944     Cost = 2;
945     break;
946   case MVT::v4i64:
947     RRC = &ARM::DPRRegClass;
948     Cost = 4;
949     break;
950   case MVT::v8i64:
951     RRC = &ARM::DPRRegClass;
952     Cost = 8;
953     break;
954   }
955   return std::make_pair(RRC, Cost);
956 }
957
958 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
959   switch (Opcode) {
960   default: return nullptr;
961   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
962   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
963   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
964   case ARMISD::CALL:          return "ARMISD::CALL";
965   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
966   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
967   case ARMISD::tCALL:         return "ARMISD::tCALL";
968   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
969   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
970   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
971   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
972   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
973   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
974   case ARMISD::CMP:           return "ARMISD::CMP";
975   case ARMISD::CMN:           return "ARMISD::CMN";
976   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
977   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
978   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
979   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
980   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
981
982   case ARMISD::CMOV:          return "ARMISD::CMOV";
983
984   case ARMISD::RBIT:          return "ARMISD::RBIT";
985
986   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
987   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
988   case ARMISD::SITOF:         return "ARMISD::SITOF";
989   case ARMISD::UITOF:         return "ARMISD::UITOF";
990
991   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
992   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
993   case ARMISD::RRX:           return "ARMISD::RRX";
994
995   case ARMISD::ADDC:          return "ARMISD::ADDC";
996   case ARMISD::ADDE:          return "ARMISD::ADDE";
997   case ARMISD::SUBC:          return "ARMISD::SUBC";
998   case ARMISD::SUBE:          return "ARMISD::SUBE";
999
1000   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1001   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1002
1003   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1004   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1005
1006   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1007
1008   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1009
1010   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1011
1012   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1013
1014   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1015
1016   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1017   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1018   case ARMISD::VCGE:          return "ARMISD::VCGE";
1019   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1020   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1021   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1022   case ARMISD::VCGT:          return "ARMISD::VCGT";
1023   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1024   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1025   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1026   case ARMISD::VTST:          return "ARMISD::VTST";
1027
1028   case ARMISD::VSHL:          return "ARMISD::VSHL";
1029   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1030   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1031   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1032   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1033   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1034   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1035   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1036   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1037   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1038   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1039   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1040   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1041   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1042   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1043   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1044   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1045   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1046   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1047   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1048   case ARMISD::VDUP:          return "ARMISD::VDUP";
1049   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1050   case ARMISD::VEXT:          return "ARMISD::VEXT";
1051   case ARMISD::VREV64:        return "ARMISD::VREV64";
1052   case ARMISD::VREV32:        return "ARMISD::VREV32";
1053   case ARMISD::VREV16:        return "ARMISD::VREV16";
1054   case ARMISD::VZIP:          return "ARMISD::VZIP";
1055   case ARMISD::VUZP:          return "ARMISD::VUZP";
1056   case ARMISD::VTRN:          return "ARMISD::VTRN";
1057   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1058   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1059   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1060   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1061   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1062   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1063   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1064   case ARMISD::FMAX:          return "ARMISD::FMAX";
1065   case ARMISD::FMIN:          return "ARMISD::FMIN";
1066   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1067   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1068   case ARMISD::BFI:           return "ARMISD::BFI";
1069   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1070   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1071   case ARMISD::VBSL:          return "ARMISD::VBSL";
1072   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1073   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1074   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1075   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1076   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1077   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1078   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1079   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1080   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1081   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1082   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1083   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1084   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1085   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1086   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1087   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1088   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1089   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1090   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1091   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1092   }
1093 }
1094
1095 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1096   if (!VT.isVector()) return getPointerTy();
1097   return VT.changeVectorElementTypeToInteger();
1098 }
1099
1100 /// getRegClassFor - Return the register class that should be used for the
1101 /// specified value type.
1102 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1103   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1104   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1105   // load / store 4 to 8 consecutive D registers.
1106   if (Subtarget->hasNEON()) {
1107     if (VT == MVT::v4i64)
1108       return &ARM::QQPRRegClass;
1109     if (VT == MVT::v8i64)
1110       return &ARM::QQQQPRRegClass;
1111   }
1112   return TargetLowering::getRegClassFor(VT);
1113 }
1114
1115 // Create a fast isel object.
1116 FastISel *
1117 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1118                                   const TargetLibraryInfo *libInfo) const {
1119   return ARM::createFastISel(funcInfo, libInfo);
1120 }
1121
1122 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1123 /// be used for loads / stores from the global.
1124 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1125   return (Subtarget->isThumb1Only() ? 127 : 4095);
1126 }
1127
1128 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1129   unsigned NumVals = N->getNumValues();
1130   if (!NumVals)
1131     return Sched::RegPressure;
1132
1133   for (unsigned i = 0; i != NumVals; ++i) {
1134     EVT VT = N->getValueType(i);
1135     if (VT == MVT::Glue || VT == MVT::Other)
1136       continue;
1137     if (VT.isFloatingPoint() || VT.isVector())
1138       return Sched::ILP;
1139   }
1140
1141   if (!N->isMachineOpcode())
1142     return Sched::RegPressure;
1143
1144   // Load are scheduled for latency even if there instruction itinerary
1145   // is not available.
1146   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1147   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1148
1149   if (MCID.getNumDefs() == 0)
1150     return Sched::RegPressure;
1151   if (!Itins->isEmpty() &&
1152       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1153     return Sched::ILP;
1154
1155   return Sched::RegPressure;
1156 }
1157
1158 //===----------------------------------------------------------------------===//
1159 // Lowering Code
1160 //===----------------------------------------------------------------------===//
1161
1162 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1163 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1164   switch (CC) {
1165   default: llvm_unreachable("Unknown condition code!");
1166   case ISD::SETNE:  return ARMCC::NE;
1167   case ISD::SETEQ:  return ARMCC::EQ;
1168   case ISD::SETGT:  return ARMCC::GT;
1169   case ISD::SETGE:  return ARMCC::GE;
1170   case ISD::SETLT:  return ARMCC::LT;
1171   case ISD::SETLE:  return ARMCC::LE;
1172   case ISD::SETUGT: return ARMCC::HI;
1173   case ISD::SETUGE: return ARMCC::HS;
1174   case ISD::SETULT: return ARMCC::LO;
1175   case ISD::SETULE: return ARMCC::LS;
1176   }
1177 }
1178
1179 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1180 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1181                         ARMCC::CondCodes &CondCode2) {
1182   CondCode2 = ARMCC::AL;
1183   switch (CC) {
1184   default: llvm_unreachable("Unknown FP condition!");
1185   case ISD::SETEQ:
1186   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1187   case ISD::SETGT:
1188   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1189   case ISD::SETGE:
1190   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1191   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1192   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1193   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1194   case ISD::SETO:   CondCode = ARMCC::VC; break;
1195   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1196   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1197   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1198   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1199   case ISD::SETLT:
1200   case ISD::SETULT: CondCode = ARMCC::LT; break;
1201   case ISD::SETLE:
1202   case ISD::SETULE: CondCode = ARMCC::LE; break;
1203   case ISD::SETNE:
1204   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1205   }
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 //                      Calling Convention Implementation
1210 //===----------------------------------------------------------------------===//
1211
1212 #include "ARMGenCallingConv.inc"
1213
1214 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1215 /// given CallingConvention value.
1216 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1217                                                  bool Return,
1218                                                  bool isVarArg) const {
1219   switch (CC) {
1220   default:
1221     llvm_unreachable("Unsupported calling convention");
1222   case CallingConv::Fast:
1223     if (Subtarget->hasVFP2() && !isVarArg) {
1224       if (!Subtarget->isAAPCS_ABI())
1225         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1226       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1227       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1228     }
1229     // Fallthrough
1230   case CallingConv::C: {
1231     // Use target triple & subtarget features to do actual dispatch.
1232     if (!Subtarget->isAAPCS_ABI())
1233       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1234     else if (Subtarget->hasVFP2() &&
1235              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1236              !isVarArg)
1237       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1238     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1239   }
1240   case CallingConv::ARM_AAPCS_VFP:
1241     if (!isVarArg)
1242       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1243     // Fallthrough
1244   case CallingConv::ARM_AAPCS:
1245     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1246   case CallingConv::ARM_APCS:
1247     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1248   case CallingConv::GHC:
1249     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1250   }
1251 }
1252
1253 /// LowerCallResult - Lower the result values of a call into the
1254 /// appropriate copies out of appropriate physical registers.
1255 SDValue
1256 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1257                                    CallingConv::ID CallConv, bool isVarArg,
1258                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1259                                    SDLoc dl, SelectionDAG &DAG,
1260                                    SmallVectorImpl<SDValue> &InVals,
1261                                    bool isThisReturn, SDValue ThisVal) const {
1262
1263   // Assign locations to each value returned by this call.
1264   SmallVector<CCValAssign, 16> RVLocs;
1265   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1266                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1267   CCInfo.AnalyzeCallResult(Ins,
1268                            CCAssignFnForNode(CallConv, /* Return*/ true,
1269                                              isVarArg));
1270
1271   // Copy all of the result registers out of their specified physreg.
1272   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1273     CCValAssign VA = RVLocs[i];
1274
1275     // Pass 'this' value directly from the argument to return value, to avoid
1276     // reg unit interference
1277     if (i == 0 && isThisReturn) {
1278       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1279              "unexpected return calling convention register assignment");
1280       InVals.push_back(ThisVal);
1281       continue;
1282     }
1283
1284     SDValue Val;
1285     if (VA.needsCustom()) {
1286       // Handle f64 or half of a v2f64.
1287       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1288                                       InFlag);
1289       Chain = Lo.getValue(1);
1290       InFlag = Lo.getValue(2);
1291       VA = RVLocs[++i]; // skip ahead to next loc
1292       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1293                                       InFlag);
1294       Chain = Hi.getValue(1);
1295       InFlag = Hi.getValue(2);
1296       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1297
1298       if (VA.getLocVT() == MVT::v2f64) {
1299         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1300         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1301                           DAG.getConstant(0, MVT::i32));
1302
1303         VA = RVLocs[++i]; // skip ahead to next loc
1304         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1305         Chain = Lo.getValue(1);
1306         InFlag = Lo.getValue(2);
1307         VA = RVLocs[++i]; // skip ahead to next loc
1308         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1309         Chain = Hi.getValue(1);
1310         InFlag = Hi.getValue(2);
1311         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1312         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1313                           DAG.getConstant(1, MVT::i32));
1314       }
1315     } else {
1316       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1317                                InFlag);
1318       Chain = Val.getValue(1);
1319       InFlag = Val.getValue(2);
1320     }
1321
1322     switch (VA.getLocInfo()) {
1323     default: llvm_unreachable("Unknown loc info!");
1324     case CCValAssign::Full: break;
1325     case CCValAssign::BCvt:
1326       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1327       break;
1328     }
1329
1330     InVals.push_back(Val);
1331   }
1332
1333   return Chain;
1334 }
1335
1336 /// LowerMemOpCallTo - Store the argument to the stack.
1337 SDValue
1338 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1339                                     SDValue StackPtr, SDValue Arg,
1340                                     SDLoc dl, SelectionDAG &DAG,
1341                                     const CCValAssign &VA,
1342                                     ISD::ArgFlagsTy Flags) const {
1343   unsigned LocMemOffset = VA.getLocMemOffset();
1344   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1345   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1346   return DAG.getStore(Chain, dl, Arg, PtrOff,
1347                       MachinePointerInfo::getStack(LocMemOffset),
1348                       false, false, 0);
1349 }
1350
1351 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1352                                          SDValue Chain, SDValue &Arg,
1353                                          RegsToPassVector &RegsToPass,
1354                                          CCValAssign &VA, CCValAssign &NextVA,
1355                                          SDValue &StackPtr,
1356                                          SmallVectorImpl<SDValue> &MemOpChains,
1357                                          ISD::ArgFlagsTy Flags) const {
1358
1359   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1360                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1361   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1362
1363   if (NextVA.isRegLoc())
1364     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1365   else {
1366     assert(NextVA.isMemLoc());
1367     if (!StackPtr.getNode())
1368       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1369
1370     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1371                                            dl, DAG, NextVA,
1372                                            Flags));
1373   }
1374 }
1375
1376 /// LowerCall - Lowering a call into a callseq_start <-
1377 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1378 /// nodes.
1379 SDValue
1380 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1381                              SmallVectorImpl<SDValue> &InVals) const {
1382   SelectionDAG &DAG                     = CLI.DAG;
1383   SDLoc &dl                          = CLI.DL;
1384   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1385   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1386   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1387   SDValue Chain                         = CLI.Chain;
1388   SDValue Callee                        = CLI.Callee;
1389   bool &isTailCall                      = CLI.IsTailCall;
1390   CallingConv::ID CallConv              = CLI.CallConv;
1391   bool doesNotRet                       = CLI.DoesNotReturn;
1392   bool isVarArg                         = CLI.IsVarArg;
1393
1394   MachineFunction &MF = DAG.getMachineFunction();
1395   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1396   bool isThisReturn   = false;
1397   bool isSibCall      = false;
1398
1399   // Disable tail calls if they're not supported.
1400   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1401     isTailCall = false;
1402
1403   if (isTailCall) {
1404     // Check if it's really possible to do a tail call.
1405     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1406                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1407                                                    Outs, OutVals, Ins, DAG);
1408     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1409       report_fatal_error("failed to perform tail call elimination on a call "
1410                          "site marked musttail");
1411     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1412     // detected sibcalls.
1413     if (isTailCall) {
1414       ++NumTailCalls;
1415       isSibCall = true;
1416     }
1417   }
1418
1419   // Analyze operands of the call, assigning locations to each operand.
1420   SmallVector<CCValAssign, 16> ArgLocs;
1421   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1422                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1423   CCInfo.AnalyzeCallOperands(Outs,
1424                              CCAssignFnForNode(CallConv, /* Return*/ false,
1425                                                isVarArg));
1426
1427   // Get a count of how many bytes are to be pushed on the stack.
1428   unsigned NumBytes = CCInfo.getNextStackOffset();
1429
1430   // For tail calls, memory operands are available in our caller's stack.
1431   if (isSibCall)
1432     NumBytes = 0;
1433
1434   // Adjust the stack pointer for the new arguments...
1435   // These operations are automatically eliminated by the prolog/epilog pass
1436   if (!isSibCall)
1437     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1438                                  dl);
1439
1440   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1441
1442   RegsToPassVector RegsToPass;
1443   SmallVector<SDValue, 8> MemOpChains;
1444
1445   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1446   // of tail call optimization, arguments are handled later.
1447   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1448        i != e;
1449        ++i, ++realArgIdx) {
1450     CCValAssign &VA = ArgLocs[i];
1451     SDValue Arg = OutVals[realArgIdx];
1452     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1453     bool isByVal = Flags.isByVal();
1454
1455     // Promote the value if needed.
1456     switch (VA.getLocInfo()) {
1457     default: llvm_unreachable("Unknown loc info!");
1458     case CCValAssign::Full: break;
1459     case CCValAssign::SExt:
1460       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1461       break;
1462     case CCValAssign::ZExt:
1463       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1464       break;
1465     case CCValAssign::AExt:
1466       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1467       break;
1468     case CCValAssign::BCvt:
1469       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1470       break;
1471     }
1472
1473     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1474     if (VA.needsCustom()) {
1475       if (VA.getLocVT() == MVT::v2f64) {
1476         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1477                                   DAG.getConstant(0, MVT::i32));
1478         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1479                                   DAG.getConstant(1, MVT::i32));
1480
1481         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1482                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1483
1484         VA = ArgLocs[++i]; // skip ahead to next loc
1485         if (VA.isRegLoc()) {
1486           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1487                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1488         } else {
1489           assert(VA.isMemLoc());
1490
1491           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1492                                                  dl, DAG, VA, Flags));
1493         }
1494       } else {
1495         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1496                          StackPtr, MemOpChains, Flags);
1497       }
1498     } else if (VA.isRegLoc()) {
1499       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1500         assert(VA.getLocVT() == MVT::i32 &&
1501                "unexpected calling convention register assignment");
1502         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1503                "unexpected use of 'returned'");
1504         isThisReturn = true;
1505       }
1506       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1507     } else if (isByVal) {
1508       assert(VA.isMemLoc());
1509       unsigned offset = 0;
1510
1511       // True if this byval aggregate will be split between registers
1512       // and memory.
1513       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1514       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1515
1516       if (CurByValIdx < ByValArgsCount) {
1517
1518         unsigned RegBegin, RegEnd;
1519         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1520
1521         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1522         unsigned int i, j;
1523         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1524           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1525           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1526           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1527                                      MachinePointerInfo(),
1528                                      false, false, false,
1529                                      DAG.InferPtrAlignment(AddArg));
1530           MemOpChains.push_back(Load.getValue(1));
1531           RegsToPass.push_back(std::make_pair(j, Load));
1532         }
1533
1534         // If parameter size outsides register area, "offset" value
1535         // helps us to calculate stack slot for remained part properly.
1536         offset = RegEnd - RegBegin;
1537
1538         CCInfo.nextInRegsParam();
1539       }
1540
1541       if (Flags.getByValSize() > 4*offset) {
1542         unsigned LocMemOffset = VA.getLocMemOffset();
1543         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1544         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1545                                   StkPtrOff);
1546         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1547         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1548         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1549                                            MVT::i32);
1550         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1551
1552         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1553         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1554         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1555                                           Ops, array_lengthof(Ops)));
1556       }
1557     } else if (!isSibCall) {
1558       assert(VA.isMemLoc());
1559
1560       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1561                                              dl, DAG, VA, Flags));
1562     }
1563   }
1564
1565   if (!MemOpChains.empty())
1566     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1567                         &MemOpChains[0], MemOpChains.size());
1568
1569   // Build a sequence of copy-to-reg nodes chained together with token chain
1570   // and flag operands which copy the outgoing args into the appropriate regs.
1571   SDValue InFlag;
1572   // Tail call byval lowering might overwrite argument registers so in case of
1573   // tail call optimization the copies to registers are lowered later.
1574   if (!isTailCall)
1575     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1576       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1577                                RegsToPass[i].second, InFlag);
1578       InFlag = Chain.getValue(1);
1579     }
1580
1581   // For tail calls lower the arguments to the 'real' stack slot.
1582   if (isTailCall) {
1583     // Force all the incoming stack arguments to be loaded from the stack
1584     // before any new outgoing arguments are stored to the stack, because the
1585     // outgoing stack slots may alias the incoming argument stack slots, and
1586     // the alias isn't otherwise explicit. This is slightly more conservative
1587     // than necessary, because it means that each store effectively depends
1588     // on every argument instead of just those arguments it would clobber.
1589
1590     // Do not flag preceding copytoreg stuff together with the following stuff.
1591     InFlag = SDValue();
1592     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1593       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1594                                RegsToPass[i].second, InFlag);
1595       InFlag = Chain.getValue(1);
1596     }
1597     InFlag = SDValue();
1598   }
1599
1600   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1601   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1602   // node so that legalize doesn't hack it.
1603   bool isDirect = false;
1604   bool isARMFunc = false;
1605   bool isLocalARMFunc = false;
1606   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1607
1608   if (EnableARMLongCalls) {
1609     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1610             && "long-calls with non-static relocation model!");
1611     // Handle a global address or an external symbol. If it's not one of
1612     // those, the target's already in a register, so we don't need to do
1613     // anything extra.
1614     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1615       const GlobalValue *GV = G->getGlobal();
1616       // Create a constant pool entry for the callee address
1617       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1618       ARMConstantPoolValue *CPV =
1619         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1620
1621       // Get the address of the callee into a register
1622       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1623       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1624       Callee = DAG.getLoad(getPointerTy(), dl,
1625                            DAG.getEntryNode(), CPAddr,
1626                            MachinePointerInfo::getConstantPool(),
1627                            false, false, false, 0);
1628     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1629       const char *Sym = S->getSymbol();
1630
1631       // Create a constant pool entry for the callee address
1632       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1633       ARMConstantPoolValue *CPV =
1634         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1635                                       ARMPCLabelIndex, 0);
1636       // Get the address of the callee into a register
1637       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1638       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1639       Callee = DAG.getLoad(getPointerTy(), dl,
1640                            DAG.getEntryNode(), CPAddr,
1641                            MachinePointerInfo::getConstantPool(),
1642                            false, false, false, 0);
1643     }
1644   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1645     const GlobalValue *GV = G->getGlobal();
1646     isDirect = true;
1647     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1648     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1649                    getTargetMachine().getRelocationModel() != Reloc::Static;
1650     isARMFunc = !Subtarget->isThumb() || isStub;
1651     // ARM call to a local ARM function is predicable.
1652     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1653     // tBX takes a register source operand.
1654     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1655       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1656       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1657                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1658     } else {
1659       // On ELF targets for PIC code, direct calls should go through the PLT
1660       unsigned OpFlags = 0;
1661       if (Subtarget->isTargetELF() &&
1662           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1663         OpFlags = ARMII::MO_PLT;
1664       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1665     }
1666   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1667     isDirect = true;
1668     bool isStub = Subtarget->isTargetMachO() &&
1669                   getTargetMachine().getRelocationModel() != Reloc::Static;
1670     isARMFunc = !Subtarget->isThumb() || isStub;
1671     // tBX takes a register source operand.
1672     const char *Sym = S->getSymbol();
1673     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1674       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1675       ARMConstantPoolValue *CPV =
1676         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1677                                       ARMPCLabelIndex, 4);
1678       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1679       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1680       Callee = DAG.getLoad(getPointerTy(), dl,
1681                            DAG.getEntryNode(), CPAddr,
1682                            MachinePointerInfo::getConstantPool(),
1683                            false, false, false, 0);
1684       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1685       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1686                            getPointerTy(), Callee, PICLabel);
1687     } else {
1688       unsigned OpFlags = 0;
1689       // On ELF targets for PIC code, direct calls should go through the PLT
1690       if (Subtarget->isTargetELF() &&
1691                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1692         OpFlags = ARMII::MO_PLT;
1693       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1694     }
1695   }
1696
1697   // FIXME: handle tail calls differently.
1698   unsigned CallOpc;
1699   bool HasMinSizeAttr = Subtarget->isMinSize();
1700   if (Subtarget->isThumb()) {
1701     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1702       CallOpc = ARMISD::CALL_NOLINK;
1703     else
1704       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1705   } else {
1706     if (!isDirect && !Subtarget->hasV5TOps())
1707       CallOpc = ARMISD::CALL_NOLINK;
1708     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1709                // Emit regular call when code size is the priority
1710                !HasMinSizeAttr)
1711       // "mov lr, pc; b _foo" to avoid confusing the RSP
1712       CallOpc = ARMISD::CALL_NOLINK;
1713     else
1714       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1715   }
1716
1717   std::vector<SDValue> Ops;
1718   Ops.push_back(Chain);
1719   Ops.push_back(Callee);
1720
1721   // Add argument registers to the end of the list so that they are known live
1722   // into the call.
1723   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1724     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1725                                   RegsToPass[i].second.getValueType()));
1726
1727   // Add a register mask operand representing the call-preserved registers.
1728   if (!isTailCall) {
1729     const uint32_t *Mask;
1730     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1731     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1732     if (isThisReturn) {
1733       // For 'this' returns, use the R0-preserving mask if applicable
1734       Mask = ARI->getThisReturnPreservedMask(CallConv);
1735       if (!Mask) {
1736         // Set isThisReturn to false if the calling convention is not one that
1737         // allows 'returned' to be modeled in this way, so LowerCallResult does
1738         // not try to pass 'this' straight through
1739         isThisReturn = false;
1740         Mask = ARI->getCallPreservedMask(CallConv);
1741       }
1742     } else
1743       Mask = ARI->getCallPreservedMask(CallConv);
1744
1745     assert(Mask && "Missing call preserved mask for calling convention");
1746     Ops.push_back(DAG.getRegisterMask(Mask));
1747   }
1748
1749   if (InFlag.getNode())
1750     Ops.push_back(InFlag);
1751
1752   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1753   if (isTailCall)
1754     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1755
1756   // Returns a chain and a flag for retval copy to use.
1757   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1758   InFlag = Chain.getValue(1);
1759
1760   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1761                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1762   if (!Ins.empty())
1763     InFlag = Chain.getValue(1);
1764
1765   // Handle result values, copying them out of physregs into vregs that we
1766   // return.
1767   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1768                          InVals, isThisReturn,
1769                          isThisReturn ? OutVals[0] : SDValue());
1770 }
1771
1772 /// HandleByVal - Every parameter *after* a byval parameter is passed
1773 /// on the stack.  Remember the next parameter register to allocate,
1774 /// and then confiscate the rest of the parameter registers to insure
1775 /// this.
1776 void
1777 ARMTargetLowering::HandleByVal(
1778     CCState *State, unsigned &size, unsigned Align) const {
1779   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1780   assert((State->getCallOrPrologue() == Prologue ||
1781           State->getCallOrPrologue() == Call) &&
1782          "unhandled ParmContext");
1783
1784   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1785     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1786       unsigned AlignInRegs = Align / 4;
1787       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1788       for (unsigned i = 0; i < Waste; ++i)
1789         reg = State->AllocateReg(GPRArgRegs, 4);
1790     }
1791     if (reg != 0) {
1792       unsigned excess = 4 * (ARM::R4 - reg);
1793
1794       // Special case when NSAA != SP and parameter size greater than size of
1795       // all remained GPR regs. In that case we can't split parameter, we must
1796       // send it to stack. We also must set NCRN to R4, so waste all
1797       // remained registers.
1798       const unsigned NSAAOffset = State->getNextStackOffset();
1799       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1800         while (State->AllocateReg(GPRArgRegs, 4))
1801           ;
1802         return;
1803       }
1804
1805       // First register for byval parameter is the first register that wasn't
1806       // allocated before this method call, so it would be "reg".
1807       // If parameter is small enough to be saved in range [reg, r4), then
1808       // the end (first after last) register would be reg + param-size-in-regs,
1809       // else parameter would be splitted between registers and stack,
1810       // end register would be r4 in this case.
1811       unsigned ByValRegBegin = reg;
1812       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1813       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1814       // Note, first register is allocated in the beginning of function already,
1815       // allocate remained amount of registers we need.
1816       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1817         State->AllocateReg(GPRArgRegs, 4);
1818       // A byval parameter that is split between registers and memory needs its
1819       // size truncated here.
1820       // In the case where the entire structure fits in registers, we set the
1821       // size in memory to zero.
1822       if (size < excess)
1823         size = 0;
1824       else
1825         size -= excess;
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   // Exception-handling functions need a special set of instructions to indicate
1900   // a return to the hardware. Tail-calling another function would probably
1901   // break this.
1902   if (CallerF->hasFnAttribute("interrupt"))
1903     return false;
1904
1905   // Also avoid sibcall optimization if either caller or callee uses struct
1906   // return semantics.
1907   if (isCalleeStructRet || isCallerStructRet)
1908     return false;
1909
1910   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1911   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1912   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1913   // support in the assembler and linker to be used. This would need to be
1914   // fixed to fully support tail calls in Thumb1.
1915   //
1916   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1917   // LR.  This means if we need to reload LR, it takes an extra instructions,
1918   // which outweighs the value of the tail call; but here we don't know yet
1919   // whether LR is going to be used.  Probably the right approach is to
1920   // generate the tail call here and turn it back into CALL/RET in
1921   // emitEpilogue if LR is used.
1922
1923   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1924   // but we need to make sure there are enough registers; the only valid
1925   // registers are the 4 used for parameters.  We don't currently do this
1926   // case.
1927   if (Subtarget->isThumb1Only())
1928     return false;
1929
1930   // If the calling conventions do not match, then we'd better make sure the
1931   // results are returned in the same way as what the caller expects.
1932   if (!CCMatch) {
1933     SmallVector<CCValAssign, 16> RVLocs1;
1934     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1935                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1936     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1937
1938     SmallVector<CCValAssign, 16> RVLocs2;
1939     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1940                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1941     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1942
1943     if (RVLocs1.size() != RVLocs2.size())
1944       return false;
1945     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1946       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1947         return false;
1948       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1949         return false;
1950       if (RVLocs1[i].isRegLoc()) {
1951         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1952           return false;
1953       } else {
1954         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1955           return false;
1956       }
1957     }
1958   }
1959
1960   // If Caller's vararg or byval argument has been split between registers and
1961   // stack, do not perform tail call, since part of the argument is in caller's
1962   // local frame.
1963   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1964                                       getInfo<ARMFunctionInfo>();
1965   if (AFI_Caller->getArgRegsSaveSize())
1966     return false;
1967
1968   // If the callee takes no arguments then go on to check the results of the
1969   // call.
1970   if (!Outs.empty()) {
1971     // Check if stack adjustment is needed. For now, do not do this if any
1972     // argument is passed on the stack.
1973     SmallVector<CCValAssign, 16> ArgLocs;
1974     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1975                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1976     CCInfo.AnalyzeCallOperands(Outs,
1977                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1978     if (CCInfo.getNextStackOffset()) {
1979       MachineFunction &MF = DAG.getMachineFunction();
1980
1981       // Check if the arguments are already laid out in the right way as
1982       // the caller's fixed stack objects.
1983       MachineFrameInfo *MFI = MF.getFrameInfo();
1984       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1985       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1986       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1987            i != e;
1988            ++i, ++realArgIdx) {
1989         CCValAssign &VA = ArgLocs[i];
1990         EVT RegVT = VA.getLocVT();
1991         SDValue Arg = OutVals[realArgIdx];
1992         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1993         if (VA.getLocInfo() == CCValAssign::Indirect)
1994           return false;
1995         if (VA.needsCustom()) {
1996           // f64 and vector types are split into multiple registers or
1997           // register/stack-slot combinations.  The types will not match
1998           // the registers; give up on memory f64 refs until we figure
1999           // out what to do about this.
2000           if (!VA.isRegLoc())
2001             return false;
2002           if (!ArgLocs[++i].isRegLoc())
2003             return false;
2004           if (RegVT == MVT::v2f64) {
2005             if (!ArgLocs[++i].isRegLoc())
2006               return false;
2007             if (!ArgLocs[++i].isRegLoc())
2008               return false;
2009           }
2010         } else if (!VA.isRegLoc()) {
2011           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2012                                    MFI, MRI, TII))
2013             return false;
2014         }
2015       }
2016     }
2017   }
2018
2019   return true;
2020 }
2021
2022 bool
2023 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2024                                   MachineFunction &MF, bool isVarArg,
2025                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2026                                   LLVMContext &Context) const {
2027   SmallVector<CCValAssign, 16> RVLocs;
2028   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2029   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2030                                                     isVarArg));
2031 }
2032
2033 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2034                                     SDLoc DL, SelectionDAG &DAG) {
2035   const MachineFunction &MF = DAG.getMachineFunction();
2036   const Function *F = MF.getFunction();
2037
2038   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2039
2040   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2041   // version of the "preferred return address". These offsets affect the return
2042   // instruction if this is a return from PL1 without hypervisor extensions.
2043   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2044   //    SWI:     0      "subs pc, lr, #0"
2045   //    ABORT:   +4     "subs pc, lr, #4"
2046   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2047   // UNDEF varies depending on where the exception came from ARM or Thumb
2048   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2049
2050   int64_t LROffset;
2051   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2052       IntKind == "ABORT")
2053     LROffset = 4;
2054   else if (IntKind == "SWI" || IntKind == "UNDEF")
2055     LROffset = 0;
2056   else
2057     report_fatal_error("Unsupported interrupt attribute. If present, value "
2058                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2059
2060   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2061
2062   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2063                      RetOps.data(), RetOps.size());
2064 }
2065
2066 SDValue
2067 ARMTargetLowering::LowerReturn(SDValue Chain,
2068                                CallingConv::ID CallConv, bool isVarArg,
2069                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2070                                const SmallVectorImpl<SDValue> &OutVals,
2071                                SDLoc dl, SelectionDAG &DAG) const {
2072
2073   // CCValAssign - represent the assignment of the return value to a location.
2074   SmallVector<CCValAssign, 16> RVLocs;
2075
2076   // CCState - Info about the registers and stack slots.
2077   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2078                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2079
2080   // Analyze outgoing return values.
2081   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2082                                                isVarArg));
2083
2084   SDValue Flag;
2085   SmallVector<SDValue, 4> RetOps;
2086   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2087
2088   // Copy the result values into the output registers.
2089   for (unsigned i = 0, realRVLocIdx = 0;
2090        i != RVLocs.size();
2091        ++i, ++realRVLocIdx) {
2092     CCValAssign &VA = RVLocs[i];
2093     assert(VA.isRegLoc() && "Can only return in registers!");
2094
2095     SDValue Arg = OutVals[realRVLocIdx];
2096
2097     switch (VA.getLocInfo()) {
2098     default: llvm_unreachable("Unknown loc info!");
2099     case CCValAssign::Full: break;
2100     case CCValAssign::BCvt:
2101       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2102       break;
2103     }
2104
2105     if (VA.needsCustom()) {
2106       if (VA.getLocVT() == MVT::v2f64) {
2107         // Extract the first half and return it in two registers.
2108         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2109                                    DAG.getConstant(0, MVT::i32));
2110         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2111                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2112
2113         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2114         Flag = Chain.getValue(1);
2115         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2116         VA = RVLocs[++i]; // skip ahead to next loc
2117         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2118                                  HalfGPRs.getValue(1), Flag);
2119         Flag = Chain.getValue(1);
2120         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2121         VA = RVLocs[++i]; // skip ahead to next loc
2122
2123         // Extract the 2nd half and fall through to handle it as an f64 value.
2124         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2125                           DAG.getConstant(1, MVT::i32));
2126       }
2127       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2128       // available.
2129       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2130                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2131       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2132       Flag = Chain.getValue(1);
2133       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2134       VA = RVLocs[++i]; // skip ahead to next loc
2135       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2136                                Flag);
2137     } else
2138       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2139
2140     // Guarantee that all emitted copies are
2141     // stuck together, avoiding something bad.
2142     Flag = Chain.getValue(1);
2143     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2144   }
2145
2146   // Update chain and glue.
2147   RetOps[0] = Chain;
2148   if (Flag.getNode())
2149     RetOps.push_back(Flag);
2150
2151   // CPUs which aren't M-class use a special sequence to return from
2152   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2153   // though we use "subs pc, lr, #N").
2154   //
2155   // M-class CPUs actually use a normal return sequence with a special
2156   // (hardware-provided) value in LR, so the normal code path works.
2157   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2158       !Subtarget->isMClass()) {
2159     if (Subtarget->isThumb1Only())
2160       report_fatal_error("interrupt attribute is not supported in Thumb1");
2161     return LowerInterruptReturn(RetOps, dl, DAG);
2162   }
2163
2164   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2165                      RetOps.data(), RetOps.size());
2166 }
2167
2168 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2169   if (N->getNumValues() != 1)
2170     return false;
2171   if (!N->hasNUsesOfValue(1, 0))
2172     return false;
2173
2174   SDValue TCChain = Chain;
2175   SDNode *Copy = *N->use_begin();
2176   if (Copy->getOpcode() == ISD::CopyToReg) {
2177     // If the copy has a glue operand, we conservatively assume it isn't safe to
2178     // perform a tail call.
2179     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2180       return false;
2181     TCChain = Copy->getOperand(0);
2182   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2183     SDNode *VMov = Copy;
2184     // f64 returned in a pair of GPRs.
2185     SmallPtrSet<SDNode*, 2> Copies;
2186     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2187          UI != UE; ++UI) {
2188       if (UI->getOpcode() != ISD::CopyToReg)
2189         return false;
2190       Copies.insert(*UI);
2191     }
2192     if (Copies.size() > 2)
2193       return false;
2194
2195     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2196          UI != UE; ++UI) {
2197       SDValue UseChain = UI->getOperand(0);
2198       if (Copies.count(UseChain.getNode()))
2199         // Second CopyToReg
2200         Copy = *UI;
2201       else
2202         // First CopyToReg
2203         TCChain = UseChain;
2204     }
2205   } else if (Copy->getOpcode() == ISD::BITCAST) {
2206     // f32 returned in a single GPR.
2207     if (!Copy->hasOneUse())
2208       return false;
2209     Copy = *Copy->use_begin();
2210     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2211       return false;
2212     TCChain = Copy->getOperand(0);
2213   } else {
2214     return false;
2215   }
2216
2217   bool HasRet = false;
2218   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2219        UI != UE; ++UI) {
2220     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2221         UI->getOpcode() != ARMISD::INTRET_FLAG)
2222       return false;
2223     HasRet = true;
2224   }
2225
2226   if (!HasRet)
2227     return false;
2228
2229   Chain = TCChain;
2230   return true;
2231 }
2232
2233 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2234   if (!Subtarget->supportsTailCall())
2235     return false;
2236
2237   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2238     return false;
2239
2240   return !Subtarget->isThumb1Only();
2241 }
2242
2243 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2244 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2245 // one of the above mentioned nodes. It has to be wrapped because otherwise
2246 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2247 // be used to form addressing mode. These wrapped nodes will be selected
2248 // into MOVi.
2249 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2250   EVT PtrVT = Op.getValueType();
2251   // FIXME there is no actual debug info here
2252   SDLoc dl(Op);
2253   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2254   SDValue Res;
2255   if (CP->isMachineConstantPoolEntry())
2256     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2257                                     CP->getAlignment());
2258   else
2259     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2260                                     CP->getAlignment());
2261   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2262 }
2263
2264 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2265   return MachineJumpTableInfo::EK_Inline;
2266 }
2267
2268 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2269                                              SelectionDAG &DAG) const {
2270   MachineFunction &MF = DAG.getMachineFunction();
2271   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2272   unsigned ARMPCLabelIndex = 0;
2273   SDLoc DL(Op);
2274   EVT PtrVT = getPointerTy();
2275   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2276   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2277   SDValue CPAddr;
2278   if (RelocM == Reloc::Static) {
2279     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2280   } else {
2281     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2282     ARMPCLabelIndex = AFI->createPICLabelUId();
2283     ARMConstantPoolValue *CPV =
2284       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2285                                       ARMCP::CPBlockAddress, PCAdj);
2286     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2287   }
2288   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2289   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2290                                MachinePointerInfo::getConstantPool(),
2291                                false, false, false, 0);
2292   if (RelocM == Reloc::Static)
2293     return Result;
2294   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2295   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2296 }
2297
2298 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2299 SDValue
2300 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2301                                                  SelectionDAG &DAG) const {
2302   SDLoc dl(GA);
2303   EVT PtrVT = getPointerTy();
2304   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2305   MachineFunction &MF = DAG.getMachineFunction();
2306   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2307   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2308   ARMConstantPoolValue *CPV =
2309     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2310                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2311   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2312   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2313   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2314                          MachinePointerInfo::getConstantPool(),
2315                          false, false, false, 0);
2316   SDValue Chain = Argument.getValue(1);
2317
2318   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2319   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2320
2321   // call __tls_get_addr.
2322   ArgListTy Args;
2323   ArgListEntry Entry;
2324   Entry.Node = Argument;
2325   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2326   Args.push_back(Entry);
2327   // FIXME: is there useful debug info available here?
2328   TargetLowering::CallLoweringInfo CLI(Chain,
2329                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2330                 false, false, false, false,
2331                 0, CallingConv::C, /*isTailCall=*/false,
2332                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2333                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2334   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2335   return CallResult.first;
2336 }
2337
2338 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2339 // "local exec" model.
2340 SDValue
2341 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2342                                         SelectionDAG &DAG,
2343                                         TLSModel::Model model) const {
2344   const GlobalValue *GV = GA->getGlobal();
2345   SDLoc dl(GA);
2346   SDValue Offset;
2347   SDValue Chain = DAG.getEntryNode();
2348   EVT PtrVT = getPointerTy();
2349   // Get the Thread Pointer
2350   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2351
2352   if (model == TLSModel::InitialExec) {
2353     MachineFunction &MF = DAG.getMachineFunction();
2354     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2355     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2356     // Initial exec model.
2357     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2358     ARMConstantPoolValue *CPV =
2359       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2360                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2361                                       true);
2362     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2363     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2364     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2365                          MachinePointerInfo::getConstantPool(),
2366                          false, false, false, 0);
2367     Chain = Offset.getValue(1);
2368
2369     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2370     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2371
2372     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2373                          MachinePointerInfo::getConstantPool(),
2374                          false, false, false, 0);
2375   } else {
2376     // local exec model
2377     assert(model == TLSModel::LocalExec);
2378     ARMConstantPoolValue *CPV =
2379       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2380     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2381     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2382     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2383                          MachinePointerInfo::getConstantPool(),
2384                          false, false, false, 0);
2385   }
2386
2387   // The address of the thread local variable is the add of the thread
2388   // pointer with the offset of the variable.
2389   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2390 }
2391
2392 SDValue
2393 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2394   // TODO: implement the "local dynamic" model
2395   assert(Subtarget->isTargetELF() &&
2396          "TLS not implemented for non-ELF targets");
2397   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2398
2399   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2400
2401   switch (model) {
2402     case TLSModel::GeneralDynamic:
2403     case TLSModel::LocalDynamic:
2404       return LowerToTLSGeneralDynamicModel(GA, DAG);
2405     case TLSModel::InitialExec:
2406     case TLSModel::LocalExec:
2407       return LowerToTLSExecModels(GA, DAG, model);
2408   }
2409   llvm_unreachable("bogus TLS model");
2410 }
2411
2412 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2413                                                  SelectionDAG &DAG) const {
2414   EVT PtrVT = getPointerTy();
2415   SDLoc dl(Op);
2416   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2417   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2418     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2419     ARMConstantPoolValue *CPV =
2420       ARMConstantPoolConstant::Create(GV,
2421                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2422     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2423     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2424     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2425                                  CPAddr,
2426                                  MachinePointerInfo::getConstantPool(),
2427                                  false, false, false, 0);
2428     SDValue Chain = Result.getValue(1);
2429     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2430     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2431     if (!UseGOTOFF)
2432       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2433                            MachinePointerInfo::getGOT(),
2434                            false, false, false, 0);
2435     return Result;
2436   }
2437
2438   // If we have T2 ops, we can materialize the address directly via movt/movw
2439   // pair. This is always cheaper.
2440   if (Subtarget->useMovt()) {
2441     ++NumMovwMovt;
2442     // FIXME: Once remat is capable of dealing with instructions with register
2443     // operands, expand this into two nodes.
2444     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2445                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2446   } else {
2447     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2448     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2449     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2450                        MachinePointerInfo::getConstantPool(),
2451                        false, false, false, 0);
2452   }
2453 }
2454
2455 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2456                                                     SelectionDAG &DAG) const {
2457   EVT PtrVT = getPointerTy();
2458   SDLoc dl(Op);
2459   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2460   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2461
2462   if (Subtarget->useMovt())
2463     ++NumMovwMovt;
2464
2465   // FIXME: Once remat is capable of dealing with instructions with register
2466   // operands, expand this into multiple nodes
2467   unsigned Wrapper =
2468       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2469
2470   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2471   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2472
2473   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2474     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2475                          MachinePointerInfo::getGOT(), false, false, false, 0);
2476   return Result;
2477 }
2478
2479 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2480                                                     SelectionDAG &DAG) const {
2481   assert(Subtarget->isTargetELF() &&
2482          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2483   MachineFunction &MF = DAG.getMachineFunction();
2484   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2485   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2486   EVT PtrVT = getPointerTy();
2487   SDLoc dl(Op);
2488   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2489   ARMConstantPoolValue *CPV =
2490     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2491                                   ARMPCLabelIndex, PCAdj);
2492   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2494   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2495                                MachinePointerInfo::getConstantPool(),
2496                                false, false, false, 0);
2497   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2498   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2499 }
2500
2501 SDValue
2502 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2503   SDLoc dl(Op);
2504   SDValue Val = DAG.getConstant(0, MVT::i32);
2505   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2506                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2507                      Op.getOperand(1), Val);
2508 }
2509
2510 SDValue
2511 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2512   SDLoc dl(Op);
2513   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2514                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2515 }
2516
2517 SDValue
2518 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2519                                           const ARMSubtarget *Subtarget) const {
2520   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2521   SDLoc dl(Op);
2522   switch (IntNo) {
2523   default: return SDValue();    // Don't custom lower most intrinsics.
2524   case Intrinsic::arm_thread_pointer: {
2525     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2526     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2527   }
2528   case Intrinsic::eh_sjlj_lsda: {
2529     MachineFunction &MF = DAG.getMachineFunction();
2530     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2531     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2532     EVT PtrVT = getPointerTy();
2533     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2534     SDValue CPAddr;
2535     unsigned PCAdj = (RelocM != Reloc::PIC_)
2536       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2537     ARMConstantPoolValue *CPV =
2538       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2539                                       ARMCP::CPLSDA, PCAdj);
2540     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2541     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2542     SDValue Result =
2543       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2544                   MachinePointerInfo::getConstantPool(),
2545                   false, false, false, 0);
2546
2547     if (RelocM == Reloc::PIC_) {
2548       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2549       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2550     }
2551     return Result;
2552   }
2553   case Intrinsic::arm_neon_vmulls:
2554   case Intrinsic::arm_neon_vmullu: {
2555     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2556       ? ARMISD::VMULLs : ARMISD::VMULLu;
2557     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2558                        Op.getOperand(1), Op.getOperand(2));
2559   }
2560   }
2561 }
2562
2563 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2564                                  const ARMSubtarget *Subtarget) {
2565   // FIXME: handle "fence singlethread" more efficiently.
2566   SDLoc dl(Op);
2567   if (!Subtarget->hasDataBarrier()) {
2568     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2569     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2570     // here.
2571     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2572            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2573     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2574                        DAG.getConstant(0, MVT::i32));
2575   }
2576
2577   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2578   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2579   unsigned Domain = ARM_MB::ISH;
2580   if (Subtarget->isMClass()) {
2581     // Only a full system barrier exists in the M-class architectures.
2582     Domain = ARM_MB::SY;
2583   } else if (Subtarget->isSwift() && Ord == Release) {
2584     // Swift happens to implement ISHST barriers in a way that's compatible with
2585     // Release semantics but weaker than ISH so we'd be fools not to use
2586     // it. Beware: other processors probably don't!
2587     Domain = ARM_MB::ISHST;
2588   }
2589
2590   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2591                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2592                      DAG.getConstant(Domain, MVT::i32));
2593 }
2594
2595 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2596                              const ARMSubtarget *Subtarget) {
2597   // ARM pre v5TE and Thumb1 does not have preload instructions.
2598   if (!(Subtarget->isThumb2() ||
2599         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2600     // Just preserve the chain.
2601     return Op.getOperand(0);
2602
2603   SDLoc dl(Op);
2604   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2605   if (!isRead &&
2606       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2607     // ARMv7 with MP extension has PLDW.
2608     return Op.getOperand(0);
2609
2610   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2611   if (Subtarget->isThumb()) {
2612     // Invert the bits.
2613     isRead = ~isRead & 1;
2614     isData = ~isData & 1;
2615   }
2616
2617   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2618                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2619                      DAG.getConstant(isData, MVT::i32));
2620 }
2621
2622 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2623   MachineFunction &MF = DAG.getMachineFunction();
2624   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2625
2626   // vastart just stores the address of the VarArgsFrameIndex slot into the
2627   // memory location argument.
2628   SDLoc dl(Op);
2629   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2630   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2631   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2632   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2633                       MachinePointerInfo(SV), false, false, 0);
2634 }
2635
2636 SDValue
2637 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2638                                         SDValue &Root, SelectionDAG &DAG,
2639                                         SDLoc dl) const {
2640   MachineFunction &MF = DAG.getMachineFunction();
2641   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2642
2643   const TargetRegisterClass *RC;
2644   if (AFI->isThumb1OnlyFunction())
2645     RC = &ARM::tGPRRegClass;
2646   else
2647     RC = &ARM::GPRRegClass;
2648
2649   // Transform the arguments stored in physical registers into virtual ones.
2650   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2651   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2652
2653   SDValue ArgValue2;
2654   if (NextVA.isMemLoc()) {
2655     MachineFrameInfo *MFI = MF.getFrameInfo();
2656     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2657
2658     // Create load node to retrieve arguments from the stack.
2659     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2660     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2661                             MachinePointerInfo::getFixedStack(FI),
2662                             false, false, false, 0);
2663   } else {
2664     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2665     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2666   }
2667
2668   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2669 }
2670
2671 void
2672 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2673                                   unsigned InRegsParamRecordIdx,
2674                                   unsigned ArgSize,
2675                                   unsigned &ArgRegsSize,
2676                                   unsigned &ArgRegsSaveSize)
2677   const {
2678   unsigned NumGPRs;
2679   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2680     unsigned RBegin, REnd;
2681     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2682     NumGPRs = REnd - RBegin;
2683   } else {
2684     unsigned int firstUnalloced;
2685     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2686                                                 sizeof(GPRArgRegs) /
2687                                                 sizeof(GPRArgRegs[0]));
2688     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2689   }
2690
2691   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2692   ArgRegsSize = NumGPRs * 4;
2693
2694   // If parameter is split between stack and GPRs...
2695   if (NumGPRs && Align > 4 &&
2696       (ArgRegsSize < ArgSize ||
2697         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2698     // Add padding for part of param recovered from GPRs.  For example,
2699     // if Align == 8, its last byte must be at address K*8 - 1.
2700     // We need to do it, since remained (stack) part of parameter has
2701     // stack alignment, and we need to "attach" "GPRs head" without gaps
2702     // to it:
2703     // Stack:
2704     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2705     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2706     //
2707     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2708     unsigned Padding =
2709         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2710     ArgRegsSaveSize = ArgRegsSize + Padding;
2711   } else
2712     // We don't need to extend regs save size for byval parameters if they
2713     // are passed via GPRs only.
2714     ArgRegsSaveSize = ArgRegsSize;
2715 }
2716
2717 // The remaining GPRs hold either the beginning of variable-argument
2718 // data, or the beginning of an aggregate passed by value (usually
2719 // byval).  Either way, we allocate stack slots adjacent to the data
2720 // provided by our caller, and store the unallocated registers there.
2721 // If this is a variadic function, the va_list pointer will begin with
2722 // these values; otherwise, this reassembles a (byval) structure that
2723 // was split between registers and memory.
2724 // Return: The frame index registers were stored into.
2725 int
2726 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2727                                   SDLoc dl, SDValue &Chain,
2728                                   const Value *OrigArg,
2729                                   unsigned InRegsParamRecordIdx,
2730                                   unsigned OffsetFromOrigArg,
2731                                   unsigned ArgOffset,
2732                                   unsigned ArgSize,
2733                                   bool ForceMutable,
2734                                   unsigned ByValStoreOffset,
2735                                   unsigned TotalArgRegsSaveSize) const {
2736
2737   // Currently, two use-cases possible:
2738   // Case #1. Non-var-args function, and we meet first byval parameter.
2739   //          Setup first unallocated register as first byval register;
2740   //          eat all remained registers
2741   //          (these two actions are performed by HandleByVal method).
2742   //          Then, here, we initialize stack frame with
2743   //          "store-reg" instructions.
2744   // Case #2. Var-args function, that doesn't contain byval parameters.
2745   //          The same: eat all remained unallocated registers,
2746   //          initialize stack frame.
2747
2748   MachineFunction &MF = DAG.getMachineFunction();
2749   MachineFrameInfo *MFI = MF.getFrameInfo();
2750   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2751   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2752   unsigned RBegin, REnd;
2753   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2754     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2755     firstRegToSaveIndex = RBegin - ARM::R0;
2756     lastRegToSaveIndex = REnd - ARM::R0;
2757   } else {
2758     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2759       (GPRArgRegs, array_lengthof(GPRArgRegs));
2760     lastRegToSaveIndex = 4;
2761   }
2762
2763   unsigned ArgRegsSize, ArgRegsSaveSize;
2764   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2765                  ArgRegsSize, ArgRegsSaveSize);
2766
2767   // Store any by-val regs to their spots on the stack so that they may be
2768   // loaded by deferencing the result of formal parameter pointer or va_next.
2769   // Note: once stack area for byval/varargs registers
2770   // was initialized, it can't be initialized again.
2771   if (ArgRegsSaveSize) {
2772     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2773
2774     if (Padding) {
2775       assert(AFI->getStoredByValParamsPadding() == 0 &&
2776              "The only parameter may be padded.");
2777       AFI->setStoredByValParamsPadding(Padding);
2778     }
2779
2780     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2781                                             Padding +
2782                                               ByValStoreOffset -
2783                                               (int64_t)TotalArgRegsSaveSize,
2784                                             false);
2785     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2786     if (Padding) {
2787        MFI->CreateFixedObject(Padding,
2788                               ArgOffset + ByValStoreOffset -
2789                                 (int64_t)ArgRegsSaveSize,
2790                               false);
2791     }
2792
2793     SmallVector<SDValue, 4> MemOps;
2794     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2795          ++firstRegToSaveIndex, ++i) {
2796       const TargetRegisterClass *RC;
2797       if (AFI->isThumb1OnlyFunction())
2798         RC = &ARM::tGPRRegClass;
2799       else
2800         RC = &ARM::GPRRegClass;
2801
2802       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2803       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2804       SDValue Store =
2805         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2806                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2807                      false, false, 0);
2808       MemOps.push_back(Store);
2809       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2810                         DAG.getConstant(4, getPointerTy()));
2811     }
2812
2813     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2814
2815     if (!MemOps.empty())
2816       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2817                           &MemOps[0], MemOps.size());
2818     return FrameIndex;
2819   } else {
2820     if (ArgSize == 0) {
2821       // We cannot allocate a zero-byte object for the first variadic argument,
2822       // so just make up a size.
2823       ArgSize = 4;
2824     }
2825     // This will point to the next argument passed via stack.
2826     return MFI->CreateFixedObject(
2827       ArgSize, ArgOffset, !ForceMutable);
2828   }
2829 }
2830
2831 // Setup stack frame, the va_list pointer will start from.
2832 void
2833 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2834                                         SDLoc dl, SDValue &Chain,
2835                                         unsigned ArgOffset,
2836                                         unsigned TotalArgRegsSaveSize,
2837                                         bool ForceMutable) const {
2838   MachineFunction &MF = DAG.getMachineFunction();
2839   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2840
2841   // Try to store any remaining integer argument regs
2842   // to their spots on the stack so that they may be loaded by deferencing
2843   // the result of va_next.
2844   // If there is no regs to be stored, just point address after last
2845   // argument passed via stack.
2846   int FrameIndex =
2847     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2848                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2849                    0, TotalArgRegsSaveSize);
2850
2851   AFI->setVarArgsFrameIndex(FrameIndex);
2852 }
2853
2854 SDValue
2855 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2856                                         CallingConv::ID CallConv, bool isVarArg,
2857                                         const SmallVectorImpl<ISD::InputArg>
2858                                           &Ins,
2859                                         SDLoc dl, SelectionDAG &DAG,
2860                                         SmallVectorImpl<SDValue> &InVals)
2861                                           const {
2862   MachineFunction &MF = DAG.getMachineFunction();
2863   MachineFrameInfo *MFI = MF.getFrameInfo();
2864
2865   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2866
2867   // Assign locations to all of the incoming arguments.
2868   SmallVector<CCValAssign, 16> ArgLocs;
2869   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2870                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2871   CCInfo.AnalyzeFormalArguments(Ins,
2872                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2873                                                   isVarArg));
2874
2875   SmallVector<SDValue, 16> ArgValues;
2876   int lastInsIndex = -1;
2877   SDValue ArgValue;
2878   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2879   unsigned CurArgIdx = 0;
2880
2881   // Initially ArgRegsSaveSize is zero.
2882   // Then we increase this value each time we meet byval parameter.
2883   // We also increase this value in case of varargs function.
2884   AFI->setArgRegsSaveSize(0);
2885
2886   unsigned ByValStoreOffset = 0;
2887   unsigned TotalArgRegsSaveSize = 0;
2888   unsigned ArgRegsSaveSizeMaxAlign = 4;
2889
2890   // Calculate the amount of stack space that we need to allocate to store
2891   // byval and variadic arguments that are passed in registers.
2892   // We need to know this before we allocate the first byval or variadic
2893   // argument, as they will be allocated a stack slot below the CFA (Canonical
2894   // Frame Address, the stack pointer at entry to the function).
2895   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2896     CCValAssign &VA = ArgLocs[i];
2897     if (VA.isMemLoc()) {
2898       int index = VA.getValNo();
2899       if (index != lastInsIndex) {
2900         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2901         if (Flags.isByVal()) {
2902           unsigned ExtraArgRegsSize;
2903           unsigned ExtraArgRegsSaveSize;
2904           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2905                          Flags.getByValSize(),
2906                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2907
2908           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2909           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2910               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2911           CCInfo.nextInRegsParam();
2912         }
2913         lastInsIndex = index;
2914       }
2915     }
2916   }
2917   CCInfo.rewindByValRegsInfo();
2918   lastInsIndex = -1;
2919   if (isVarArg) {
2920     unsigned ExtraArgRegsSize;
2921     unsigned ExtraArgRegsSaveSize;
2922     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2923                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2924     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2925   }
2926   // If the arg regs save area contains N-byte aligned values, the
2927   // bottom of it must be at least N-byte aligned.
2928   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2929   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2930
2931   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2932     CCValAssign &VA = ArgLocs[i];
2933     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2934     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2935     // Arguments stored in registers.
2936     if (VA.isRegLoc()) {
2937       EVT RegVT = VA.getLocVT();
2938
2939       if (VA.needsCustom()) {
2940         // f64 and vector types are split up into multiple registers or
2941         // combinations of registers and stack slots.
2942         if (VA.getLocVT() == MVT::v2f64) {
2943           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2944                                                    Chain, DAG, dl);
2945           VA = ArgLocs[++i]; // skip ahead to next loc
2946           SDValue ArgValue2;
2947           if (VA.isMemLoc()) {
2948             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2949             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2950             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2951                                     MachinePointerInfo::getFixedStack(FI),
2952                                     false, false, false, 0);
2953           } else {
2954             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2955                                              Chain, DAG, dl);
2956           }
2957           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2958           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2959                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2960           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2961                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2962         } else
2963           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2964
2965       } else {
2966         const TargetRegisterClass *RC;
2967
2968         if (RegVT == MVT::f32)
2969           RC = &ARM::SPRRegClass;
2970         else if (RegVT == MVT::f64)
2971           RC = &ARM::DPRRegClass;
2972         else if (RegVT == MVT::v2f64)
2973           RC = &ARM::QPRRegClass;
2974         else if (RegVT == MVT::i32)
2975           RC = AFI->isThumb1OnlyFunction() ?
2976             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2977             (const TargetRegisterClass*)&ARM::GPRRegClass;
2978         else
2979           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2980
2981         // Transform the arguments in physical registers into virtual ones.
2982         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2983         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2984       }
2985
2986       // If this is an 8 or 16-bit value, it is really passed promoted
2987       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2988       // truncate to the right size.
2989       switch (VA.getLocInfo()) {
2990       default: llvm_unreachable("Unknown loc info!");
2991       case CCValAssign::Full: break;
2992       case CCValAssign::BCvt:
2993         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2994         break;
2995       case CCValAssign::SExt:
2996         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2997                                DAG.getValueType(VA.getValVT()));
2998         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2999         break;
3000       case CCValAssign::ZExt:
3001         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3002                                DAG.getValueType(VA.getValVT()));
3003         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3004         break;
3005       }
3006
3007       InVals.push_back(ArgValue);
3008
3009     } else { // VA.isRegLoc()
3010
3011       // sanity check
3012       assert(VA.isMemLoc());
3013       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3014
3015       int index = ArgLocs[i].getValNo();
3016
3017       // Some Ins[] entries become multiple ArgLoc[] entries.
3018       // Process them only once.
3019       if (index != lastInsIndex)
3020         {
3021           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3022           // FIXME: For now, all byval parameter objects are marked mutable.
3023           // This can be changed with more analysis.
3024           // In case of tail call optimization mark all arguments mutable.
3025           // Since they could be overwritten by lowering of arguments in case of
3026           // a tail call.
3027           if (Flags.isByVal()) {
3028             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3029
3030             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3031             int FrameIndex = StoreByValRegs(
3032                 CCInfo, DAG, dl, Chain, CurOrigArg,
3033                 CurByValIndex,
3034                 Ins[VA.getValNo()].PartOffset,
3035                 VA.getLocMemOffset(),
3036                 Flags.getByValSize(),
3037                 true /*force mutable frames*/,
3038                 ByValStoreOffset,
3039                 TotalArgRegsSaveSize);
3040             ByValStoreOffset += Flags.getByValSize();
3041             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3042             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3043             CCInfo.nextInRegsParam();
3044           } else {
3045             unsigned FIOffset = VA.getLocMemOffset();
3046             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3047                                             FIOffset, true);
3048
3049             // Create load nodes to retrieve arguments from the stack.
3050             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3051             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3052                                          MachinePointerInfo::getFixedStack(FI),
3053                                          false, false, false, 0));
3054           }
3055           lastInsIndex = index;
3056         }
3057     }
3058   }
3059
3060   // varargs
3061   if (isVarArg)
3062     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3063                          CCInfo.getNextStackOffset(),
3064                          TotalArgRegsSaveSize);
3065
3066   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3067
3068   return Chain;
3069 }
3070
3071 /// isFloatingPointZero - Return true if this is +0.0.
3072 static bool isFloatingPointZero(SDValue Op) {
3073   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3074     return CFP->getValueAPF().isPosZero();
3075   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3076     // Maybe this has already been legalized into the constant pool?
3077     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3078       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3079       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3080         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3081           return CFP->getValueAPF().isPosZero();
3082     }
3083   }
3084   return false;
3085 }
3086
3087 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3088 /// the given operands.
3089 SDValue
3090 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3091                              SDValue &ARMcc, SelectionDAG &DAG,
3092                              SDLoc dl) const {
3093   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3094     unsigned C = RHSC->getZExtValue();
3095     if (!isLegalICmpImmediate(C)) {
3096       // Constant does not fit, try adjusting it by one?
3097       switch (CC) {
3098       default: break;
3099       case ISD::SETLT:
3100       case ISD::SETGE:
3101         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3102           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3103           RHS = DAG.getConstant(C-1, MVT::i32);
3104         }
3105         break;
3106       case ISD::SETULT:
3107       case ISD::SETUGE:
3108         if (C != 0 && isLegalICmpImmediate(C-1)) {
3109           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3110           RHS = DAG.getConstant(C-1, MVT::i32);
3111         }
3112         break;
3113       case ISD::SETLE:
3114       case ISD::SETGT:
3115         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3116           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3117           RHS = DAG.getConstant(C+1, MVT::i32);
3118         }
3119         break;
3120       case ISD::SETULE:
3121       case ISD::SETUGT:
3122         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3123           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3124           RHS = DAG.getConstant(C+1, MVT::i32);
3125         }
3126         break;
3127       }
3128     }
3129   }
3130
3131   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3132   ARMISD::NodeType CompareType;
3133   switch (CondCode) {
3134   default:
3135     CompareType = ARMISD::CMP;
3136     break;
3137   case ARMCC::EQ:
3138   case ARMCC::NE:
3139     // Uses only Z Flag
3140     CompareType = ARMISD::CMPZ;
3141     break;
3142   }
3143   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3144   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3145 }
3146
3147 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3148 SDValue
3149 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3150                              SDLoc dl) const {
3151   SDValue Cmp;
3152   if (!isFloatingPointZero(RHS))
3153     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3154   else
3155     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3156   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3157 }
3158
3159 /// duplicateCmp - Glue values can have only one use, so this function
3160 /// duplicates a comparison node.
3161 SDValue
3162 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3163   unsigned Opc = Cmp.getOpcode();
3164   SDLoc DL(Cmp);
3165   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3166     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3167
3168   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3169   Cmp = Cmp.getOperand(0);
3170   Opc = Cmp.getOpcode();
3171   if (Opc == ARMISD::CMPFP)
3172     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3173   else {
3174     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3175     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3176   }
3177   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3178 }
3179
3180 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3181   SDValue Cond = Op.getOperand(0);
3182   SDValue SelectTrue = Op.getOperand(1);
3183   SDValue SelectFalse = Op.getOperand(2);
3184   SDLoc dl(Op);
3185
3186   // Convert:
3187   //
3188   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3189   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3190   //
3191   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3192     const ConstantSDNode *CMOVTrue =
3193       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3194     const ConstantSDNode *CMOVFalse =
3195       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3196
3197     if (CMOVTrue && CMOVFalse) {
3198       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3199       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3200
3201       SDValue True;
3202       SDValue False;
3203       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3204         True = SelectTrue;
3205         False = SelectFalse;
3206       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3207         True = SelectFalse;
3208         False = SelectTrue;
3209       }
3210
3211       if (True.getNode() && False.getNode()) {
3212         EVT VT = Op.getValueType();
3213         SDValue ARMcc = Cond.getOperand(2);
3214         SDValue CCR = Cond.getOperand(3);
3215         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3216         assert(True.getValueType() == VT);
3217         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3218       }
3219     }
3220   }
3221
3222   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3223   // undefined bits before doing a full-word comparison with zero.
3224   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3225                      DAG.getConstant(1, Cond.getValueType()));
3226
3227   return DAG.getSelectCC(dl, Cond,
3228                          DAG.getConstant(0, Cond.getValueType()),
3229                          SelectTrue, SelectFalse, ISD::SETNE);
3230 }
3231
3232 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3233   if (CC == ISD::SETNE)
3234     return ISD::SETEQ;
3235   return ISD::getSetCCInverse(CC, true);
3236 }
3237
3238 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3239                                  bool &swpCmpOps, bool &swpVselOps) {
3240   // Start by selecting the GE condition code for opcodes that return true for
3241   // 'equality'
3242   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3243       CC == ISD::SETULE)
3244     CondCode = ARMCC::GE;
3245
3246   // and GT for opcodes that return false for 'equality'.
3247   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3248            CC == ISD::SETULT)
3249     CondCode = ARMCC::GT;
3250
3251   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3252   // to swap the compare operands.
3253   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3254       CC == ISD::SETULT)
3255     swpCmpOps = true;
3256
3257   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3258   // If we have an unordered opcode, we need to swap the operands to the VSEL
3259   // instruction (effectively negating the condition).
3260   //
3261   // This also has the effect of swapping which one of 'less' or 'greater'
3262   // returns true, so we also swap the compare operands. It also switches
3263   // whether we return true for 'equality', so we compensate by picking the
3264   // opposite condition code to our original choice.
3265   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3266       CC == ISD::SETUGT) {
3267     swpCmpOps = !swpCmpOps;
3268     swpVselOps = !swpVselOps;
3269     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3270   }
3271
3272   // 'ordered' is 'anything but unordered', so use the VS condition code and
3273   // swap the VSEL operands.
3274   if (CC == ISD::SETO) {
3275     CondCode = ARMCC::VS;
3276     swpVselOps = true;
3277   }
3278
3279   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3280   // code and swap the VSEL operands.
3281   if (CC == ISD::SETUNE) {
3282     CondCode = ARMCC::EQ;
3283     swpVselOps = true;
3284   }
3285 }
3286
3287 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3288   EVT VT = Op.getValueType();
3289   SDValue LHS = Op.getOperand(0);
3290   SDValue RHS = Op.getOperand(1);
3291   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3292   SDValue TrueVal = Op.getOperand(2);
3293   SDValue FalseVal = Op.getOperand(3);
3294   SDLoc dl(Op);
3295
3296   if (LHS.getValueType() == MVT::i32) {
3297     // Try to generate VSEL on ARMv8.
3298     // The VSEL instruction can't use all the usual ARM condition
3299     // codes: it only has two bits to select the condition code, so it's
3300     // constrained to use only GE, GT, VS and EQ.
3301     //
3302     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3303     // swap the operands of the previous compare instruction (effectively
3304     // inverting the compare condition, swapping 'less' and 'greater') and
3305     // sometimes need to swap the operands to the VSEL (which inverts the
3306     // condition in the sense of firing whenever the previous condition didn't)
3307     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3308                                       TrueVal.getValueType() == MVT::f64)) {
3309       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3310       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3311           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3312         CC = getInverseCCForVSEL(CC);
3313         std::swap(TrueVal, FalseVal);
3314       }
3315     }
3316
3317     SDValue ARMcc;
3318     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3319     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3320     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3321                        Cmp);
3322   }
3323
3324   ARMCC::CondCodes CondCode, CondCode2;
3325   FPCCToARMCC(CC, CondCode, CondCode2);
3326
3327   // Try to generate VSEL on ARMv8.
3328   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3329                                     TrueVal.getValueType() == MVT::f64)) {
3330     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3331     // same operands, as follows:
3332     //   c = fcmp [ogt, olt, ugt, ult] a, b
3333     //   select c, a, b
3334     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3335     // handled differently than the original code sequence.
3336     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3337         RHS == FalseVal) {
3338       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3339         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3340       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3341         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3342     }
3343
3344     bool swpCmpOps = false;
3345     bool swpVselOps = false;
3346     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3347
3348     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3349         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3350       if (swpCmpOps)
3351         std::swap(LHS, RHS);
3352       if (swpVselOps)
3353         std::swap(TrueVal, FalseVal);
3354     }
3355   }
3356
3357   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3358   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3359   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3360   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3361                                ARMcc, CCR, Cmp);
3362   if (CondCode2 != ARMCC::AL) {
3363     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3364     // FIXME: Needs another CMP because flag can have but one use.
3365     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3366     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3367                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3368   }
3369   return Result;
3370 }
3371
3372 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3373 /// to morph to an integer compare sequence.
3374 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3375                            const ARMSubtarget *Subtarget) {
3376   SDNode *N = Op.getNode();
3377   if (!N->hasOneUse())
3378     // Otherwise it requires moving the value from fp to integer registers.
3379     return false;
3380   if (!N->getNumValues())
3381     return false;
3382   EVT VT = Op.getValueType();
3383   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3384     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3385     // vmrs are very slow, e.g. cortex-a8.
3386     return false;
3387
3388   if (isFloatingPointZero(Op)) {
3389     SeenZero = true;
3390     return true;
3391   }
3392   return ISD::isNormalLoad(N);
3393 }
3394
3395 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3396   if (isFloatingPointZero(Op))
3397     return DAG.getConstant(0, MVT::i32);
3398
3399   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3400     return DAG.getLoad(MVT::i32, SDLoc(Op),
3401                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3402                        Ld->isVolatile(), Ld->isNonTemporal(),
3403                        Ld->isInvariant(), Ld->getAlignment());
3404
3405   llvm_unreachable("Unknown VFP cmp argument!");
3406 }
3407
3408 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3409                            SDValue &RetVal1, SDValue &RetVal2) {
3410   if (isFloatingPointZero(Op)) {
3411     RetVal1 = DAG.getConstant(0, MVT::i32);
3412     RetVal2 = DAG.getConstant(0, MVT::i32);
3413     return;
3414   }
3415
3416   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3417     SDValue Ptr = Ld->getBasePtr();
3418     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3419                           Ld->getChain(), Ptr,
3420                           Ld->getPointerInfo(),
3421                           Ld->isVolatile(), Ld->isNonTemporal(),
3422                           Ld->isInvariant(), Ld->getAlignment());
3423
3424     EVT PtrType = Ptr.getValueType();
3425     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3426     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3427                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3428     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3429                           Ld->getChain(), NewPtr,
3430                           Ld->getPointerInfo().getWithOffset(4),
3431                           Ld->isVolatile(), Ld->isNonTemporal(),
3432                           Ld->isInvariant(), NewAlign);
3433     return;
3434   }
3435
3436   llvm_unreachable("Unknown VFP cmp argument!");
3437 }
3438
3439 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3440 /// f32 and even f64 comparisons to integer ones.
3441 SDValue
3442 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3443   SDValue Chain = Op.getOperand(0);
3444   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3445   SDValue LHS = Op.getOperand(2);
3446   SDValue RHS = Op.getOperand(3);
3447   SDValue Dest = Op.getOperand(4);
3448   SDLoc dl(Op);
3449
3450   bool LHSSeenZero = false;
3451   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3452   bool RHSSeenZero = false;
3453   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3454   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3455     // If unsafe fp math optimization is enabled and there are no other uses of
3456     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3457     // to an integer comparison.
3458     if (CC == ISD::SETOEQ)
3459       CC = ISD::SETEQ;
3460     else if (CC == ISD::SETUNE)
3461       CC = ISD::SETNE;
3462
3463     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3464     SDValue ARMcc;
3465     if (LHS.getValueType() == MVT::f32) {
3466       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3467                         bitcastf32Toi32(LHS, DAG), Mask);
3468       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3469                         bitcastf32Toi32(RHS, DAG), Mask);
3470       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3471       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3472       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3473                          Chain, Dest, ARMcc, CCR, Cmp);
3474     }
3475
3476     SDValue LHS1, LHS2;
3477     SDValue RHS1, RHS2;
3478     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3479     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3480     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3481     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3482     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3483     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3484     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3485     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3486     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3487   }
3488
3489   return SDValue();
3490 }
3491
3492 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3493   SDValue Chain = Op.getOperand(0);
3494   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3495   SDValue LHS = Op.getOperand(2);
3496   SDValue RHS = Op.getOperand(3);
3497   SDValue Dest = Op.getOperand(4);
3498   SDLoc dl(Op);
3499
3500   if (LHS.getValueType() == MVT::i32) {
3501     SDValue ARMcc;
3502     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3503     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3504     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3505                        Chain, Dest, ARMcc, CCR, Cmp);
3506   }
3507
3508   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3509
3510   if (getTargetMachine().Options.UnsafeFPMath &&
3511       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3512        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3513     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3514     if (Result.getNode())
3515       return Result;
3516   }
3517
3518   ARMCC::CondCodes CondCode, CondCode2;
3519   FPCCToARMCC(CC, CondCode, CondCode2);
3520
3521   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3522   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3523   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3524   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3525   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3526   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3527   if (CondCode2 != ARMCC::AL) {
3528     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3529     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3530     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3531   }
3532   return Res;
3533 }
3534
3535 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3536   SDValue Chain = Op.getOperand(0);
3537   SDValue Table = Op.getOperand(1);
3538   SDValue Index = Op.getOperand(2);
3539   SDLoc dl(Op);
3540
3541   EVT PTy = getPointerTy();
3542   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3543   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3544   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3545   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3546   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3547   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3548   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3549   if (Subtarget->isThumb2()) {
3550     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3551     // which does another jump to the destination. This also makes it easier
3552     // to translate it to TBB / TBH later.
3553     // FIXME: This might not work if the function is extremely large.
3554     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3555                        Addr, Op.getOperand(2), JTI, UId);
3556   }
3557   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3558     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3559                        MachinePointerInfo::getJumpTable(),
3560                        false, false, false, 0);
3561     Chain = Addr.getValue(1);
3562     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3563     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3564   } else {
3565     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3566                        MachinePointerInfo::getJumpTable(),
3567                        false, false, false, 0);
3568     Chain = Addr.getValue(1);
3569     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3570   }
3571 }
3572
3573 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3574   EVT VT = Op.getValueType();
3575   SDLoc dl(Op);
3576
3577   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3578     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3579       return Op;
3580     return DAG.UnrollVectorOp(Op.getNode());
3581   }
3582
3583   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3584          "Invalid type for custom lowering!");
3585   if (VT != MVT::v4i16)
3586     return DAG.UnrollVectorOp(Op.getNode());
3587
3588   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3589   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3590 }
3591
3592 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3593   EVT VT = Op.getValueType();
3594   if (VT.isVector())
3595     return LowerVectorFP_TO_INT(Op, DAG);
3596
3597   SDLoc dl(Op);
3598   unsigned Opc;
3599
3600   switch (Op.getOpcode()) {
3601   default: llvm_unreachable("Invalid opcode!");
3602   case ISD::FP_TO_SINT:
3603     Opc = ARMISD::FTOSI;
3604     break;
3605   case ISD::FP_TO_UINT:
3606     Opc = ARMISD::FTOUI;
3607     break;
3608   }
3609   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3610   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3611 }
3612
3613 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3614   EVT VT = Op.getValueType();
3615   SDLoc dl(Op);
3616
3617   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3618     if (VT.getVectorElementType() == MVT::f32)
3619       return Op;
3620     return DAG.UnrollVectorOp(Op.getNode());
3621   }
3622
3623   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3624          "Invalid type for custom lowering!");
3625   if (VT != MVT::v4f32)
3626     return DAG.UnrollVectorOp(Op.getNode());
3627
3628   unsigned CastOpc;
3629   unsigned Opc;
3630   switch (Op.getOpcode()) {
3631   default: llvm_unreachable("Invalid opcode!");
3632   case ISD::SINT_TO_FP:
3633     CastOpc = ISD::SIGN_EXTEND;
3634     Opc = ISD::SINT_TO_FP;
3635     break;
3636   case ISD::UINT_TO_FP:
3637     CastOpc = ISD::ZERO_EXTEND;
3638     Opc = ISD::UINT_TO_FP;
3639     break;
3640   }
3641
3642   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3643   return DAG.getNode(Opc, dl, VT, Op);
3644 }
3645
3646 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3647   EVT VT = Op.getValueType();
3648   if (VT.isVector())
3649     return LowerVectorINT_TO_FP(Op, DAG);
3650
3651   SDLoc dl(Op);
3652   unsigned Opc;
3653
3654   switch (Op.getOpcode()) {
3655   default: llvm_unreachable("Invalid opcode!");
3656   case ISD::SINT_TO_FP:
3657     Opc = ARMISD::SITOF;
3658     break;
3659   case ISD::UINT_TO_FP:
3660     Opc = ARMISD::UITOF;
3661     break;
3662   }
3663
3664   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3665   return DAG.getNode(Opc, dl, VT, Op);
3666 }
3667
3668 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3669   // Implement fcopysign with a fabs and a conditional fneg.
3670   SDValue Tmp0 = Op.getOperand(0);
3671   SDValue Tmp1 = Op.getOperand(1);
3672   SDLoc dl(Op);
3673   EVT VT = Op.getValueType();
3674   EVT SrcVT = Tmp1.getValueType();
3675   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3676     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3677   bool UseNEON = !InGPR && Subtarget->hasNEON();
3678
3679   if (UseNEON) {
3680     // Use VBSL to copy the sign bit.
3681     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3682     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3683                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3684     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3685     if (VT == MVT::f64)
3686       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3687                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3688                          DAG.getConstant(32, MVT::i32));
3689     else /*if (VT == MVT::f32)*/
3690       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3691     if (SrcVT == MVT::f32) {
3692       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3693       if (VT == MVT::f64)
3694         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3695                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3696                            DAG.getConstant(32, MVT::i32));
3697     } else if (VT == MVT::f32)
3698       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3699                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3700                          DAG.getConstant(32, MVT::i32));
3701     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3702     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3703
3704     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3705                                             MVT::i32);
3706     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3707     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3708                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3709
3710     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3711                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3712                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3713     if (VT == MVT::f32) {
3714       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3715       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3716                         DAG.getConstant(0, MVT::i32));
3717     } else {
3718       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3719     }
3720
3721     return Res;
3722   }
3723
3724   // Bitcast operand 1 to i32.
3725   if (SrcVT == MVT::f64)
3726     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3727                        &Tmp1, 1).getValue(1);
3728   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3729
3730   // Or in the signbit with integer operations.
3731   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3732   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3733   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3734   if (VT == MVT::f32) {
3735     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3736                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3737     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3738                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3739   }
3740
3741   // f64: Or the high part with signbit and then combine two parts.
3742   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3743                      &Tmp0, 1);
3744   SDValue Lo = Tmp0.getValue(0);
3745   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3746   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3747   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3748 }
3749
3750 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3751   MachineFunction &MF = DAG.getMachineFunction();
3752   MachineFrameInfo *MFI = MF.getFrameInfo();
3753   MFI->setReturnAddressIsTaken(true);
3754
3755   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3756     return SDValue();
3757
3758   EVT VT = Op.getValueType();
3759   SDLoc dl(Op);
3760   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3761   if (Depth) {
3762     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3763     SDValue Offset = DAG.getConstant(4, MVT::i32);
3764     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3765                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3766                        MachinePointerInfo(), false, false, false, 0);
3767   }
3768
3769   // Return LR, which contains the return address. Mark it an implicit live-in.
3770   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3771   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3772 }
3773
3774 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3775   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3776   MFI->setFrameAddressIsTaken(true);
3777
3778   EVT VT = Op.getValueType();
3779   SDLoc dl(Op);  // FIXME probably not meaningful
3780   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3781   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3782     ? ARM::R7 : ARM::R11;
3783   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3784   while (Depth--)
3785     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3786                             MachinePointerInfo(),
3787                             false, false, false, 0);
3788   return FrameAddr;
3789 }
3790
3791 /// ExpandBITCAST - If the target supports VFP, this function is called to
3792 /// expand a bit convert where either the source or destination type is i64 to
3793 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3794 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3795 /// vectors), since the legalizer won't know what to do with that.
3796 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3797   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3798   SDLoc dl(N);
3799   SDValue Op = N->getOperand(0);
3800
3801   // This function is only supposed to be called for i64 types, either as the
3802   // source or destination of the bit convert.
3803   EVT SrcVT = Op.getValueType();
3804   EVT DstVT = N->getValueType(0);
3805   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3806          "ExpandBITCAST called for non-i64 type");
3807
3808   // Turn i64->f64 into VMOVDRR.
3809   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3810     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3811                              DAG.getConstant(0, MVT::i32));
3812     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3813                              DAG.getConstant(1, MVT::i32));
3814     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3815                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3816   }
3817
3818   // Turn f64->i64 into VMOVRRD.
3819   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3820     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3821                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3822     // Merge the pieces into a single i64 value.
3823     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3824   }
3825
3826   return SDValue();
3827 }
3828
3829 /// getZeroVector - Returns a vector of specified type with all zero elements.
3830 /// Zero vectors are used to represent vector negation and in those cases
3831 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3832 /// not support i64 elements, so sometimes the zero vectors will need to be
3833 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3834 /// zero vector.
3835 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3836   assert(VT.isVector() && "Expected a vector type");
3837   // The canonical modified immediate encoding of a zero vector is....0!
3838   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3839   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3840   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3841   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3842 }
3843
3844 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3845 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3846 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3847                                                 SelectionDAG &DAG) const {
3848   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3849   EVT VT = Op.getValueType();
3850   unsigned VTBits = VT.getSizeInBits();
3851   SDLoc dl(Op);
3852   SDValue ShOpLo = Op.getOperand(0);
3853   SDValue ShOpHi = Op.getOperand(1);
3854   SDValue ShAmt  = Op.getOperand(2);
3855   SDValue ARMcc;
3856   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3857
3858   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3859
3860   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3861                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3862   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3863   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3864                                    DAG.getConstant(VTBits, MVT::i32));
3865   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3866   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3867   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3868
3869   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3870   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3871                           ARMcc, DAG, dl);
3872   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3873   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3874                            CCR, Cmp);
3875
3876   SDValue Ops[2] = { Lo, Hi };
3877   return DAG.getMergeValues(Ops, 2, dl);
3878 }
3879
3880 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3881 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3882 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3883                                                SelectionDAG &DAG) const {
3884   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3885   EVT VT = Op.getValueType();
3886   unsigned VTBits = VT.getSizeInBits();
3887   SDLoc dl(Op);
3888   SDValue ShOpLo = Op.getOperand(0);
3889   SDValue ShOpHi = Op.getOperand(1);
3890   SDValue ShAmt  = Op.getOperand(2);
3891   SDValue ARMcc;
3892
3893   assert(Op.getOpcode() == ISD::SHL_PARTS);
3894   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3895                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3896   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3897   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3898                                    DAG.getConstant(VTBits, MVT::i32));
3899   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3900   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3901
3902   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3903   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3904   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3905                           ARMcc, DAG, dl);
3906   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3907   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3908                            CCR, Cmp);
3909
3910   SDValue Ops[2] = { Lo, Hi };
3911   return DAG.getMergeValues(Ops, 2, dl);
3912 }
3913
3914 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3915                                             SelectionDAG &DAG) const {
3916   // The rounding mode is in bits 23:22 of the FPSCR.
3917   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3918   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3919   // so that the shift + and get folded into a bitfield extract.
3920   SDLoc dl(Op);
3921   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3922                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3923                                               MVT::i32));
3924   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3925                                   DAG.getConstant(1U << 22, MVT::i32));
3926   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3927                               DAG.getConstant(22, MVT::i32));
3928   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3929                      DAG.getConstant(3, MVT::i32));
3930 }
3931
3932 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3933                          const ARMSubtarget *ST) {
3934   EVT VT = N->getValueType(0);
3935   SDLoc dl(N);
3936
3937   if (!ST->hasV6T2Ops())
3938     return SDValue();
3939
3940   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3941   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3942 }
3943
3944 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3945 /// for each 16-bit element from operand, repeated.  The basic idea is to
3946 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3947 ///
3948 /// Trace for v4i16:
3949 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3950 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3951 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3952 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3953 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3954 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3955 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3956 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3957 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3958   EVT VT = N->getValueType(0);
3959   SDLoc DL(N);
3960
3961   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3962   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3963   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3964   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3965   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3966   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3967 }
3968
3969 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3970 /// bit-count for each 16-bit element from the operand.  We need slightly
3971 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3972 /// 64/128-bit registers.
3973 ///
3974 /// Trace for v4i16:
3975 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3976 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3977 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3978 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3979 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3980   EVT VT = N->getValueType(0);
3981   SDLoc DL(N);
3982
3983   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3984   if (VT.is64BitVector()) {
3985     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3986     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3987                        DAG.getIntPtrConstant(0));
3988   } else {
3989     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3990                                     BitCounts, DAG.getIntPtrConstant(0));
3991     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3992   }
3993 }
3994
3995 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3996 /// bit-count for each 32-bit element from the operand.  The idea here is
3997 /// to split the vector into 16-bit elements, leverage the 16-bit count
3998 /// routine, and then combine the results.
3999 ///
4000 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4001 /// input    = [v0    v1    ] (vi: 32-bit elements)
4002 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4003 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4004 /// vrev: N0 = [k1 k0 k3 k2 ]
4005 ///            [k0 k1 k2 k3 ]
4006 ///       N1 =+[k1 k0 k3 k2 ]
4007 ///            [k0 k2 k1 k3 ]
4008 ///       N2 =+[k1 k3 k0 k2 ]
4009 ///            [k0    k2    k1    k3    ]
4010 /// Extended =+[k1    k3    k0    k2    ]
4011 ///            [k0    k2    ]
4012 /// Extracted=+[k1    k3    ]
4013 ///
4014 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4015   EVT VT = N->getValueType(0);
4016   SDLoc DL(N);
4017
4018   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4019
4020   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4021   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4022   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4023   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4024   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4025
4026   if (VT.is64BitVector()) {
4027     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4028     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4029                        DAG.getIntPtrConstant(0));
4030   } else {
4031     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4032                                     DAG.getIntPtrConstant(0));
4033     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4034   }
4035 }
4036
4037 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4038                           const ARMSubtarget *ST) {
4039   EVT VT = N->getValueType(0);
4040
4041   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4042   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4043           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4044          "Unexpected type for custom ctpop lowering");
4045
4046   if (VT.getVectorElementType() == MVT::i32)
4047     return lowerCTPOP32BitElements(N, DAG);
4048   else
4049     return lowerCTPOP16BitElements(N, DAG);
4050 }
4051
4052 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4053                           const ARMSubtarget *ST) {
4054   EVT VT = N->getValueType(0);
4055   SDLoc dl(N);
4056
4057   if (!VT.isVector())
4058     return SDValue();
4059
4060   // Lower vector shifts on NEON to use VSHL.
4061   assert(ST->hasNEON() && "unexpected vector shift");
4062
4063   // Left shifts translate directly to the vshiftu intrinsic.
4064   if (N->getOpcode() == ISD::SHL)
4065     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4066                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4067                        N->getOperand(0), N->getOperand(1));
4068
4069   assert((N->getOpcode() == ISD::SRA ||
4070           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4071
4072   // NEON uses the same intrinsics for both left and right shifts.  For
4073   // right shifts, the shift amounts are negative, so negate the vector of
4074   // shift amounts.
4075   EVT ShiftVT = N->getOperand(1).getValueType();
4076   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4077                                      getZeroVector(ShiftVT, DAG, dl),
4078                                      N->getOperand(1));
4079   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4080                              Intrinsic::arm_neon_vshifts :
4081                              Intrinsic::arm_neon_vshiftu);
4082   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4083                      DAG.getConstant(vshiftInt, MVT::i32),
4084                      N->getOperand(0), NegatedCount);
4085 }
4086
4087 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4088                                 const ARMSubtarget *ST) {
4089   EVT VT = N->getValueType(0);
4090   SDLoc dl(N);
4091
4092   // We can get here for a node like i32 = ISD::SHL i32, i64
4093   if (VT != MVT::i64)
4094     return SDValue();
4095
4096   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4097          "Unknown shift to lower!");
4098
4099   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4100   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4101       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4102     return SDValue();
4103
4104   // If we are in thumb mode, we don't have RRX.
4105   if (ST->isThumb1Only()) return SDValue();
4106
4107   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4108   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4109                            DAG.getConstant(0, MVT::i32));
4110   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4111                            DAG.getConstant(1, MVT::i32));
4112
4113   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4114   // captures the result into a carry flag.
4115   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4116   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4117
4118   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4119   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4120
4121   // Merge the pieces into a single i64 value.
4122  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4123 }
4124
4125 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4126   SDValue TmpOp0, TmpOp1;
4127   bool Invert = false;
4128   bool Swap = false;
4129   unsigned Opc = 0;
4130
4131   SDValue Op0 = Op.getOperand(0);
4132   SDValue Op1 = Op.getOperand(1);
4133   SDValue CC = Op.getOperand(2);
4134   EVT VT = Op.getValueType();
4135   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4136   SDLoc dl(Op);
4137
4138   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4139     switch (SetCCOpcode) {
4140     default: llvm_unreachable("Illegal FP comparison");
4141     case ISD::SETUNE:
4142     case ISD::SETNE:  Invert = true; // Fallthrough
4143     case ISD::SETOEQ:
4144     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4145     case ISD::SETOLT:
4146     case ISD::SETLT: Swap = true; // Fallthrough
4147     case ISD::SETOGT:
4148     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4149     case ISD::SETOLE:
4150     case ISD::SETLE:  Swap = true; // Fallthrough
4151     case ISD::SETOGE:
4152     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4153     case ISD::SETUGE: Swap = true; // Fallthrough
4154     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4155     case ISD::SETUGT: Swap = true; // Fallthrough
4156     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4157     case ISD::SETUEQ: Invert = true; // Fallthrough
4158     case ISD::SETONE:
4159       // Expand this to (OLT | OGT).
4160       TmpOp0 = Op0;
4161       TmpOp1 = Op1;
4162       Opc = ISD::OR;
4163       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4164       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4165       break;
4166     case ISD::SETUO: Invert = true; // Fallthrough
4167     case ISD::SETO:
4168       // Expand this to (OLT | OGE).
4169       TmpOp0 = Op0;
4170       TmpOp1 = Op1;
4171       Opc = ISD::OR;
4172       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4173       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4174       break;
4175     }
4176   } else {
4177     // Integer comparisons.
4178     switch (SetCCOpcode) {
4179     default: llvm_unreachable("Illegal integer comparison");
4180     case ISD::SETNE:  Invert = true;
4181     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4182     case ISD::SETLT:  Swap = true;
4183     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4184     case ISD::SETLE:  Swap = true;
4185     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4186     case ISD::SETULT: Swap = true;
4187     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4188     case ISD::SETULE: Swap = true;
4189     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4190     }
4191
4192     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4193     if (Opc == ARMISD::VCEQ) {
4194
4195       SDValue AndOp;
4196       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4197         AndOp = Op0;
4198       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4199         AndOp = Op1;
4200
4201       // Ignore bitconvert.
4202       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4203         AndOp = AndOp.getOperand(0);
4204
4205       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4206         Opc = ARMISD::VTST;
4207         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4208         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4209         Invert = !Invert;
4210       }
4211     }
4212   }
4213
4214   if (Swap)
4215     std::swap(Op0, Op1);
4216
4217   // If one of the operands is a constant vector zero, attempt to fold the
4218   // comparison to a specialized compare-against-zero form.
4219   SDValue SingleOp;
4220   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4221     SingleOp = Op0;
4222   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4223     if (Opc == ARMISD::VCGE)
4224       Opc = ARMISD::VCLEZ;
4225     else if (Opc == ARMISD::VCGT)
4226       Opc = ARMISD::VCLTZ;
4227     SingleOp = Op1;
4228   }
4229
4230   SDValue Result;
4231   if (SingleOp.getNode()) {
4232     switch (Opc) {
4233     case ARMISD::VCEQ:
4234       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4235     case ARMISD::VCGE:
4236       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4237     case ARMISD::VCLEZ:
4238       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4239     case ARMISD::VCGT:
4240       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4241     case ARMISD::VCLTZ:
4242       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4243     default:
4244       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4245     }
4246   } else {
4247      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4248   }
4249
4250   if (Invert)
4251     Result = DAG.getNOT(dl, Result, VT);
4252
4253   return Result;
4254 }
4255
4256 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4257 /// valid vector constant for a NEON instruction with a "modified immediate"
4258 /// operand (e.g., VMOV).  If so, return the encoded value.
4259 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4260                                  unsigned SplatBitSize, SelectionDAG &DAG,
4261                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4262   unsigned OpCmode, Imm;
4263
4264   // SplatBitSize is set to the smallest size that splats the vector, so a
4265   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4266   // immediate instructions others than VMOV do not support the 8-bit encoding
4267   // of a zero vector, and the default encoding of zero is supposed to be the
4268   // 32-bit version.
4269   if (SplatBits == 0)
4270     SplatBitSize = 32;
4271
4272   switch (SplatBitSize) {
4273   case 8:
4274     if (type != VMOVModImm)
4275       return SDValue();
4276     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4277     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4278     OpCmode = 0xe;
4279     Imm = SplatBits;
4280     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4281     break;
4282
4283   case 16:
4284     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4285     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4286     if ((SplatBits & ~0xff) == 0) {
4287       // Value = 0x00nn: Op=x, Cmode=100x.
4288       OpCmode = 0x8;
4289       Imm = SplatBits;
4290       break;
4291     }
4292     if ((SplatBits & ~0xff00) == 0) {
4293       // Value = 0xnn00: Op=x, Cmode=101x.
4294       OpCmode = 0xa;
4295       Imm = SplatBits >> 8;
4296       break;
4297     }
4298     return SDValue();
4299
4300   case 32:
4301     // NEON's 32-bit VMOV supports splat values where:
4302     // * only one byte is nonzero, or
4303     // * the least significant byte is 0xff and the second byte is nonzero, or
4304     // * the least significant 2 bytes are 0xff and the third is nonzero.
4305     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4306     if ((SplatBits & ~0xff) == 0) {
4307       // Value = 0x000000nn: Op=x, Cmode=000x.
4308       OpCmode = 0;
4309       Imm = SplatBits;
4310       break;
4311     }
4312     if ((SplatBits & ~0xff00) == 0) {
4313       // Value = 0x0000nn00: Op=x, Cmode=001x.
4314       OpCmode = 0x2;
4315       Imm = SplatBits >> 8;
4316       break;
4317     }
4318     if ((SplatBits & ~0xff0000) == 0) {
4319       // Value = 0x00nn0000: Op=x, Cmode=010x.
4320       OpCmode = 0x4;
4321       Imm = SplatBits >> 16;
4322       break;
4323     }
4324     if ((SplatBits & ~0xff000000) == 0) {
4325       // Value = 0xnn000000: Op=x, Cmode=011x.
4326       OpCmode = 0x6;
4327       Imm = SplatBits >> 24;
4328       break;
4329     }
4330
4331     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4332     if (type == OtherModImm) return SDValue();
4333
4334     if ((SplatBits & ~0xffff) == 0 &&
4335         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4336       // Value = 0x0000nnff: Op=x, Cmode=1100.
4337       OpCmode = 0xc;
4338       Imm = SplatBits >> 8;
4339       break;
4340     }
4341
4342     if ((SplatBits & ~0xffffff) == 0 &&
4343         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4344       // Value = 0x00nnffff: Op=x, Cmode=1101.
4345       OpCmode = 0xd;
4346       Imm = SplatBits >> 16;
4347       break;
4348     }
4349
4350     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4351     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4352     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4353     // and fall through here to test for a valid 64-bit splat.  But, then the
4354     // caller would also need to check and handle the change in size.
4355     return SDValue();
4356
4357   case 64: {
4358     if (type != VMOVModImm)
4359       return SDValue();
4360     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4361     uint64_t BitMask = 0xff;
4362     uint64_t Val = 0;
4363     unsigned ImmMask = 1;
4364     Imm = 0;
4365     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4366       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4367         Val |= BitMask;
4368         Imm |= ImmMask;
4369       } else if ((SplatBits & BitMask) != 0) {
4370         return SDValue();
4371       }
4372       BitMask <<= 8;
4373       ImmMask <<= 1;
4374     }
4375     // Op=1, Cmode=1110.
4376     OpCmode = 0x1e;
4377     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4378     break;
4379   }
4380
4381   default:
4382     llvm_unreachable("unexpected size for isNEONModifiedImm");
4383   }
4384
4385   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4386   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4387 }
4388
4389 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4390                                            const ARMSubtarget *ST) const {
4391   if (!ST->hasVFP3())
4392     return SDValue();
4393
4394   bool IsDouble = Op.getValueType() == MVT::f64;
4395   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4396
4397   // Try splatting with a VMOV.f32...
4398   APFloat FPVal = CFP->getValueAPF();
4399   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4400
4401   if (ImmVal != -1) {
4402     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4403       // We have code in place to select a valid ConstantFP already, no need to
4404       // do any mangling.
4405       return Op;
4406     }
4407
4408     // It's a float and we are trying to use NEON operations where
4409     // possible. Lower it to a splat followed by an extract.
4410     SDLoc DL(Op);
4411     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4412     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4413                                       NewVal);
4414     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4415                        DAG.getConstant(0, MVT::i32));
4416   }
4417
4418   // The rest of our options are NEON only, make sure that's allowed before
4419   // proceeding..
4420   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4421     return SDValue();
4422
4423   EVT VMovVT;
4424   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4425
4426   // It wouldn't really be worth bothering for doubles except for one very
4427   // important value, which does happen to match: 0.0. So make sure we don't do
4428   // anything stupid.
4429   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4430     return SDValue();
4431
4432   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4433   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4434                                      false, VMOVModImm);
4435   if (NewVal != SDValue()) {
4436     SDLoc DL(Op);
4437     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4438                                       NewVal);
4439     if (IsDouble)
4440       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4441
4442     // It's a float: cast and extract a vector element.
4443     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4444                                        VecConstant);
4445     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4446                        DAG.getConstant(0, MVT::i32));
4447   }
4448
4449   // Finally, try a VMVN.i32
4450   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4451                              false, VMVNModImm);
4452   if (NewVal != SDValue()) {
4453     SDLoc DL(Op);
4454     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4455
4456     if (IsDouble)
4457       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4458
4459     // It's a float: cast and extract a vector element.
4460     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4461                                        VecConstant);
4462     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4463                        DAG.getConstant(0, MVT::i32));
4464   }
4465
4466   return SDValue();
4467 }
4468
4469 // check if an VEXT instruction can handle the shuffle mask when the
4470 // vector sources of the shuffle are the same.
4471 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4472   unsigned NumElts = VT.getVectorNumElements();
4473
4474   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4475   if (M[0] < 0)
4476     return false;
4477
4478   Imm = M[0];
4479
4480   // If this is a VEXT shuffle, the immediate value is the index of the first
4481   // element.  The other shuffle indices must be the successive elements after
4482   // the first one.
4483   unsigned ExpectedElt = Imm;
4484   for (unsigned i = 1; i < NumElts; ++i) {
4485     // Increment the expected index.  If it wraps around, just follow it
4486     // back to index zero and keep going.
4487     ++ExpectedElt;
4488     if (ExpectedElt == NumElts)
4489       ExpectedElt = 0;
4490
4491     if (M[i] < 0) continue; // ignore UNDEF indices
4492     if (ExpectedElt != static_cast<unsigned>(M[i]))
4493       return false;
4494   }
4495
4496   return true;
4497 }
4498
4499
4500 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4501                        bool &ReverseVEXT, unsigned &Imm) {
4502   unsigned NumElts = VT.getVectorNumElements();
4503   ReverseVEXT = false;
4504
4505   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4506   if (M[0] < 0)
4507     return false;
4508
4509   Imm = M[0];
4510
4511   // If this is a VEXT shuffle, the immediate value is the index of the first
4512   // element.  The other shuffle indices must be the successive elements after
4513   // the first one.
4514   unsigned ExpectedElt = Imm;
4515   for (unsigned i = 1; i < NumElts; ++i) {
4516     // Increment the expected index.  If it wraps around, it may still be
4517     // a VEXT but the source vectors must be swapped.
4518     ExpectedElt += 1;
4519     if (ExpectedElt == NumElts * 2) {
4520       ExpectedElt = 0;
4521       ReverseVEXT = true;
4522     }
4523
4524     if (M[i] < 0) continue; // ignore UNDEF indices
4525     if (ExpectedElt != static_cast<unsigned>(M[i]))
4526       return false;
4527   }
4528
4529   // Adjust the index value if the source operands will be swapped.
4530   if (ReverseVEXT)
4531     Imm -= NumElts;
4532
4533   return true;
4534 }
4535
4536 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4537 /// instruction with the specified blocksize.  (The order of the elements
4538 /// within each block of the vector is reversed.)
4539 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4540   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4541          "Only possible block sizes for VREV are: 16, 32, 64");
4542
4543   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4544   if (EltSz == 64)
4545     return false;
4546
4547   unsigned NumElts = VT.getVectorNumElements();
4548   unsigned BlockElts = M[0] + 1;
4549   // If the first shuffle index is UNDEF, be optimistic.
4550   if (M[0] < 0)
4551     BlockElts = BlockSize / EltSz;
4552
4553   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4554     return false;
4555
4556   for (unsigned i = 0; i < NumElts; ++i) {
4557     if (M[i] < 0) continue; // ignore UNDEF indices
4558     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4559       return false;
4560   }
4561
4562   return true;
4563 }
4564
4565 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4566   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4567   // range, then 0 is placed into the resulting vector. So pretty much any mask
4568   // of 8 elements can work here.
4569   return VT == MVT::v8i8 && M.size() == 8;
4570 }
4571
4572 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4573   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4574   if (EltSz == 64)
4575     return false;
4576
4577   unsigned NumElts = VT.getVectorNumElements();
4578   WhichResult = (M[0] == 0 ? 0 : 1);
4579   for (unsigned i = 0; i < NumElts; i += 2) {
4580     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4581         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4582       return false;
4583   }
4584   return true;
4585 }
4586
4587 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4588 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4589 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4590 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4591   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4592   if (EltSz == 64)
4593     return false;
4594
4595   unsigned NumElts = VT.getVectorNumElements();
4596   WhichResult = (M[0] == 0 ? 0 : 1);
4597   for (unsigned i = 0; i < NumElts; i += 2) {
4598     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4599         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4600       return false;
4601   }
4602   return true;
4603 }
4604
4605 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4606   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4607   if (EltSz == 64)
4608     return false;
4609
4610   unsigned NumElts = VT.getVectorNumElements();
4611   WhichResult = (M[0] == 0 ? 0 : 1);
4612   for (unsigned i = 0; i != NumElts; ++i) {
4613     if (M[i] < 0) continue; // ignore UNDEF indices
4614     if ((unsigned) M[i] != 2 * i + WhichResult)
4615       return false;
4616   }
4617
4618   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4619   if (VT.is64BitVector() && EltSz == 32)
4620     return false;
4621
4622   return true;
4623 }
4624
4625 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4626 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4627 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4628 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4629   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4630   if (EltSz == 64)
4631     return false;
4632
4633   unsigned Half = VT.getVectorNumElements() / 2;
4634   WhichResult = (M[0] == 0 ? 0 : 1);
4635   for (unsigned j = 0; j != 2; ++j) {
4636     unsigned Idx = WhichResult;
4637     for (unsigned i = 0; i != Half; ++i) {
4638       int MIdx = M[i + j * Half];
4639       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4640         return false;
4641       Idx += 2;
4642     }
4643   }
4644
4645   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4646   if (VT.is64BitVector() && EltSz == 32)
4647     return false;
4648
4649   return true;
4650 }
4651
4652 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4653   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4654   if (EltSz == 64)
4655     return false;
4656
4657   unsigned NumElts = VT.getVectorNumElements();
4658   WhichResult = (M[0] == 0 ? 0 : 1);
4659   unsigned Idx = WhichResult * NumElts / 2;
4660   for (unsigned i = 0; i != NumElts; i += 2) {
4661     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4662         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4663       return false;
4664     Idx += 1;
4665   }
4666
4667   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4668   if (VT.is64BitVector() && EltSz == 32)
4669     return false;
4670
4671   return true;
4672 }
4673
4674 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4675 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4676 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4677 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4678   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4679   if (EltSz == 64)
4680     return false;
4681
4682   unsigned NumElts = VT.getVectorNumElements();
4683   WhichResult = (M[0] == 0 ? 0 : 1);
4684   unsigned Idx = WhichResult * NumElts / 2;
4685   for (unsigned i = 0; i != NumElts; i += 2) {
4686     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4687         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4688       return false;
4689     Idx += 1;
4690   }
4691
4692   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4693   if (VT.is64BitVector() && EltSz == 32)
4694     return false;
4695
4696   return true;
4697 }
4698
4699 /// \return true if this is a reverse operation on an vector.
4700 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4701   unsigned NumElts = VT.getVectorNumElements();
4702   // Make sure the mask has the right size.
4703   if (NumElts != M.size())
4704       return false;
4705
4706   // Look for <15, ..., 3, -1, 1, 0>.
4707   for (unsigned i = 0; i != NumElts; ++i)
4708     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4709       return false;
4710
4711   return true;
4712 }
4713
4714 // If N is an integer constant that can be moved into a register in one
4715 // instruction, return an SDValue of such a constant (will become a MOV
4716 // instruction).  Otherwise return null.
4717 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4718                                      const ARMSubtarget *ST, SDLoc dl) {
4719   uint64_t Val;
4720   if (!isa<ConstantSDNode>(N))
4721     return SDValue();
4722   Val = cast<ConstantSDNode>(N)->getZExtValue();
4723
4724   if (ST->isThumb1Only()) {
4725     if (Val <= 255 || ~Val <= 255)
4726       return DAG.getConstant(Val, MVT::i32);
4727   } else {
4728     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4729       return DAG.getConstant(Val, MVT::i32);
4730   }
4731   return SDValue();
4732 }
4733
4734 // If this is a case we can't handle, return null and let the default
4735 // expansion code take care of it.
4736 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4737                                              const ARMSubtarget *ST) const {
4738   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4739   SDLoc dl(Op);
4740   EVT VT = Op.getValueType();
4741
4742   APInt SplatBits, SplatUndef;
4743   unsigned SplatBitSize;
4744   bool HasAnyUndefs;
4745   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4746     if (SplatBitSize <= 64) {
4747       // Check if an immediate VMOV works.
4748       EVT VmovVT;
4749       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4750                                       SplatUndef.getZExtValue(), SplatBitSize,
4751                                       DAG, VmovVT, VT.is128BitVector(),
4752                                       VMOVModImm);
4753       if (Val.getNode()) {
4754         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4755         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4756       }
4757
4758       // Try an immediate VMVN.
4759       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4760       Val = isNEONModifiedImm(NegatedImm,
4761                                       SplatUndef.getZExtValue(), SplatBitSize,
4762                                       DAG, VmovVT, VT.is128BitVector(),
4763                                       VMVNModImm);
4764       if (Val.getNode()) {
4765         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4766         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4767       }
4768
4769       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4770       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4771         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4772         if (ImmVal != -1) {
4773           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4774           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4775         }
4776       }
4777     }
4778   }
4779
4780   // Scan through the operands to see if only one value is used.
4781   //
4782   // As an optimisation, even if more than one value is used it may be more
4783   // profitable to splat with one value then change some lanes.
4784   //
4785   // Heuristically we decide to do this if the vector has a "dominant" value,
4786   // defined as splatted to more than half of the lanes.
4787   unsigned NumElts = VT.getVectorNumElements();
4788   bool isOnlyLowElement = true;
4789   bool usesOnlyOneValue = true;
4790   bool hasDominantValue = false;
4791   bool isConstant = true;
4792
4793   // Map of the number of times a particular SDValue appears in the
4794   // element list.
4795   DenseMap<SDValue, unsigned> ValueCounts;
4796   SDValue Value;
4797   for (unsigned i = 0; i < NumElts; ++i) {
4798     SDValue V = Op.getOperand(i);
4799     if (V.getOpcode() == ISD::UNDEF)
4800       continue;
4801     if (i > 0)
4802       isOnlyLowElement = false;
4803     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4804       isConstant = false;
4805
4806     ValueCounts.insert(std::make_pair(V, 0));
4807     unsigned &Count = ValueCounts[V];
4808
4809     // Is this value dominant? (takes up more than half of the lanes)
4810     if (++Count > (NumElts / 2)) {
4811       hasDominantValue = true;
4812       Value = V;
4813     }
4814   }
4815   if (ValueCounts.size() != 1)
4816     usesOnlyOneValue = false;
4817   if (!Value.getNode() && ValueCounts.size() > 0)
4818     Value = ValueCounts.begin()->first;
4819
4820   if (ValueCounts.size() == 0)
4821     return DAG.getUNDEF(VT);
4822
4823   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4824   // Keep going if we are hitting this case.
4825   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4826     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4827
4828   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4829
4830   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4831   // i32 and try again.
4832   if (hasDominantValue && EltSize <= 32) {
4833     if (!isConstant) {
4834       SDValue N;
4835
4836       // If we are VDUPing a value that comes directly from a vector, that will
4837       // cause an unnecessary move to and from a GPR, where instead we could
4838       // just use VDUPLANE. We can only do this if the lane being extracted
4839       // is at a constant index, as the VDUP from lane instructions only have
4840       // constant-index forms.
4841       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4842           isa<ConstantSDNode>(Value->getOperand(1))) {
4843         // We need to create a new undef vector to use for the VDUPLANE if the
4844         // size of the vector from which we get the value is different than the
4845         // size of the vector that we need to create. We will insert the element
4846         // such that the register coalescer will remove unnecessary copies.
4847         if (VT != Value->getOperand(0).getValueType()) {
4848           ConstantSDNode *constIndex;
4849           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4850           assert(constIndex && "The index is not a constant!");
4851           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4852                              VT.getVectorNumElements();
4853           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4854                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4855                         Value, DAG.getConstant(index, MVT::i32)),
4856                            DAG.getConstant(index, MVT::i32));
4857         } else
4858           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4859                         Value->getOperand(0), Value->getOperand(1));
4860       } else
4861         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4862
4863       if (!usesOnlyOneValue) {
4864         // The dominant value was splatted as 'N', but we now have to insert
4865         // all differing elements.
4866         for (unsigned I = 0; I < NumElts; ++I) {
4867           if (Op.getOperand(I) == Value)
4868             continue;
4869           SmallVector<SDValue, 3> Ops;
4870           Ops.push_back(N);
4871           Ops.push_back(Op.getOperand(I));
4872           Ops.push_back(DAG.getConstant(I, MVT::i32));
4873           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4874         }
4875       }
4876       return N;
4877     }
4878     if (VT.getVectorElementType().isFloatingPoint()) {
4879       SmallVector<SDValue, 8> Ops;
4880       for (unsigned i = 0; i < NumElts; ++i)
4881         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4882                                   Op.getOperand(i)));
4883       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4884       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4885       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4886       if (Val.getNode())
4887         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4888     }
4889     if (usesOnlyOneValue) {
4890       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4891       if (isConstant && Val.getNode())
4892         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4893     }
4894   }
4895
4896   // If all elements are constants and the case above didn't get hit, fall back
4897   // to the default expansion, which will generate a load from the constant
4898   // pool.
4899   if (isConstant)
4900     return SDValue();
4901
4902   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4903   if (NumElts >= 4) {
4904     SDValue shuffle = ReconstructShuffle(Op, DAG);
4905     if (shuffle != SDValue())
4906       return shuffle;
4907   }
4908
4909   // Vectors with 32- or 64-bit elements can be built by directly assigning
4910   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4911   // will be legalized.
4912   if (EltSize >= 32) {
4913     // Do the expansion with floating-point types, since that is what the VFP
4914     // registers are defined to use, and since i64 is not legal.
4915     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4916     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4917     SmallVector<SDValue, 8> Ops;
4918     for (unsigned i = 0; i < NumElts; ++i)
4919       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4920     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4921     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4922   }
4923
4924   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4925   // know the default expansion would otherwise fall back on something even
4926   // worse. For a vector with one or two non-undef values, that's
4927   // scalar_to_vector for the elements followed by a shuffle (provided the
4928   // shuffle is valid for the target) and materialization element by element
4929   // on the stack followed by a load for everything else.
4930   if (!isConstant && !usesOnlyOneValue) {
4931     SDValue Vec = DAG.getUNDEF(VT);
4932     for (unsigned i = 0 ; i < NumElts; ++i) {
4933       SDValue V = Op.getOperand(i);
4934       if (V.getOpcode() == ISD::UNDEF)
4935         continue;
4936       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4937       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4938     }
4939     return Vec;
4940   }
4941
4942   return SDValue();
4943 }
4944
4945 // Gather data to see if the operation can be modelled as a
4946 // shuffle in combination with VEXTs.
4947 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4948                                               SelectionDAG &DAG) const {
4949   SDLoc dl(Op);
4950   EVT VT = Op.getValueType();
4951   unsigned NumElts = VT.getVectorNumElements();
4952
4953   SmallVector<SDValue, 2> SourceVecs;
4954   SmallVector<unsigned, 2> MinElts;
4955   SmallVector<unsigned, 2> MaxElts;
4956
4957   for (unsigned i = 0; i < NumElts; ++i) {
4958     SDValue V = Op.getOperand(i);
4959     if (V.getOpcode() == ISD::UNDEF)
4960       continue;
4961     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4962       // A shuffle can only come from building a vector from various
4963       // elements of other vectors.
4964       return SDValue();
4965     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4966                VT.getVectorElementType()) {
4967       // This code doesn't know how to handle shuffles where the vector
4968       // element types do not match (this happens because type legalization
4969       // promotes the return type of EXTRACT_VECTOR_ELT).
4970       // FIXME: It might be appropriate to extend this code to handle
4971       // mismatched types.
4972       return SDValue();
4973     }
4974
4975     // Record this extraction against the appropriate vector if possible...
4976     SDValue SourceVec = V.getOperand(0);
4977     // If the element number isn't a constant, we can't effectively
4978     // analyze what's going on.
4979     if (!isa<ConstantSDNode>(V.getOperand(1)))
4980       return SDValue();
4981     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4982     bool FoundSource = false;
4983     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4984       if (SourceVecs[j] == SourceVec) {
4985         if (MinElts[j] > EltNo)
4986           MinElts[j] = EltNo;
4987         if (MaxElts[j] < EltNo)
4988           MaxElts[j] = EltNo;
4989         FoundSource = true;
4990         break;
4991       }
4992     }
4993
4994     // Or record a new source if not...
4995     if (!FoundSource) {
4996       SourceVecs.push_back(SourceVec);
4997       MinElts.push_back(EltNo);
4998       MaxElts.push_back(EltNo);
4999     }
5000   }
5001
5002   // Currently only do something sane when at most two source vectors
5003   // involved.
5004   if (SourceVecs.size() > 2)
5005     return SDValue();
5006
5007   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5008   int VEXTOffsets[2] = {0, 0};
5009
5010   // This loop extracts the usage patterns of the source vectors
5011   // and prepares appropriate SDValues for a shuffle if possible.
5012   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5013     if (SourceVecs[i].getValueType() == VT) {
5014       // No VEXT necessary
5015       ShuffleSrcs[i] = SourceVecs[i];
5016       VEXTOffsets[i] = 0;
5017       continue;
5018     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5019       // It probably isn't worth padding out a smaller vector just to
5020       // break it down again in a shuffle.
5021       return SDValue();
5022     }
5023
5024     // Since only 64-bit and 128-bit vectors are legal on ARM and
5025     // we've eliminated the other cases...
5026     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5027            "unexpected vector sizes in ReconstructShuffle");
5028
5029     if (MaxElts[i] - MinElts[i] >= NumElts) {
5030       // Span too large for a VEXT to cope
5031       return SDValue();
5032     }
5033
5034     if (MinElts[i] >= NumElts) {
5035       // The extraction can just take the second half
5036       VEXTOffsets[i] = NumElts;
5037       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5038                                    SourceVecs[i],
5039                                    DAG.getIntPtrConstant(NumElts));
5040     } else if (MaxElts[i] < NumElts) {
5041       // The extraction can just take the first half
5042       VEXTOffsets[i] = 0;
5043       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5044                                    SourceVecs[i],
5045                                    DAG.getIntPtrConstant(0));
5046     } else {
5047       // An actual VEXT is needed
5048       VEXTOffsets[i] = MinElts[i];
5049       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5050                                      SourceVecs[i],
5051                                      DAG.getIntPtrConstant(0));
5052       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5053                                      SourceVecs[i],
5054                                      DAG.getIntPtrConstant(NumElts));
5055       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5056                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5057     }
5058   }
5059
5060   SmallVector<int, 8> Mask;
5061
5062   for (unsigned i = 0; i < NumElts; ++i) {
5063     SDValue Entry = Op.getOperand(i);
5064     if (Entry.getOpcode() == ISD::UNDEF) {
5065       Mask.push_back(-1);
5066       continue;
5067     }
5068
5069     SDValue ExtractVec = Entry.getOperand(0);
5070     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5071                                           .getOperand(1))->getSExtValue();
5072     if (ExtractVec == SourceVecs[0]) {
5073       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5074     } else {
5075       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5076     }
5077   }
5078
5079   // Final check before we try to produce nonsense...
5080   if (isShuffleMaskLegal(Mask, VT))
5081     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5082                                 &Mask[0]);
5083
5084   return SDValue();
5085 }
5086
5087 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5088 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5089 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5090 /// are assumed to be legal.
5091 bool
5092 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5093                                       EVT VT) const {
5094   if (VT.getVectorNumElements() == 4 &&
5095       (VT.is128BitVector() || VT.is64BitVector())) {
5096     unsigned PFIndexes[4];
5097     for (unsigned i = 0; i != 4; ++i) {
5098       if (M[i] < 0)
5099         PFIndexes[i] = 8;
5100       else
5101         PFIndexes[i] = M[i];
5102     }
5103
5104     // Compute the index in the perfect shuffle table.
5105     unsigned PFTableIndex =
5106       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5107     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5108     unsigned Cost = (PFEntry >> 30);
5109
5110     if (Cost <= 4)
5111       return true;
5112   }
5113
5114   bool ReverseVEXT;
5115   unsigned Imm, WhichResult;
5116
5117   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5118   return (EltSize >= 32 ||
5119           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5120           isVREVMask(M, VT, 64) ||
5121           isVREVMask(M, VT, 32) ||
5122           isVREVMask(M, VT, 16) ||
5123           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5124           isVTBLMask(M, VT) ||
5125           isVTRNMask(M, VT, WhichResult) ||
5126           isVUZPMask(M, VT, WhichResult) ||
5127           isVZIPMask(M, VT, WhichResult) ||
5128           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5129           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5130           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5131           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5132 }
5133
5134 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5135 /// the specified operations to build the shuffle.
5136 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5137                                       SDValue RHS, SelectionDAG &DAG,
5138                                       SDLoc dl) {
5139   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5140   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5141   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5142
5143   enum {
5144     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5145     OP_VREV,
5146     OP_VDUP0,
5147     OP_VDUP1,
5148     OP_VDUP2,
5149     OP_VDUP3,
5150     OP_VEXT1,
5151     OP_VEXT2,
5152     OP_VEXT3,
5153     OP_VUZPL, // VUZP, left result
5154     OP_VUZPR, // VUZP, right result
5155     OP_VZIPL, // VZIP, left result
5156     OP_VZIPR, // VZIP, right result
5157     OP_VTRNL, // VTRN, left result
5158     OP_VTRNR  // VTRN, right result
5159   };
5160
5161   if (OpNum == OP_COPY) {
5162     if (LHSID == (1*9+2)*9+3) return LHS;
5163     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5164     return RHS;
5165   }
5166
5167   SDValue OpLHS, OpRHS;
5168   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5169   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5170   EVT VT = OpLHS.getValueType();
5171
5172   switch (OpNum) {
5173   default: llvm_unreachable("Unknown shuffle opcode!");
5174   case OP_VREV:
5175     // VREV divides the vector in half and swaps within the half.
5176     if (VT.getVectorElementType() == MVT::i32 ||
5177         VT.getVectorElementType() == MVT::f32)
5178       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5179     // vrev <4 x i16> -> VREV32
5180     if (VT.getVectorElementType() == MVT::i16)
5181       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5182     // vrev <4 x i8> -> VREV16
5183     assert(VT.getVectorElementType() == MVT::i8);
5184     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5185   case OP_VDUP0:
5186   case OP_VDUP1:
5187   case OP_VDUP2:
5188   case OP_VDUP3:
5189     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5190                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5191   case OP_VEXT1:
5192   case OP_VEXT2:
5193   case OP_VEXT3:
5194     return DAG.getNode(ARMISD::VEXT, dl, VT,
5195                        OpLHS, OpRHS,
5196                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5197   case OP_VUZPL:
5198   case OP_VUZPR:
5199     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5200                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5201   case OP_VZIPL:
5202   case OP_VZIPR:
5203     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5204                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5205   case OP_VTRNL:
5206   case OP_VTRNR:
5207     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5208                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5209   }
5210 }
5211
5212 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5213                                        ArrayRef<int> ShuffleMask,
5214                                        SelectionDAG &DAG) {
5215   // Check to see if we can use the VTBL instruction.
5216   SDValue V1 = Op.getOperand(0);
5217   SDValue V2 = Op.getOperand(1);
5218   SDLoc DL(Op);
5219
5220   SmallVector<SDValue, 8> VTBLMask;
5221   for (ArrayRef<int>::iterator
5222          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5223     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5224
5225   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5226     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5227                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5228                                    &VTBLMask[0], 8));
5229
5230   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5231                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5232                                  &VTBLMask[0], 8));
5233 }
5234
5235 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5236                                                       SelectionDAG &DAG) {
5237   SDLoc DL(Op);
5238   SDValue OpLHS = Op.getOperand(0);
5239   EVT VT = OpLHS.getValueType();
5240
5241   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5242          "Expect an v8i16/v16i8 type");
5243   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5244   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5245   // extract the first 8 bytes into the top double word and the last 8 bytes
5246   // into the bottom double word. The v8i16 case is similar.
5247   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5248   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5249                      DAG.getConstant(ExtractNum, MVT::i32));
5250 }
5251
5252 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5253   SDValue V1 = Op.getOperand(0);
5254   SDValue V2 = Op.getOperand(1);
5255   SDLoc dl(Op);
5256   EVT VT = Op.getValueType();
5257   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5258
5259   // Convert shuffles that are directly supported on NEON to target-specific
5260   // DAG nodes, instead of keeping them as shuffles and matching them again
5261   // during code selection.  This is more efficient and avoids the possibility
5262   // of inconsistencies between legalization and selection.
5263   // FIXME: floating-point vectors should be canonicalized to integer vectors
5264   // of the same time so that they get CSEd properly.
5265   ArrayRef<int> ShuffleMask = SVN->getMask();
5266
5267   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5268   if (EltSize <= 32) {
5269     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5270       int Lane = SVN->getSplatIndex();
5271       // If this is undef splat, generate it via "just" vdup, if possible.
5272       if (Lane == -1) Lane = 0;
5273
5274       // Test if V1 is a SCALAR_TO_VECTOR.
5275       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5276         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5277       }
5278       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5279       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5280       // reaches it).
5281       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5282           !isa<ConstantSDNode>(V1.getOperand(0))) {
5283         bool IsScalarToVector = true;
5284         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5285           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5286             IsScalarToVector = false;
5287             break;
5288           }
5289         if (IsScalarToVector)
5290           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5291       }
5292       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5293                          DAG.getConstant(Lane, MVT::i32));
5294     }
5295
5296     bool ReverseVEXT;
5297     unsigned Imm;
5298     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5299       if (ReverseVEXT)
5300         std::swap(V1, V2);
5301       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5302                          DAG.getConstant(Imm, MVT::i32));
5303     }
5304
5305     if (isVREVMask(ShuffleMask, VT, 64))
5306       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5307     if (isVREVMask(ShuffleMask, VT, 32))
5308       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5309     if (isVREVMask(ShuffleMask, VT, 16))
5310       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5311
5312     if (V2->getOpcode() == ISD::UNDEF &&
5313         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5314       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5315                          DAG.getConstant(Imm, MVT::i32));
5316     }
5317
5318     // Check for Neon shuffles that modify both input vectors in place.
5319     // If both results are used, i.e., if there are two shuffles with the same
5320     // source operands and with masks corresponding to both results of one of
5321     // these operations, DAG memoization will ensure that a single node is
5322     // used for both shuffles.
5323     unsigned WhichResult;
5324     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5325       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5326                          V1, V2).getValue(WhichResult);
5327     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5328       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5329                          V1, V2).getValue(WhichResult);
5330     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5331       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5332                          V1, V2).getValue(WhichResult);
5333
5334     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5335       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5336                          V1, V1).getValue(WhichResult);
5337     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5338       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5339                          V1, V1).getValue(WhichResult);
5340     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5341       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5342                          V1, V1).getValue(WhichResult);
5343   }
5344
5345   // If the shuffle is not directly supported and it has 4 elements, use
5346   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5347   unsigned NumElts = VT.getVectorNumElements();
5348   if (NumElts == 4) {
5349     unsigned PFIndexes[4];
5350     for (unsigned i = 0; i != 4; ++i) {
5351       if (ShuffleMask[i] < 0)
5352         PFIndexes[i] = 8;
5353       else
5354         PFIndexes[i] = ShuffleMask[i];
5355     }
5356
5357     // Compute the index in the perfect shuffle table.
5358     unsigned PFTableIndex =
5359       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5360     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5361     unsigned Cost = (PFEntry >> 30);
5362
5363     if (Cost <= 4)
5364       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5365   }
5366
5367   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5368   if (EltSize >= 32) {
5369     // Do the expansion with floating-point types, since that is what the VFP
5370     // registers are defined to use, and since i64 is not legal.
5371     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5372     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5373     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5374     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5375     SmallVector<SDValue, 8> Ops;
5376     for (unsigned i = 0; i < NumElts; ++i) {
5377       if (ShuffleMask[i] < 0)
5378         Ops.push_back(DAG.getUNDEF(EltVT));
5379       else
5380         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5381                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5382                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5383                                                   MVT::i32)));
5384     }
5385     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5386     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5387   }
5388
5389   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5390     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5391
5392   if (VT == MVT::v8i8) {
5393     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5394     if (NewOp.getNode())
5395       return NewOp;
5396   }
5397
5398   return SDValue();
5399 }
5400
5401 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5402   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5403   SDValue Lane = Op.getOperand(2);
5404   if (!isa<ConstantSDNode>(Lane))
5405     return SDValue();
5406
5407   return Op;
5408 }
5409
5410 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5411   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5412   SDValue Lane = Op.getOperand(1);
5413   if (!isa<ConstantSDNode>(Lane))
5414     return SDValue();
5415
5416   SDValue Vec = Op.getOperand(0);
5417   if (Op.getValueType() == MVT::i32 &&
5418       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5419     SDLoc dl(Op);
5420     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5421   }
5422
5423   return Op;
5424 }
5425
5426 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5427   // The only time a CONCAT_VECTORS operation can have legal types is when
5428   // two 64-bit vectors are concatenated to a 128-bit vector.
5429   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5430          "unexpected CONCAT_VECTORS");
5431   SDLoc dl(Op);
5432   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5433   SDValue Op0 = Op.getOperand(0);
5434   SDValue Op1 = Op.getOperand(1);
5435   if (Op0.getOpcode() != ISD::UNDEF)
5436     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5437                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5438                       DAG.getIntPtrConstant(0));
5439   if (Op1.getOpcode() != ISD::UNDEF)
5440     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5441                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5442                       DAG.getIntPtrConstant(1));
5443   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5444 }
5445
5446 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5447 /// element has been zero/sign-extended, depending on the isSigned parameter,
5448 /// from an integer type half its size.
5449 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5450                                    bool isSigned) {
5451   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5452   EVT VT = N->getValueType(0);
5453   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5454     SDNode *BVN = N->getOperand(0).getNode();
5455     if (BVN->getValueType(0) != MVT::v4i32 ||
5456         BVN->getOpcode() != ISD::BUILD_VECTOR)
5457       return false;
5458     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5459     unsigned HiElt = 1 - LoElt;
5460     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5461     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5462     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5463     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5464     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5465       return false;
5466     if (isSigned) {
5467       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5468           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5469         return true;
5470     } else {
5471       if (Hi0->isNullValue() && Hi1->isNullValue())
5472         return true;
5473     }
5474     return false;
5475   }
5476
5477   if (N->getOpcode() != ISD::BUILD_VECTOR)
5478     return false;
5479
5480   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5481     SDNode *Elt = N->getOperand(i).getNode();
5482     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5483       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5484       unsigned HalfSize = EltSize / 2;
5485       if (isSigned) {
5486         if (!isIntN(HalfSize, C->getSExtValue()))
5487           return false;
5488       } else {
5489         if (!isUIntN(HalfSize, C->getZExtValue()))
5490           return false;
5491       }
5492       continue;
5493     }
5494     return false;
5495   }
5496
5497   return true;
5498 }
5499
5500 /// isSignExtended - Check if a node is a vector value that is sign-extended
5501 /// or a constant BUILD_VECTOR with sign-extended elements.
5502 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5503   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5504     return true;
5505   if (isExtendedBUILD_VECTOR(N, DAG, true))
5506     return true;
5507   return false;
5508 }
5509
5510 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5511 /// or a constant BUILD_VECTOR with zero-extended elements.
5512 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5513   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5514     return true;
5515   if (isExtendedBUILD_VECTOR(N, DAG, false))
5516     return true;
5517   return false;
5518 }
5519
5520 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5521   if (OrigVT.getSizeInBits() >= 64)
5522     return OrigVT;
5523
5524   assert(OrigVT.isSimple() && "Expecting a simple value type");
5525
5526   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5527   switch (OrigSimpleTy) {
5528   default: llvm_unreachable("Unexpected Vector Type");
5529   case MVT::v2i8:
5530   case MVT::v2i16:
5531      return MVT::v2i32;
5532   case MVT::v4i8:
5533     return  MVT::v4i16;
5534   }
5535 }
5536
5537 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5538 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5539 /// We insert the required extension here to get the vector to fill a D register.
5540 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5541                                             const EVT &OrigTy,
5542                                             const EVT &ExtTy,
5543                                             unsigned ExtOpcode) {
5544   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5545   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5546   // 64-bits we need to insert a new extension so that it will be 64-bits.
5547   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5548   if (OrigTy.getSizeInBits() >= 64)
5549     return N;
5550
5551   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5552   EVT NewVT = getExtensionTo64Bits(OrigTy);
5553
5554   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5555 }
5556
5557 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5558 /// does not do any sign/zero extension. If the original vector is less
5559 /// than 64 bits, an appropriate extension will be added after the load to
5560 /// reach a total size of 64 bits. We have to add the extension separately
5561 /// because ARM does not have a sign/zero extending load for vectors.
5562 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5563   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5564
5565   // The load already has the right type.
5566   if (ExtendedTy == LD->getMemoryVT())
5567     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5568                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5569                 LD->isNonTemporal(), LD->isInvariant(),
5570                 LD->getAlignment());
5571
5572   // We need to create a zextload/sextload. We cannot just create a load
5573   // followed by a zext/zext node because LowerMUL is also run during normal
5574   // operation legalization where we can't create illegal types.
5575   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5576                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5577                         LD->getMemoryVT(), LD->isVolatile(),
5578                         LD->isNonTemporal(), LD->getAlignment());
5579 }
5580
5581 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5582 /// extending load, or BUILD_VECTOR with extended elements, return the
5583 /// unextended value. The unextended vector should be 64 bits so that it can
5584 /// be used as an operand to a VMULL instruction. If the original vector size
5585 /// before extension is less than 64 bits we add a an extension to resize
5586 /// the vector to 64 bits.
5587 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5588   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5589     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5590                                         N->getOperand(0)->getValueType(0),
5591                                         N->getValueType(0),
5592                                         N->getOpcode());
5593
5594   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5595     return SkipLoadExtensionForVMULL(LD, DAG);
5596
5597   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5598   // have been legalized as a BITCAST from v4i32.
5599   if (N->getOpcode() == ISD::BITCAST) {
5600     SDNode *BVN = N->getOperand(0).getNode();
5601     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5602            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5603     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5604     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5605                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5606   }
5607   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5608   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5609   EVT VT = N->getValueType(0);
5610   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5611   unsigned NumElts = VT.getVectorNumElements();
5612   MVT TruncVT = MVT::getIntegerVT(EltSize);
5613   SmallVector<SDValue, 8> Ops;
5614   for (unsigned i = 0; i != NumElts; ++i) {
5615     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5616     const APInt &CInt = C->getAPIntValue();
5617     // Element types smaller than 32 bits are not legal, so use i32 elements.
5618     // The values are implicitly truncated so sext vs. zext doesn't matter.
5619     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5620   }
5621   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5622                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5623 }
5624
5625 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5626   unsigned Opcode = N->getOpcode();
5627   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5628     SDNode *N0 = N->getOperand(0).getNode();
5629     SDNode *N1 = N->getOperand(1).getNode();
5630     return N0->hasOneUse() && N1->hasOneUse() &&
5631       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5632   }
5633   return false;
5634 }
5635
5636 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5637   unsigned Opcode = N->getOpcode();
5638   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5639     SDNode *N0 = N->getOperand(0).getNode();
5640     SDNode *N1 = N->getOperand(1).getNode();
5641     return N0->hasOneUse() && N1->hasOneUse() &&
5642       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5643   }
5644   return false;
5645 }
5646
5647 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5648   // Multiplications are only custom-lowered for 128-bit vectors so that
5649   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5650   EVT VT = Op.getValueType();
5651   assert(VT.is128BitVector() && VT.isInteger() &&
5652          "unexpected type for custom-lowering ISD::MUL");
5653   SDNode *N0 = Op.getOperand(0).getNode();
5654   SDNode *N1 = Op.getOperand(1).getNode();
5655   unsigned NewOpc = 0;
5656   bool isMLA = false;
5657   bool isN0SExt = isSignExtended(N0, DAG);
5658   bool isN1SExt = isSignExtended(N1, DAG);
5659   if (isN0SExt && isN1SExt)
5660     NewOpc = ARMISD::VMULLs;
5661   else {
5662     bool isN0ZExt = isZeroExtended(N0, DAG);
5663     bool isN1ZExt = isZeroExtended(N1, DAG);
5664     if (isN0ZExt && isN1ZExt)
5665       NewOpc = ARMISD::VMULLu;
5666     else if (isN1SExt || isN1ZExt) {
5667       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5668       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5669       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5670         NewOpc = ARMISD::VMULLs;
5671         isMLA = true;
5672       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5673         NewOpc = ARMISD::VMULLu;
5674         isMLA = true;
5675       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5676         std::swap(N0, N1);
5677         NewOpc = ARMISD::VMULLu;
5678         isMLA = true;
5679       }
5680     }
5681
5682     if (!NewOpc) {
5683       if (VT == MVT::v2i64)
5684         // Fall through to expand this.  It is not legal.
5685         return SDValue();
5686       else
5687         // Other vector multiplications are legal.
5688         return Op;
5689     }
5690   }
5691
5692   // Legalize to a VMULL instruction.
5693   SDLoc DL(Op);
5694   SDValue Op0;
5695   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5696   if (!isMLA) {
5697     Op0 = SkipExtensionForVMULL(N0, DAG);
5698     assert(Op0.getValueType().is64BitVector() &&
5699            Op1.getValueType().is64BitVector() &&
5700            "unexpected types for extended operands to VMULL");
5701     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5702   }
5703
5704   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5705   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5706   //   vmull q0, d4, d6
5707   //   vmlal q0, d5, d6
5708   // is faster than
5709   //   vaddl q0, d4, d5
5710   //   vmovl q1, d6
5711   //   vmul  q0, q0, q1
5712   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5713   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5714   EVT Op1VT = Op1.getValueType();
5715   return DAG.getNode(N0->getOpcode(), DL, VT,
5716                      DAG.getNode(NewOpc, DL, VT,
5717                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5718                      DAG.getNode(NewOpc, DL, VT,
5719                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5720 }
5721
5722 static SDValue
5723 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5724   // Convert to float
5725   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5726   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5727   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5728   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5729   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5730   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5731   // Get reciprocal estimate.
5732   // float4 recip = vrecpeq_f32(yf);
5733   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5734                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5735   // Because char has a smaller range than uchar, we can actually get away
5736   // without any newton steps.  This requires that we use a weird bias
5737   // of 0xb000, however (again, this has been exhaustively tested).
5738   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5739   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5740   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5741   Y = DAG.getConstant(0xb000, MVT::i32);
5742   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5743   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5744   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5745   // Convert back to short.
5746   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5747   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5748   return X;
5749 }
5750
5751 static SDValue
5752 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5753   SDValue N2;
5754   // Convert to float.
5755   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5756   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5757   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5758   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5759   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5760   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5761
5762   // Use reciprocal estimate and one refinement step.
5763   // float4 recip = vrecpeq_f32(yf);
5764   // recip *= vrecpsq_f32(yf, recip);
5765   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5766                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5767   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5768                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5769                    N1, N2);
5770   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5771   // Because short has a smaller range than ushort, we can actually get away
5772   // with only a single newton step.  This requires that we use a weird bias
5773   // of 89, however (again, this has been exhaustively tested).
5774   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5775   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5776   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5777   N1 = DAG.getConstant(0x89, MVT::i32);
5778   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5779   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5780   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5781   // Convert back to integer and return.
5782   // return vmovn_s32(vcvt_s32_f32(result));
5783   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5784   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5785   return N0;
5786 }
5787
5788 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5789   EVT VT = Op.getValueType();
5790   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5791          "unexpected type for custom-lowering ISD::SDIV");
5792
5793   SDLoc dl(Op);
5794   SDValue N0 = Op.getOperand(0);
5795   SDValue N1 = Op.getOperand(1);
5796   SDValue N2, N3;
5797
5798   if (VT == MVT::v8i8) {
5799     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5800     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5801
5802     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5803                      DAG.getIntPtrConstant(4));
5804     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5805                      DAG.getIntPtrConstant(4));
5806     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5807                      DAG.getIntPtrConstant(0));
5808     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5809                      DAG.getIntPtrConstant(0));
5810
5811     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5812     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5813
5814     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5815     N0 = LowerCONCAT_VECTORS(N0, DAG);
5816
5817     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5818     return N0;
5819   }
5820   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5821 }
5822
5823 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5824   EVT VT = Op.getValueType();
5825   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5826          "unexpected type for custom-lowering ISD::UDIV");
5827
5828   SDLoc dl(Op);
5829   SDValue N0 = Op.getOperand(0);
5830   SDValue N1 = Op.getOperand(1);
5831   SDValue N2, N3;
5832
5833   if (VT == MVT::v8i8) {
5834     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5835     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5836
5837     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5838                      DAG.getIntPtrConstant(4));
5839     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5840                      DAG.getIntPtrConstant(4));
5841     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5842                      DAG.getIntPtrConstant(0));
5843     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5844                      DAG.getIntPtrConstant(0));
5845
5846     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5847     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5848
5849     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5850     N0 = LowerCONCAT_VECTORS(N0, DAG);
5851
5852     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5853                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5854                      N0);
5855     return N0;
5856   }
5857
5858   // v4i16 sdiv ... Convert to float.
5859   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5860   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5861   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5862   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5863   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5864   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5865
5866   // Use reciprocal estimate and two refinement steps.
5867   // float4 recip = vrecpeq_f32(yf);
5868   // recip *= vrecpsq_f32(yf, recip);
5869   // recip *= vrecpsq_f32(yf, recip);
5870   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5871                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5872   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5873                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5874                    BN1, N2);
5875   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5876   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5877                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5878                    BN1, N2);
5879   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5880   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5881   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5882   // and that it will never cause us to return an answer too large).
5883   // float4 result = as_float4(as_int4(xf*recip) + 2);
5884   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5885   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5886   N1 = DAG.getConstant(2, MVT::i32);
5887   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5888   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5889   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5890   // Convert back to integer and return.
5891   // return vmovn_u32(vcvt_s32_f32(result));
5892   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5893   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5894   return N0;
5895 }
5896
5897 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5898   EVT VT = Op.getNode()->getValueType(0);
5899   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5900
5901   unsigned Opc;
5902   bool ExtraOp = false;
5903   switch (Op.getOpcode()) {
5904   default: llvm_unreachable("Invalid code");
5905   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5906   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5907   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5908   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5909   }
5910
5911   if (!ExtraOp)
5912     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5913                        Op.getOperand(1));
5914   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5915                      Op.getOperand(1), Op.getOperand(2));
5916 }
5917
5918 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5919   assert(Subtarget->isTargetDarwin());
5920
5921   // For iOS, we want to call an alternative entry point: __sincos_stret,
5922   // return values are passed via sret.
5923   SDLoc dl(Op);
5924   SDValue Arg = Op.getOperand(0);
5925   EVT ArgVT = Arg.getValueType();
5926   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5927
5928   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5930
5931   // Pair of floats / doubles used to pass the result.
5932   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5933
5934   // Create stack object for sret.
5935   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5936   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5937   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5938   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5939
5940   ArgListTy Args;
5941   ArgListEntry Entry;
5942
5943   Entry.Node = SRet;
5944   Entry.Ty = RetTy->getPointerTo();
5945   Entry.isSExt = false;
5946   Entry.isZExt = false;
5947   Entry.isSRet = true;
5948   Args.push_back(Entry);
5949
5950   Entry.Node = Arg;
5951   Entry.Ty = ArgTy;
5952   Entry.isSExt = false;
5953   Entry.isZExt = false;
5954   Args.push_back(Entry);
5955
5956   const char *LibcallName  = (ArgVT == MVT::f64)
5957   ? "__sincos_stret" : "__sincosf_stret";
5958   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5959
5960   TargetLowering::
5961   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5962                        false, false, false, false, 0,
5963                        CallingConv::C, /*isTaillCall=*/false,
5964                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5965                        Callee, Args, DAG, dl);
5966   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5967
5968   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5969                                 MachinePointerInfo(), false, false, false, 0);
5970
5971   // Address of cos field.
5972   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5973                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5974   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5975                                 MachinePointerInfo(), false, false, false, 0);
5976
5977   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5978   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5979                      LoadSin.getValue(0), LoadCos.getValue(0));
5980 }
5981
5982 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5983   // Monotonic load/store is legal for all targets
5984   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5985     return Op;
5986
5987   // Acquire/Release load/store is not legal for targets without a
5988   // dmb or equivalent available.
5989   return SDValue();
5990 }
5991
5992 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5993                                     SmallVectorImpl<SDValue> &Results,
5994                                     SelectionDAG &DAG,
5995                                     const ARMSubtarget *Subtarget) {
5996   SDLoc DL(N);
5997   SDValue Cycles32, OutChain;
5998
5999   if (Subtarget->hasPerfMon()) {
6000     // Under Power Management extensions, the cycle-count is:
6001     //    mrc p15, #0, <Rt>, c9, c13, #0
6002     SDValue Ops[] = { N->getOperand(0), // Chain
6003                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6004                       DAG.getConstant(15, MVT::i32),
6005                       DAG.getConstant(0, MVT::i32),
6006                       DAG.getConstant(9, MVT::i32),
6007                       DAG.getConstant(13, MVT::i32),
6008                       DAG.getConstant(0, MVT::i32)
6009     };
6010
6011     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6012                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6013                            array_lengthof(Ops));
6014     OutChain = Cycles32.getValue(1);
6015   } else {
6016     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6017     // there are older ARM CPUs that have implementation-specific ways of
6018     // obtaining this information (FIXME!).
6019     Cycles32 = DAG.getConstant(0, MVT::i32);
6020     OutChain = DAG.getEntryNode();
6021   }
6022
6023
6024   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6025                                  Cycles32, DAG.getConstant(0, MVT::i32));
6026   Results.push_back(Cycles64);
6027   Results.push_back(OutChain);
6028 }
6029
6030 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6031   switch (Op.getOpcode()) {
6032   default: llvm_unreachable("Don't know how to custom lower this!");
6033   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6034   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6035   case ISD::GlobalAddress:
6036     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6037       LowerGlobalAddressELF(Op, DAG);
6038   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6039   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6040   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6041   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6042   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6043   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6044   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6045   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6046   case ISD::SINT_TO_FP:
6047   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6048   case ISD::FP_TO_SINT:
6049   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6050   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6051   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6052   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6053   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6054   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6055   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6056   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6057                                                                Subtarget);
6058   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6059   case ISD::SHL:
6060   case ISD::SRL:
6061   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6062   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6063   case ISD::SRL_PARTS:
6064   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6065   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6066   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6067   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6068   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6069   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6070   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6071   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6072   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6073   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6074   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6075   case ISD::MUL:           return LowerMUL(Op, DAG);
6076   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6077   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6078   case ISD::ADDC:
6079   case ISD::ADDE:
6080   case ISD::SUBC:
6081   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6082   case ISD::ATOMIC_LOAD:
6083   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6084   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6085   case ISD::SDIVREM:
6086   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6087   }
6088 }
6089
6090 /// ReplaceNodeResults - Replace the results of node with an illegal result
6091 /// type with new values built out of custom code.
6092 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6093                                            SmallVectorImpl<SDValue>&Results,
6094                                            SelectionDAG &DAG) const {
6095   SDValue Res;
6096   switch (N->getOpcode()) {
6097   default:
6098     llvm_unreachable("Don't know how to custom expand this!");
6099   case ISD::BITCAST:
6100     Res = ExpandBITCAST(N, DAG);
6101     break;
6102   case ISD::SRL:
6103   case ISD::SRA:
6104     Res = Expand64BitShift(N, DAG, Subtarget);
6105     break;
6106   case ISD::READCYCLECOUNTER:
6107     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6108     return;
6109   }
6110   if (Res.getNode())
6111     Results.push_back(Res);
6112 }
6113
6114 //===----------------------------------------------------------------------===//
6115 //                           ARM Scheduler Hooks
6116 //===----------------------------------------------------------------------===//
6117
6118 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6119 /// registers the function context.
6120 void ARMTargetLowering::
6121 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6122                        MachineBasicBlock *DispatchBB, int FI) const {
6123   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6124   DebugLoc dl = MI->getDebugLoc();
6125   MachineFunction *MF = MBB->getParent();
6126   MachineRegisterInfo *MRI = &MF->getRegInfo();
6127   MachineConstantPool *MCP = MF->getConstantPool();
6128   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6129   const Function *F = MF->getFunction();
6130
6131   bool isThumb = Subtarget->isThumb();
6132   bool isThumb2 = Subtarget->isThumb2();
6133
6134   unsigned PCLabelId = AFI->createPICLabelUId();
6135   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6136   ARMConstantPoolValue *CPV =
6137     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6138   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6139
6140   const TargetRegisterClass *TRC = isThumb ?
6141     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6142     (const TargetRegisterClass*)&ARM::GPRRegClass;
6143
6144   // Grab constant pool and fixed stack memory operands.
6145   MachineMemOperand *CPMMO =
6146     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6147                              MachineMemOperand::MOLoad, 4, 4);
6148
6149   MachineMemOperand *FIMMOSt =
6150     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6151                              MachineMemOperand::MOStore, 4, 4);
6152
6153   // Load the address of the dispatch MBB into the jump buffer.
6154   if (isThumb2) {
6155     // Incoming value: jbuf
6156     //   ldr.n  r5, LCPI1_1
6157     //   orr    r5, r5, #1
6158     //   add    r5, pc
6159     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6160     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6161     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6162                    .addConstantPoolIndex(CPI)
6163                    .addMemOperand(CPMMO));
6164     // Set the low bit because of thumb mode.
6165     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6166     AddDefaultCC(
6167       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6168                      .addReg(NewVReg1, RegState::Kill)
6169                      .addImm(0x01)));
6170     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6171     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6172       .addReg(NewVReg2, RegState::Kill)
6173       .addImm(PCLabelId);
6174     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6175                    .addReg(NewVReg3, RegState::Kill)
6176                    .addFrameIndex(FI)
6177                    .addImm(36)  // &jbuf[1] :: pc
6178                    .addMemOperand(FIMMOSt));
6179   } else if (isThumb) {
6180     // Incoming value: jbuf
6181     //   ldr.n  r1, LCPI1_4
6182     //   add    r1, pc
6183     //   mov    r2, #1
6184     //   orrs   r1, r2
6185     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6186     //   str    r1, [r2]
6187     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6188     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6189                    .addConstantPoolIndex(CPI)
6190                    .addMemOperand(CPMMO));
6191     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6192     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6193       .addReg(NewVReg1, RegState::Kill)
6194       .addImm(PCLabelId);
6195     // Set the low bit because of thumb mode.
6196     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6197     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6198                    .addReg(ARM::CPSR, RegState::Define)
6199                    .addImm(1));
6200     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6201     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6202                    .addReg(ARM::CPSR, RegState::Define)
6203                    .addReg(NewVReg2, RegState::Kill)
6204                    .addReg(NewVReg3, RegState::Kill));
6205     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6206     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6207                    .addFrameIndex(FI)
6208                    .addImm(36)); // &jbuf[1] :: pc
6209     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6210                    .addReg(NewVReg4, RegState::Kill)
6211                    .addReg(NewVReg5, RegState::Kill)
6212                    .addImm(0)
6213                    .addMemOperand(FIMMOSt));
6214   } else {
6215     // Incoming value: jbuf
6216     //   ldr  r1, LCPI1_1
6217     //   add  r1, pc, r1
6218     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6219     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6220     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6221                    .addConstantPoolIndex(CPI)
6222                    .addImm(0)
6223                    .addMemOperand(CPMMO));
6224     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6225     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6226                    .addReg(NewVReg1, RegState::Kill)
6227                    .addImm(PCLabelId));
6228     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6229                    .addReg(NewVReg2, RegState::Kill)
6230                    .addFrameIndex(FI)
6231                    .addImm(36)  // &jbuf[1] :: pc
6232                    .addMemOperand(FIMMOSt));
6233   }
6234 }
6235
6236 MachineBasicBlock *ARMTargetLowering::
6237 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6238   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6239   DebugLoc dl = MI->getDebugLoc();
6240   MachineFunction *MF = MBB->getParent();
6241   MachineRegisterInfo *MRI = &MF->getRegInfo();
6242   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6243   MachineFrameInfo *MFI = MF->getFrameInfo();
6244   int FI = MFI->getFunctionContextIndex();
6245
6246   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6247     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6248     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6249
6250   // Get a mapping of the call site numbers to all of the landing pads they're
6251   // associated with.
6252   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6253   unsigned MaxCSNum = 0;
6254   MachineModuleInfo &MMI = MF->getMMI();
6255   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6256        ++BB) {
6257     if (!BB->isLandingPad()) continue;
6258
6259     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6260     // pad.
6261     for (MachineBasicBlock::iterator
6262            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6263       if (!II->isEHLabel()) continue;
6264
6265       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6266       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6267
6268       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6269       for (SmallVectorImpl<unsigned>::iterator
6270              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6271            CSI != CSE; ++CSI) {
6272         CallSiteNumToLPad[*CSI].push_back(BB);
6273         MaxCSNum = std::max(MaxCSNum, *CSI);
6274       }
6275       break;
6276     }
6277   }
6278
6279   // Get an ordered list of the machine basic blocks for the jump table.
6280   std::vector<MachineBasicBlock*> LPadList;
6281   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6282   LPadList.reserve(CallSiteNumToLPad.size());
6283   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6284     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6285     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6286            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6287       LPadList.push_back(*II);
6288       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6289     }
6290   }
6291
6292   assert(!LPadList.empty() &&
6293          "No landing pad destinations for the dispatch jump table!");
6294
6295   // Create the jump table and associated information.
6296   MachineJumpTableInfo *JTI =
6297     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6298   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6299   unsigned UId = AFI->createJumpTableUId();
6300   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6301
6302   // Create the MBBs for the dispatch code.
6303
6304   // Shove the dispatch's address into the return slot in the function context.
6305   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6306   DispatchBB->setIsLandingPad();
6307
6308   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6309   unsigned trap_opcode;
6310   if (Subtarget->isThumb())
6311     trap_opcode = ARM::tTRAP;
6312   else
6313     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6314
6315   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6316   DispatchBB->addSuccessor(TrapBB);
6317
6318   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6319   DispatchBB->addSuccessor(DispContBB);
6320
6321   // Insert and MBBs.
6322   MF->insert(MF->end(), DispatchBB);
6323   MF->insert(MF->end(), DispContBB);
6324   MF->insert(MF->end(), TrapBB);
6325
6326   // Insert code into the entry block that creates and registers the function
6327   // context.
6328   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6329
6330   MachineMemOperand *FIMMOLd =
6331     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6332                              MachineMemOperand::MOLoad |
6333                              MachineMemOperand::MOVolatile, 4, 4);
6334
6335   MachineInstrBuilder MIB;
6336   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6337
6338   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6339   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6340
6341   // Add a register mask with no preserved registers.  This results in all
6342   // registers being marked as clobbered.
6343   MIB.addRegMask(RI.getNoPreservedMask());
6344
6345   unsigned NumLPads = LPadList.size();
6346   if (Subtarget->isThumb2()) {
6347     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6348     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6349                    .addFrameIndex(FI)
6350                    .addImm(4)
6351                    .addMemOperand(FIMMOLd));
6352
6353     if (NumLPads < 256) {
6354       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6355                      .addReg(NewVReg1)
6356                      .addImm(LPadList.size()));
6357     } else {
6358       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6359       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6360                      .addImm(NumLPads & 0xFFFF));
6361
6362       unsigned VReg2 = VReg1;
6363       if ((NumLPads & 0xFFFF0000) != 0) {
6364         VReg2 = MRI->createVirtualRegister(TRC);
6365         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6366                        .addReg(VReg1)
6367                        .addImm(NumLPads >> 16));
6368       }
6369
6370       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6371                      .addReg(NewVReg1)
6372                      .addReg(VReg2));
6373     }
6374
6375     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6376       .addMBB(TrapBB)
6377       .addImm(ARMCC::HI)
6378       .addReg(ARM::CPSR);
6379
6380     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6381     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6382                    .addJumpTableIndex(MJTI)
6383                    .addImm(UId));
6384
6385     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6386     AddDefaultCC(
6387       AddDefaultPred(
6388         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6389         .addReg(NewVReg3, RegState::Kill)
6390         .addReg(NewVReg1)
6391         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6392
6393     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6394       .addReg(NewVReg4, RegState::Kill)
6395       .addReg(NewVReg1)
6396       .addJumpTableIndex(MJTI)
6397       .addImm(UId);
6398   } else if (Subtarget->isThumb()) {
6399     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6400     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6401                    .addFrameIndex(FI)
6402                    .addImm(1)
6403                    .addMemOperand(FIMMOLd));
6404
6405     if (NumLPads < 256) {
6406       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6407                      .addReg(NewVReg1)
6408                      .addImm(NumLPads));
6409     } else {
6410       MachineConstantPool *ConstantPool = MF->getConstantPool();
6411       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6412       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6413
6414       // MachineConstantPool wants an explicit alignment.
6415       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6416       if (Align == 0)
6417         Align = getDataLayout()->getTypeAllocSize(C->getType());
6418       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6419
6420       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6421       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6422                      .addReg(VReg1, RegState::Define)
6423                      .addConstantPoolIndex(Idx));
6424       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6425                      .addReg(NewVReg1)
6426                      .addReg(VReg1));
6427     }
6428
6429     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6430       .addMBB(TrapBB)
6431       .addImm(ARMCC::HI)
6432       .addReg(ARM::CPSR);
6433
6434     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6435     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6436                    .addReg(ARM::CPSR, RegState::Define)
6437                    .addReg(NewVReg1)
6438                    .addImm(2));
6439
6440     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6441     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6442                    .addJumpTableIndex(MJTI)
6443                    .addImm(UId));
6444
6445     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6446     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6447                    .addReg(ARM::CPSR, RegState::Define)
6448                    .addReg(NewVReg2, RegState::Kill)
6449                    .addReg(NewVReg3));
6450
6451     MachineMemOperand *JTMMOLd =
6452       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6453                                MachineMemOperand::MOLoad, 4, 4);
6454
6455     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6456     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6457                    .addReg(NewVReg4, RegState::Kill)
6458                    .addImm(0)
6459                    .addMemOperand(JTMMOLd));
6460
6461     unsigned NewVReg6 = NewVReg5;
6462     if (RelocM == Reloc::PIC_) {
6463       NewVReg6 = MRI->createVirtualRegister(TRC);
6464       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6465                      .addReg(ARM::CPSR, RegState::Define)
6466                      .addReg(NewVReg5, RegState::Kill)
6467                      .addReg(NewVReg3));
6468     }
6469
6470     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6471       .addReg(NewVReg6, RegState::Kill)
6472       .addJumpTableIndex(MJTI)
6473       .addImm(UId);
6474   } else {
6475     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6476     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6477                    .addFrameIndex(FI)
6478                    .addImm(4)
6479                    .addMemOperand(FIMMOLd));
6480
6481     if (NumLPads < 256) {
6482       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6483                      .addReg(NewVReg1)
6484                      .addImm(NumLPads));
6485     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6486       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6487       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6488                      .addImm(NumLPads & 0xFFFF));
6489
6490       unsigned VReg2 = VReg1;
6491       if ((NumLPads & 0xFFFF0000) != 0) {
6492         VReg2 = MRI->createVirtualRegister(TRC);
6493         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6494                        .addReg(VReg1)
6495                        .addImm(NumLPads >> 16));
6496       }
6497
6498       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6499                      .addReg(NewVReg1)
6500                      .addReg(VReg2));
6501     } else {
6502       MachineConstantPool *ConstantPool = MF->getConstantPool();
6503       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6504       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6505
6506       // MachineConstantPool wants an explicit alignment.
6507       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6508       if (Align == 0)
6509         Align = getDataLayout()->getTypeAllocSize(C->getType());
6510       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6511
6512       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6513       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6514                      .addReg(VReg1, RegState::Define)
6515                      .addConstantPoolIndex(Idx)
6516                      .addImm(0));
6517       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6518                      .addReg(NewVReg1)
6519                      .addReg(VReg1, RegState::Kill));
6520     }
6521
6522     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6523       .addMBB(TrapBB)
6524       .addImm(ARMCC::HI)
6525       .addReg(ARM::CPSR);
6526
6527     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6528     AddDefaultCC(
6529       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6530                      .addReg(NewVReg1)
6531                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6532     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6533     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6534                    .addJumpTableIndex(MJTI)
6535                    .addImm(UId));
6536
6537     MachineMemOperand *JTMMOLd =
6538       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6539                                MachineMemOperand::MOLoad, 4, 4);
6540     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6541     AddDefaultPred(
6542       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6543       .addReg(NewVReg3, RegState::Kill)
6544       .addReg(NewVReg4)
6545       .addImm(0)
6546       .addMemOperand(JTMMOLd));
6547
6548     if (RelocM == Reloc::PIC_) {
6549       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6550         .addReg(NewVReg5, RegState::Kill)
6551         .addReg(NewVReg4)
6552         .addJumpTableIndex(MJTI)
6553         .addImm(UId);
6554     } else {
6555       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6556         .addReg(NewVReg5, RegState::Kill)
6557         .addJumpTableIndex(MJTI)
6558         .addImm(UId);
6559     }
6560   }
6561
6562   // Add the jump table entries as successors to the MBB.
6563   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6564   for (std::vector<MachineBasicBlock*>::iterator
6565          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6566     MachineBasicBlock *CurMBB = *I;
6567     if (SeenMBBs.insert(CurMBB))
6568       DispContBB->addSuccessor(CurMBB);
6569   }
6570
6571   // N.B. the order the invoke BBs are processed in doesn't matter here.
6572   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6573   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6574   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6575          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6576     MachineBasicBlock *BB = *I;
6577
6578     // Remove the landing pad successor from the invoke block and replace it
6579     // with the new dispatch block.
6580     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6581                                                   BB->succ_end());
6582     while (!Successors.empty()) {
6583       MachineBasicBlock *SMBB = Successors.pop_back_val();
6584       if (SMBB->isLandingPad()) {
6585         BB->removeSuccessor(SMBB);
6586         MBBLPads.push_back(SMBB);
6587       }
6588     }
6589
6590     BB->addSuccessor(DispatchBB);
6591
6592     // Find the invoke call and mark all of the callee-saved registers as
6593     // 'implicit defined' so that they're spilled. This prevents code from
6594     // moving instructions to before the EH block, where they will never be
6595     // executed.
6596     for (MachineBasicBlock::reverse_iterator
6597            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6598       if (!II->isCall()) continue;
6599
6600       DenseMap<unsigned, bool> DefRegs;
6601       for (MachineInstr::mop_iterator
6602              OI = II->operands_begin(), OE = II->operands_end();
6603            OI != OE; ++OI) {
6604         if (!OI->isReg()) continue;
6605         DefRegs[OI->getReg()] = true;
6606       }
6607
6608       MachineInstrBuilder MIB(*MF, &*II);
6609
6610       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6611         unsigned Reg = SavedRegs[i];
6612         if (Subtarget->isThumb2() &&
6613             !ARM::tGPRRegClass.contains(Reg) &&
6614             !ARM::hGPRRegClass.contains(Reg))
6615           continue;
6616         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6617           continue;
6618         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6619           continue;
6620         if (!DefRegs[Reg])
6621           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6622       }
6623
6624       break;
6625     }
6626   }
6627
6628   // Mark all former landing pads as non-landing pads. The dispatch is the only
6629   // landing pad now.
6630   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6631          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6632     (*I)->setIsLandingPad(false);
6633
6634   // The instruction is gone now.
6635   MI->eraseFromParent();
6636
6637   return MBB;
6638 }
6639
6640 static
6641 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6642   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6643        E = MBB->succ_end(); I != E; ++I)
6644     if (*I != Succ)
6645       return *I;
6646   llvm_unreachable("Expecting a BB with two successors!");
6647 }
6648
6649 /// Return the load opcode for a given load size. If load size >= 8,
6650 /// neon opcode will be returned.
6651 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6652   if (LdSize >= 8)
6653     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6654                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6655   if (IsThumb1)
6656     return LdSize == 4 ? ARM::tLDRi
6657                        : LdSize == 2 ? ARM::tLDRHi
6658                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6659   if (IsThumb2)
6660     return LdSize == 4 ? ARM::t2LDR_POST
6661                        : LdSize == 2 ? ARM::t2LDRH_POST
6662                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6663   return LdSize == 4 ? ARM::LDR_POST_IMM
6664                      : LdSize == 2 ? ARM::LDRH_POST
6665                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6666 }
6667
6668 /// Return the store opcode for a given store size. If store size >= 8,
6669 /// neon opcode will be returned.
6670 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6671   if (StSize >= 8)
6672     return StSize == 16 ? ARM::VST1q32wb_fixed
6673                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6674   if (IsThumb1)
6675     return StSize == 4 ? ARM::tSTRi
6676                        : StSize == 2 ? ARM::tSTRHi
6677                                      : StSize == 1 ? ARM::tSTRBi : 0;
6678   if (IsThumb2)
6679     return StSize == 4 ? ARM::t2STR_POST
6680                        : StSize == 2 ? ARM::t2STRH_POST
6681                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6682   return StSize == 4 ? ARM::STR_POST_IMM
6683                      : StSize == 2 ? ARM::STRH_POST
6684                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6685 }
6686
6687 /// Emit a post-increment load operation with given size. The instructions
6688 /// will be added to BB at Pos.
6689 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6690                        const TargetInstrInfo *TII, DebugLoc dl,
6691                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6692                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6693   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6694   assert(LdOpc != 0 && "Should have a load opcode");
6695   if (LdSize >= 8) {
6696     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6697                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6698                        .addImm(0));
6699   } else if (IsThumb1) {
6700     // load + update AddrIn
6701     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6702                        .addReg(AddrIn).addImm(0));
6703     MachineInstrBuilder MIB =
6704         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6705     MIB = AddDefaultT1CC(MIB);
6706     MIB.addReg(AddrIn).addImm(LdSize);
6707     AddDefaultPred(MIB);
6708   } else if (IsThumb2) {
6709     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6710                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6711                        .addImm(LdSize));
6712   } else { // arm
6713     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6714                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6715                        .addReg(0).addImm(LdSize));
6716   }
6717 }
6718
6719 /// Emit a post-increment store operation with given size. The instructions
6720 /// will be added to BB at Pos.
6721 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6722                        const TargetInstrInfo *TII, DebugLoc dl,
6723                        unsigned StSize, unsigned Data, unsigned AddrIn,
6724                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6725   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6726   assert(StOpc != 0 && "Should have a store opcode");
6727   if (StSize >= 8) {
6728     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6729                        .addReg(AddrIn).addImm(0).addReg(Data));
6730   } else if (IsThumb1) {
6731     // store + update AddrIn
6732     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6733                        .addReg(AddrIn).addImm(0));
6734     MachineInstrBuilder MIB =
6735         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6736     MIB = AddDefaultT1CC(MIB);
6737     MIB.addReg(AddrIn).addImm(StSize);
6738     AddDefaultPred(MIB);
6739   } else if (IsThumb2) {
6740     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6741                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6742   } else { // arm
6743     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6744                        .addReg(Data).addReg(AddrIn).addReg(0)
6745                        .addImm(StSize));
6746   }
6747 }
6748
6749 MachineBasicBlock *
6750 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6751                                    MachineBasicBlock *BB) const {
6752   // This pseudo instruction has 3 operands: dst, src, size
6753   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6754   // Otherwise, we will generate unrolled scalar copies.
6755   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6756   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6757   MachineFunction::iterator It = BB;
6758   ++It;
6759
6760   unsigned dest = MI->getOperand(0).getReg();
6761   unsigned src = MI->getOperand(1).getReg();
6762   unsigned SizeVal = MI->getOperand(2).getImm();
6763   unsigned Align = MI->getOperand(3).getImm();
6764   DebugLoc dl = MI->getDebugLoc();
6765
6766   MachineFunction *MF = BB->getParent();
6767   MachineRegisterInfo &MRI = MF->getRegInfo();
6768   unsigned UnitSize = 0;
6769   const TargetRegisterClass *TRC = nullptr;
6770   const TargetRegisterClass *VecTRC = nullptr;
6771
6772   bool IsThumb1 = Subtarget->isThumb1Only();
6773   bool IsThumb2 = Subtarget->isThumb2();
6774
6775   if (Align & 1) {
6776     UnitSize = 1;
6777   } else if (Align & 2) {
6778     UnitSize = 2;
6779   } else {
6780     // Check whether we can use NEON instructions.
6781     if (!MF->getFunction()->getAttributes().
6782           hasAttribute(AttributeSet::FunctionIndex,
6783                        Attribute::NoImplicitFloat) &&
6784         Subtarget->hasNEON()) {
6785       if ((Align % 16 == 0) && SizeVal >= 16)
6786         UnitSize = 16;
6787       else if ((Align % 8 == 0) && SizeVal >= 8)
6788         UnitSize = 8;
6789     }
6790     // Can't use NEON instructions.
6791     if (UnitSize == 0)
6792       UnitSize = 4;
6793   }
6794
6795   // Select the correct opcode and register class for unit size load/store
6796   bool IsNeon = UnitSize >= 8;
6797   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6798                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6799   if (IsNeon)
6800     VecTRC = UnitSize == 16
6801                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6802                  : UnitSize == 8
6803                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6804                        : nullptr;
6805
6806   unsigned BytesLeft = SizeVal % UnitSize;
6807   unsigned LoopSize = SizeVal - BytesLeft;
6808
6809   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6810     // Use LDR and STR to copy.
6811     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6812     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6813     unsigned srcIn = src;
6814     unsigned destIn = dest;
6815     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6816       unsigned srcOut = MRI.createVirtualRegister(TRC);
6817       unsigned destOut = MRI.createVirtualRegister(TRC);
6818       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6819       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6820                  IsThumb1, IsThumb2);
6821       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6822                  IsThumb1, IsThumb2);
6823       srcIn = srcOut;
6824       destIn = destOut;
6825     }
6826
6827     // Handle the leftover bytes with LDRB and STRB.
6828     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6829     // [destOut] = STRB_POST(scratch, destIn, 1)
6830     for (unsigned i = 0; i < BytesLeft; i++) {
6831       unsigned srcOut = MRI.createVirtualRegister(TRC);
6832       unsigned destOut = MRI.createVirtualRegister(TRC);
6833       unsigned scratch = MRI.createVirtualRegister(TRC);
6834       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6835                  IsThumb1, IsThumb2);
6836       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6837                  IsThumb1, IsThumb2);
6838       srcIn = srcOut;
6839       destIn = destOut;
6840     }
6841     MI->eraseFromParent();   // The instruction is gone now.
6842     return BB;
6843   }
6844
6845   // Expand the pseudo op to a loop.
6846   // thisMBB:
6847   //   ...
6848   //   movw varEnd, # --> with thumb2
6849   //   movt varEnd, #
6850   //   ldrcp varEnd, idx --> without thumb2
6851   //   fallthrough --> loopMBB
6852   // loopMBB:
6853   //   PHI varPhi, varEnd, varLoop
6854   //   PHI srcPhi, src, srcLoop
6855   //   PHI destPhi, dst, destLoop
6856   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6857   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6858   //   subs varLoop, varPhi, #UnitSize
6859   //   bne loopMBB
6860   //   fallthrough --> exitMBB
6861   // exitMBB:
6862   //   epilogue to handle left-over bytes
6863   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6864   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6865   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6866   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6867   MF->insert(It, loopMBB);
6868   MF->insert(It, exitMBB);
6869
6870   // Transfer the remainder of BB and its successor edges to exitMBB.
6871   exitMBB->splice(exitMBB->begin(), BB,
6872                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6873   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6874
6875   // Load an immediate to varEnd.
6876   unsigned varEnd = MRI.createVirtualRegister(TRC);
6877   if (IsThumb2) {
6878     unsigned Vtmp = varEnd;
6879     if ((LoopSize & 0xFFFF0000) != 0)
6880       Vtmp = MRI.createVirtualRegister(TRC);
6881     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
6882                        .addImm(LoopSize & 0xFFFF));
6883
6884     if ((LoopSize & 0xFFFF0000) != 0)
6885       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6886                          .addReg(Vtmp).addImm(LoopSize >> 16));
6887   } else {
6888     MachineConstantPool *ConstantPool = MF->getConstantPool();
6889     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6890     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6891
6892     // MachineConstantPool wants an explicit alignment.
6893     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6894     if (Align == 0)
6895       Align = getDataLayout()->getTypeAllocSize(C->getType());
6896     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6897
6898     if (IsThumb1)
6899       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
6900           varEnd, RegState::Define).addConstantPoolIndex(Idx));
6901     else
6902       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
6903           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
6904   }
6905   BB->addSuccessor(loopMBB);
6906
6907   // Generate the loop body:
6908   //   varPhi = PHI(varLoop, varEnd)
6909   //   srcPhi = PHI(srcLoop, src)
6910   //   destPhi = PHI(destLoop, dst)
6911   MachineBasicBlock *entryBB = BB;
6912   BB = loopMBB;
6913   unsigned varLoop = MRI.createVirtualRegister(TRC);
6914   unsigned varPhi = MRI.createVirtualRegister(TRC);
6915   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6916   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6917   unsigned destLoop = MRI.createVirtualRegister(TRC);
6918   unsigned destPhi = MRI.createVirtualRegister(TRC);
6919
6920   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6921     .addReg(varLoop).addMBB(loopMBB)
6922     .addReg(varEnd).addMBB(entryBB);
6923   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6924     .addReg(srcLoop).addMBB(loopMBB)
6925     .addReg(src).addMBB(entryBB);
6926   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6927     .addReg(destLoop).addMBB(loopMBB)
6928     .addReg(dest).addMBB(entryBB);
6929
6930   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6931   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6932   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6933   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
6934              IsThumb1, IsThumb2);
6935   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
6936              IsThumb1, IsThumb2);
6937
6938   // Decrement loop variable by UnitSize.
6939   if (IsThumb1) {
6940     MachineInstrBuilder MIB =
6941         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
6942     MIB = AddDefaultT1CC(MIB);
6943     MIB.addReg(varPhi).addImm(UnitSize);
6944     AddDefaultPred(MIB);
6945   } else {
6946     MachineInstrBuilder MIB =
6947         BuildMI(*BB, BB->end(), dl,
6948                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6949     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6950     MIB->getOperand(5).setReg(ARM::CPSR);
6951     MIB->getOperand(5).setIsDef(true);
6952   }
6953   BuildMI(*BB, BB->end(), dl,
6954           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
6955       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6956
6957   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6958   BB->addSuccessor(loopMBB);
6959   BB->addSuccessor(exitMBB);
6960
6961   // Add epilogue to handle BytesLeft.
6962   BB = exitMBB;
6963   MachineInstr *StartOfExit = exitMBB->begin();
6964
6965   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6966   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6967   unsigned srcIn = srcLoop;
6968   unsigned destIn = destLoop;
6969   for (unsigned i = 0; i < BytesLeft; i++) {
6970     unsigned srcOut = MRI.createVirtualRegister(TRC);
6971     unsigned destOut = MRI.createVirtualRegister(TRC);
6972     unsigned scratch = MRI.createVirtualRegister(TRC);
6973     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
6974                IsThumb1, IsThumb2);
6975     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
6976                IsThumb1, IsThumb2);
6977     srcIn = srcOut;
6978     destIn = destOut;
6979   }
6980
6981   MI->eraseFromParent();   // The instruction is gone now.
6982   return BB;
6983 }
6984
6985 MachineBasicBlock *
6986 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6987                                                MachineBasicBlock *BB) const {
6988   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6989   DebugLoc dl = MI->getDebugLoc();
6990   bool isThumb2 = Subtarget->isThumb2();
6991   switch (MI->getOpcode()) {
6992   default: {
6993     MI->dump();
6994     llvm_unreachable("Unexpected instr type to insert");
6995   }
6996   // The Thumb2 pre-indexed stores have the same MI operands, they just
6997   // define them differently in the .td files from the isel patterns, so
6998   // they need pseudos.
6999   case ARM::t2STR_preidx:
7000     MI->setDesc(TII->get(ARM::t2STR_PRE));
7001     return BB;
7002   case ARM::t2STRB_preidx:
7003     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7004     return BB;
7005   case ARM::t2STRH_preidx:
7006     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7007     return BB;
7008
7009   case ARM::STRi_preidx:
7010   case ARM::STRBi_preidx: {
7011     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7012       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7013     // Decode the offset.
7014     unsigned Offset = MI->getOperand(4).getImm();
7015     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7016     Offset = ARM_AM::getAM2Offset(Offset);
7017     if (isSub)
7018       Offset = -Offset;
7019
7020     MachineMemOperand *MMO = *MI->memoperands_begin();
7021     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7022       .addOperand(MI->getOperand(0))  // Rn_wb
7023       .addOperand(MI->getOperand(1))  // Rt
7024       .addOperand(MI->getOperand(2))  // Rn
7025       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7026       .addOperand(MI->getOperand(5))  // pred
7027       .addOperand(MI->getOperand(6))
7028       .addMemOperand(MMO);
7029     MI->eraseFromParent();
7030     return BB;
7031   }
7032   case ARM::STRr_preidx:
7033   case ARM::STRBr_preidx:
7034   case ARM::STRH_preidx: {
7035     unsigned NewOpc;
7036     switch (MI->getOpcode()) {
7037     default: llvm_unreachable("unexpected opcode!");
7038     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7039     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7040     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7041     }
7042     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7043     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7044       MIB.addOperand(MI->getOperand(i));
7045     MI->eraseFromParent();
7046     return BB;
7047   }
7048
7049   case ARM::tMOVCCr_pseudo: {
7050     // To "insert" a SELECT_CC instruction, we actually have to insert the
7051     // diamond control-flow pattern.  The incoming instruction knows the
7052     // destination vreg to set, the condition code register to branch on, the
7053     // true/false values to select between, and a branch opcode to use.
7054     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7055     MachineFunction::iterator It = BB;
7056     ++It;
7057
7058     //  thisMBB:
7059     //  ...
7060     //   TrueVal = ...
7061     //   cmpTY ccX, r1, r2
7062     //   bCC copy1MBB
7063     //   fallthrough --> copy0MBB
7064     MachineBasicBlock *thisMBB  = BB;
7065     MachineFunction *F = BB->getParent();
7066     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7067     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7068     F->insert(It, copy0MBB);
7069     F->insert(It, sinkMBB);
7070
7071     // Transfer the remainder of BB and its successor edges to sinkMBB.
7072     sinkMBB->splice(sinkMBB->begin(), BB,
7073                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7074     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7075
7076     BB->addSuccessor(copy0MBB);
7077     BB->addSuccessor(sinkMBB);
7078
7079     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7080       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7081
7082     //  copy0MBB:
7083     //   %FalseValue = ...
7084     //   # fallthrough to sinkMBB
7085     BB = copy0MBB;
7086
7087     // Update machine-CFG edges
7088     BB->addSuccessor(sinkMBB);
7089
7090     //  sinkMBB:
7091     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7092     //  ...
7093     BB = sinkMBB;
7094     BuildMI(*BB, BB->begin(), dl,
7095             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7096       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7097       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7098
7099     MI->eraseFromParent();   // The pseudo instruction is gone now.
7100     return BB;
7101   }
7102
7103   case ARM::BCCi64:
7104   case ARM::BCCZi64: {
7105     // If there is an unconditional branch to the other successor, remove it.
7106     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7107
7108     // Compare both parts that make up the double comparison separately for
7109     // equality.
7110     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7111
7112     unsigned LHS1 = MI->getOperand(1).getReg();
7113     unsigned LHS2 = MI->getOperand(2).getReg();
7114     if (RHSisZero) {
7115       AddDefaultPred(BuildMI(BB, dl,
7116                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7117                      .addReg(LHS1).addImm(0));
7118       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7119         .addReg(LHS2).addImm(0)
7120         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7121     } else {
7122       unsigned RHS1 = MI->getOperand(3).getReg();
7123       unsigned RHS2 = MI->getOperand(4).getReg();
7124       AddDefaultPred(BuildMI(BB, dl,
7125                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7126                      .addReg(LHS1).addReg(RHS1));
7127       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7128         .addReg(LHS2).addReg(RHS2)
7129         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7130     }
7131
7132     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7133     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7134     if (MI->getOperand(0).getImm() == ARMCC::NE)
7135       std::swap(destMBB, exitMBB);
7136
7137     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7138       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7139     if (isThumb2)
7140       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7141     else
7142       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7143
7144     MI->eraseFromParent();   // The pseudo instruction is gone now.
7145     return BB;
7146   }
7147
7148   case ARM::Int_eh_sjlj_setjmp:
7149   case ARM::Int_eh_sjlj_setjmp_nofp:
7150   case ARM::tInt_eh_sjlj_setjmp:
7151   case ARM::t2Int_eh_sjlj_setjmp:
7152   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7153     EmitSjLjDispatchBlock(MI, BB);
7154     return BB;
7155
7156   case ARM::ABS:
7157   case ARM::t2ABS: {
7158     // To insert an ABS instruction, we have to insert the
7159     // diamond control-flow pattern.  The incoming instruction knows the
7160     // source vreg to test against 0, the destination vreg to set,
7161     // the condition code register to branch on, the
7162     // true/false values to select between, and a branch opcode to use.
7163     // It transforms
7164     //     V1 = ABS V0
7165     // into
7166     //     V2 = MOVS V0
7167     //     BCC                      (branch to SinkBB if V0 >= 0)
7168     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7169     //     SinkBB: V1 = PHI(V2, V3)
7170     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7171     MachineFunction::iterator BBI = BB;
7172     ++BBI;
7173     MachineFunction *Fn = BB->getParent();
7174     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7175     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7176     Fn->insert(BBI, RSBBB);
7177     Fn->insert(BBI, SinkBB);
7178
7179     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7180     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7181     bool isThumb2 = Subtarget->isThumb2();
7182     MachineRegisterInfo &MRI = Fn->getRegInfo();
7183     // In Thumb mode S must not be specified if source register is the SP or
7184     // PC and if destination register is the SP, so restrict register class
7185     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7186       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7187       (const TargetRegisterClass*)&ARM::GPRRegClass);
7188
7189     // Transfer the remainder of BB and its successor edges to sinkMBB.
7190     SinkBB->splice(SinkBB->begin(), BB,
7191                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7192     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7193
7194     BB->addSuccessor(RSBBB);
7195     BB->addSuccessor(SinkBB);
7196
7197     // fall through to SinkMBB
7198     RSBBB->addSuccessor(SinkBB);
7199
7200     // insert a cmp at the end of BB
7201     AddDefaultPred(BuildMI(BB, dl,
7202                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7203                    .addReg(ABSSrcReg).addImm(0));
7204
7205     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7206     BuildMI(BB, dl,
7207       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7208       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7209
7210     // insert rsbri in RSBBB
7211     // Note: BCC and rsbri will be converted into predicated rsbmi
7212     // by if-conversion pass
7213     BuildMI(*RSBBB, RSBBB->begin(), dl,
7214       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7215       .addReg(ABSSrcReg, RegState::Kill)
7216       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7217
7218     // insert PHI in SinkBB,
7219     // reuse ABSDstReg to not change uses of ABS instruction
7220     BuildMI(*SinkBB, SinkBB->begin(), dl,
7221       TII->get(ARM::PHI), ABSDstReg)
7222       .addReg(NewRsbDstReg).addMBB(RSBBB)
7223       .addReg(ABSSrcReg).addMBB(BB);
7224
7225     // remove ABS instruction
7226     MI->eraseFromParent();
7227
7228     // return last added BB
7229     return SinkBB;
7230   }
7231   case ARM::COPY_STRUCT_BYVAL_I32:
7232     ++NumLoopByVals;
7233     return EmitStructByval(MI, BB);
7234   }
7235 }
7236
7237 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7238                                                       SDNode *Node) const {
7239   if (!MI->hasPostISelHook()) {
7240     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7241            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7242     return;
7243   }
7244
7245   const MCInstrDesc *MCID = &MI->getDesc();
7246   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7247   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7248   // operand is still set to noreg. If needed, set the optional operand's
7249   // register to CPSR, and remove the redundant implicit def.
7250   //
7251   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7252
7253   // Rename pseudo opcodes.
7254   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7255   if (NewOpc) {
7256     const ARMBaseInstrInfo *TII =
7257       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7258     MCID = &TII->get(NewOpc);
7259
7260     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7261            "converted opcode should be the same except for cc_out");
7262
7263     MI->setDesc(*MCID);
7264
7265     // Add the optional cc_out operand
7266     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7267   }
7268   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7269
7270   // Any ARM instruction that sets the 's' bit should specify an optional
7271   // "cc_out" operand in the last operand position.
7272   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7273     assert(!NewOpc && "Optional cc_out operand required");
7274     return;
7275   }
7276   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7277   // since we already have an optional CPSR def.
7278   bool definesCPSR = false;
7279   bool deadCPSR = false;
7280   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7281        i != e; ++i) {
7282     const MachineOperand &MO = MI->getOperand(i);
7283     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7284       definesCPSR = true;
7285       if (MO.isDead())
7286         deadCPSR = true;
7287       MI->RemoveOperand(i);
7288       break;
7289     }
7290   }
7291   if (!definesCPSR) {
7292     assert(!NewOpc && "Optional cc_out operand required");
7293     return;
7294   }
7295   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7296   if (deadCPSR) {
7297     assert(!MI->getOperand(ccOutIdx).getReg() &&
7298            "expect uninitialized optional cc_out operand");
7299     return;
7300   }
7301
7302   // If this instruction was defined with an optional CPSR def and its dag node
7303   // had a live implicit CPSR def, then activate the optional CPSR def.
7304   MachineOperand &MO = MI->getOperand(ccOutIdx);
7305   MO.setReg(ARM::CPSR);
7306   MO.setIsDef(true);
7307 }
7308
7309 //===----------------------------------------------------------------------===//
7310 //                           ARM Optimization Hooks
7311 //===----------------------------------------------------------------------===//
7312
7313 // Helper function that checks if N is a null or all ones constant.
7314 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7315   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7316   if (!C)
7317     return false;
7318   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7319 }
7320
7321 // Return true if N is conditionally 0 or all ones.
7322 // Detects these expressions where cc is an i1 value:
7323 //
7324 //   (select cc 0, y)   [AllOnes=0]
7325 //   (select cc y, 0)   [AllOnes=0]
7326 //   (zext cc)          [AllOnes=0]
7327 //   (sext cc)          [AllOnes=0/1]
7328 //   (select cc -1, y)  [AllOnes=1]
7329 //   (select cc y, -1)  [AllOnes=1]
7330 //
7331 // Invert is set when N is the null/all ones constant when CC is false.
7332 // OtherOp is set to the alternative value of N.
7333 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7334                                        SDValue &CC, bool &Invert,
7335                                        SDValue &OtherOp,
7336                                        SelectionDAG &DAG) {
7337   switch (N->getOpcode()) {
7338   default: return false;
7339   case ISD::SELECT: {
7340     CC = N->getOperand(0);
7341     SDValue N1 = N->getOperand(1);
7342     SDValue N2 = N->getOperand(2);
7343     if (isZeroOrAllOnes(N1, AllOnes)) {
7344       Invert = false;
7345       OtherOp = N2;
7346       return true;
7347     }
7348     if (isZeroOrAllOnes(N2, AllOnes)) {
7349       Invert = true;
7350       OtherOp = N1;
7351       return true;
7352     }
7353     return false;
7354   }
7355   case ISD::ZERO_EXTEND:
7356     // (zext cc) can never be the all ones value.
7357     if (AllOnes)
7358       return false;
7359     // Fall through.
7360   case ISD::SIGN_EXTEND: {
7361     EVT VT = N->getValueType(0);
7362     CC = N->getOperand(0);
7363     if (CC.getValueType() != MVT::i1)
7364       return false;
7365     Invert = !AllOnes;
7366     if (AllOnes)
7367       // When looking for an AllOnes constant, N is an sext, and the 'other'
7368       // value is 0.
7369       OtherOp = DAG.getConstant(0, VT);
7370     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7371       // When looking for a 0 constant, N can be zext or sext.
7372       OtherOp = DAG.getConstant(1, VT);
7373     else
7374       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7375     return true;
7376   }
7377   }
7378 }
7379
7380 // Combine a constant select operand into its use:
7381 //
7382 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7383 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7384 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7385 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7386 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7387 //
7388 // The transform is rejected if the select doesn't have a constant operand that
7389 // is null, or all ones when AllOnes is set.
7390 //
7391 // Also recognize sext/zext from i1:
7392 //
7393 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7394 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7395 //
7396 // These transformations eventually create predicated instructions.
7397 //
7398 // @param N       The node to transform.
7399 // @param Slct    The N operand that is a select.
7400 // @param OtherOp The other N operand (x above).
7401 // @param DCI     Context.
7402 // @param AllOnes Require the select constant to be all ones instead of null.
7403 // @returns The new node, or SDValue() on failure.
7404 static
7405 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7406                             TargetLowering::DAGCombinerInfo &DCI,
7407                             bool AllOnes = false) {
7408   SelectionDAG &DAG = DCI.DAG;
7409   EVT VT = N->getValueType(0);
7410   SDValue NonConstantVal;
7411   SDValue CCOp;
7412   bool SwapSelectOps;
7413   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7414                                   NonConstantVal, DAG))
7415     return SDValue();
7416
7417   // Slct is now know to be the desired identity constant when CC is true.
7418   SDValue TrueVal = OtherOp;
7419   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7420                                  OtherOp, NonConstantVal);
7421   // Unless SwapSelectOps says CC should be false.
7422   if (SwapSelectOps)
7423     std::swap(TrueVal, FalseVal);
7424
7425   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7426                      CCOp, TrueVal, FalseVal);
7427 }
7428
7429 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7430 static
7431 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7432                                        TargetLowering::DAGCombinerInfo &DCI) {
7433   SDValue N0 = N->getOperand(0);
7434   SDValue N1 = N->getOperand(1);
7435   if (N0.getNode()->hasOneUse()) {
7436     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7437     if (Result.getNode())
7438       return Result;
7439   }
7440   if (N1.getNode()->hasOneUse()) {
7441     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7442     if (Result.getNode())
7443       return Result;
7444   }
7445   return SDValue();
7446 }
7447
7448 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7449 // (only after legalization).
7450 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7451                                  TargetLowering::DAGCombinerInfo &DCI,
7452                                  const ARMSubtarget *Subtarget) {
7453
7454   // Only perform optimization if after legalize, and if NEON is available. We
7455   // also expected both operands to be BUILD_VECTORs.
7456   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7457       || N0.getOpcode() != ISD::BUILD_VECTOR
7458       || N1.getOpcode() != ISD::BUILD_VECTOR)
7459     return SDValue();
7460
7461   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7462   EVT VT = N->getValueType(0);
7463   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7464     return SDValue();
7465
7466   // Check that the vector operands are of the right form.
7467   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7468   // operands, where N is the size of the formed vector.
7469   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7470   // index such that we have a pair wise add pattern.
7471
7472   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7473   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7474     return SDValue();
7475   SDValue Vec = N0->getOperand(0)->getOperand(0);
7476   SDNode *V = Vec.getNode();
7477   unsigned nextIndex = 0;
7478
7479   // For each operands to the ADD which are BUILD_VECTORs,
7480   // check to see if each of their operands are an EXTRACT_VECTOR with
7481   // the same vector and appropriate index.
7482   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7483     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7484         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7485
7486       SDValue ExtVec0 = N0->getOperand(i);
7487       SDValue ExtVec1 = N1->getOperand(i);
7488
7489       // First operand is the vector, verify its the same.
7490       if (V != ExtVec0->getOperand(0).getNode() ||
7491           V != ExtVec1->getOperand(0).getNode())
7492         return SDValue();
7493
7494       // Second is the constant, verify its correct.
7495       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7496       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7497
7498       // For the constant, we want to see all the even or all the odd.
7499       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7500           || C1->getZExtValue() != nextIndex+1)
7501         return SDValue();
7502
7503       // Increment index.
7504       nextIndex+=2;
7505     } else
7506       return SDValue();
7507   }
7508
7509   // Create VPADDL node.
7510   SelectionDAG &DAG = DCI.DAG;
7511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7512
7513   // Build operand list.
7514   SmallVector<SDValue, 8> Ops;
7515   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7516                                 TLI.getPointerTy()));
7517
7518   // Input is the vector.
7519   Ops.push_back(Vec);
7520
7521   // Get widened type and narrowed type.
7522   MVT widenType;
7523   unsigned numElem = VT.getVectorNumElements();
7524   
7525   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7526   switch (inputLaneType.getSimpleVT().SimpleTy) {
7527     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7528     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7529     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7530     default:
7531       llvm_unreachable("Invalid vector element type for padd optimization.");
7532   }
7533
7534   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7535                             widenType, &Ops[0], Ops.size());
7536   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7537   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7538 }
7539
7540 static SDValue findMUL_LOHI(SDValue V) {
7541   if (V->getOpcode() == ISD::UMUL_LOHI ||
7542       V->getOpcode() == ISD::SMUL_LOHI)
7543     return V;
7544   return SDValue();
7545 }
7546
7547 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7548                                      TargetLowering::DAGCombinerInfo &DCI,
7549                                      const ARMSubtarget *Subtarget) {
7550
7551   if (Subtarget->isThumb1Only()) return SDValue();
7552
7553   // Only perform the checks after legalize when the pattern is available.
7554   if (DCI.isBeforeLegalize()) return SDValue();
7555
7556   // Look for multiply add opportunities.
7557   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7558   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7559   // a glue link from the first add to the second add.
7560   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7561   // a S/UMLAL instruction.
7562   //          loAdd   UMUL_LOHI
7563   //            \    / :lo    \ :hi
7564   //             \  /          \          [no multiline comment]
7565   //              ADDC         |  hiAdd
7566   //                 \ :glue  /  /
7567   //                  \      /  /
7568   //                    ADDE
7569   //
7570   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7571   SDValue AddcOp0 = AddcNode->getOperand(0);
7572   SDValue AddcOp1 = AddcNode->getOperand(1);
7573
7574   // Check if the two operands are from the same mul_lohi node.
7575   if (AddcOp0.getNode() == AddcOp1.getNode())
7576     return SDValue();
7577
7578   assert(AddcNode->getNumValues() == 2 &&
7579          AddcNode->getValueType(0) == MVT::i32 &&
7580          "Expect ADDC with two result values. First: i32");
7581
7582   // Check that we have a glued ADDC node.
7583   if (AddcNode->getValueType(1) != MVT::Glue)
7584     return SDValue();
7585
7586   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7587   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7588       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7589       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7590       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7591     return SDValue();
7592
7593   // Look for the glued ADDE.
7594   SDNode* AddeNode = AddcNode->getGluedUser();
7595   if (!AddeNode)
7596     return SDValue();
7597
7598   // Make sure it is really an ADDE.
7599   if (AddeNode->getOpcode() != ISD::ADDE)
7600     return SDValue();
7601
7602   assert(AddeNode->getNumOperands() == 3 &&
7603          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7604          "ADDE node has the wrong inputs");
7605
7606   // Check for the triangle shape.
7607   SDValue AddeOp0 = AddeNode->getOperand(0);
7608   SDValue AddeOp1 = AddeNode->getOperand(1);
7609
7610   // Make sure that the ADDE operands are not coming from the same node.
7611   if (AddeOp0.getNode() == AddeOp1.getNode())
7612     return SDValue();
7613
7614   // Find the MUL_LOHI node walking up ADDE's operands.
7615   bool IsLeftOperandMUL = false;
7616   SDValue MULOp = findMUL_LOHI(AddeOp0);
7617   if (MULOp == SDValue())
7618    MULOp = findMUL_LOHI(AddeOp1);
7619   else
7620     IsLeftOperandMUL = true;
7621   if (MULOp == SDValue())
7622      return SDValue();
7623
7624   // Figure out the right opcode.
7625   unsigned Opc = MULOp->getOpcode();
7626   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7627
7628   // Figure out the high and low input values to the MLAL node.
7629   SDValue* HiMul = &MULOp;
7630   SDValue* HiAdd = nullptr;
7631   SDValue* LoMul = nullptr;
7632   SDValue* LowAdd = nullptr;
7633
7634   if (IsLeftOperandMUL)
7635     HiAdd = &AddeOp1;
7636   else
7637     HiAdd = &AddeOp0;
7638
7639
7640   if (AddcOp0->getOpcode() == Opc) {
7641     LoMul = &AddcOp0;
7642     LowAdd = &AddcOp1;
7643   }
7644   if (AddcOp1->getOpcode() == Opc) {
7645     LoMul = &AddcOp1;
7646     LowAdd = &AddcOp0;
7647   }
7648
7649   if (!LoMul)
7650     return SDValue();
7651
7652   if (LoMul->getNode() != HiMul->getNode())
7653     return SDValue();
7654
7655   // Create the merged node.
7656   SelectionDAG &DAG = DCI.DAG;
7657
7658   // Build operand list.
7659   SmallVector<SDValue, 8> Ops;
7660   Ops.push_back(LoMul->getOperand(0));
7661   Ops.push_back(LoMul->getOperand(1));
7662   Ops.push_back(*LowAdd);
7663   Ops.push_back(*HiAdd);
7664
7665   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7666                                  DAG.getVTList(MVT::i32, MVT::i32),
7667                                  &Ops[0], Ops.size());
7668
7669   // Replace the ADDs' nodes uses by the MLA node's values.
7670   SDValue HiMLALResult(MLALNode.getNode(), 1);
7671   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7672
7673   SDValue LoMLALResult(MLALNode.getNode(), 0);
7674   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7675
7676   // Return original node to notify the driver to stop replacing.
7677   SDValue resNode(AddcNode, 0);
7678   return resNode;
7679 }
7680
7681 /// PerformADDCCombine - Target-specific dag combine transform from
7682 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7683 static SDValue PerformADDCCombine(SDNode *N,
7684                                  TargetLowering::DAGCombinerInfo &DCI,
7685                                  const ARMSubtarget *Subtarget) {
7686
7687   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7688
7689 }
7690
7691 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7692 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7693 /// called with the default operands, and if that fails, with commuted
7694 /// operands.
7695 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7696                                           TargetLowering::DAGCombinerInfo &DCI,
7697                                           const ARMSubtarget *Subtarget){
7698
7699   // Attempt to create vpaddl for this add.
7700   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7701   if (Result.getNode())
7702     return Result;
7703
7704   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7705   if (N0.getNode()->hasOneUse()) {
7706     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7707     if (Result.getNode()) return Result;
7708   }
7709   return SDValue();
7710 }
7711
7712 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7713 ///
7714 static SDValue PerformADDCombine(SDNode *N,
7715                                  TargetLowering::DAGCombinerInfo &DCI,
7716                                  const ARMSubtarget *Subtarget) {
7717   SDValue N0 = N->getOperand(0);
7718   SDValue N1 = N->getOperand(1);
7719
7720   // First try with the default operand order.
7721   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7722   if (Result.getNode())
7723     return Result;
7724
7725   // If that didn't work, try again with the operands commuted.
7726   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7727 }
7728
7729 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7730 ///
7731 static SDValue PerformSUBCombine(SDNode *N,
7732                                  TargetLowering::DAGCombinerInfo &DCI) {
7733   SDValue N0 = N->getOperand(0);
7734   SDValue N1 = N->getOperand(1);
7735
7736   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7737   if (N1.getNode()->hasOneUse()) {
7738     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7739     if (Result.getNode()) return Result;
7740   }
7741
7742   return SDValue();
7743 }
7744
7745 /// PerformVMULCombine
7746 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7747 /// special multiplier accumulator forwarding.
7748 ///   vmul d3, d0, d2
7749 ///   vmla d3, d1, d2
7750 /// is faster than
7751 ///   vadd d3, d0, d1
7752 ///   vmul d3, d3, d2
7753 //  However, for (A + B) * (A + B),
7754 //    vadd d2, d0, d1
7755 //    vmul d3, d0, d2
7756 //    vmla d3, d1, d2
7757 //  is slower than
7758 //    vadd d2, d0, d1
7759 //    vmul d3, d2, d2
7760 static SDValue PerformVMULCombine(SDNode *N,
7761                                   TargetLowering::DAGCombinerInfo &DCI,
7762                                   const ARMSubtarget *Subtarget) {
7763   if (!Subtarget->hasVMLxForwarding())
7764     return SDValue();
7765
7766   SelectionDAG &DAG = DCI.DAG;
7767   SDValue N0 = N->getOperand(0);
7768   SDValue N1 = N->getOperand(1);
7769   unsigned Opcode = N0.getOpcode();
7770   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7771       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7772     Opcode = N1.getOpcode();
7773     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7774         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7775       return SDValue();
7776     std::swap(N0, N1);
7777   }
7778
7779   if (N0 == N1)
7780     return SDValue();
7781
7782   EVT VT = N->getValueType(0);
7783   SDLoc DL(N);
7784   SDValue N00 = N0->getOperand(0);
7785   SDValue N01 = N0->getOperand(1);
7786   return DAG.getNode(Opcode, DL, VT,
7787                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7788                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7789 }
7790
7791 static SDValue PerformMULCombine(SDNode *N,
7792                                  TargetLowering::DAGCombinerInfo &DCI,
7793                                  const ARMSubtarget *Subtarget) {
7794   SelectionDAG &DAG = DCI.DAG;
7795
7796   if (Subtarget->isThumb1Only())
7797     return SDValue();
7798
7799   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7800     return SDValue();
7801
7802   EVT VT = N->getValueType(0);
7803   if (VT.is64BitVector() || VT.is128BitVector())
7804     return PerformVMULCombine(N, DCI, Subtarget);
7805   if (VT != MVT::i32)
7806     return SDValue();
7807
7808   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7809   if (!C)
7810     return SDValue();
7811
7812   int64_t MulAmt = C->getSExtValue();
7813   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7814
7815   ShiftAmt = ShiftAmt & (32 - 1);
7816   SDValue V = N->getOperand(0);
7817   SDLoc DL(N);
7818
7819   SDValue Res;
7820   MulAmt >>= ShiftAmt;
7821
7822   if (MulAmt >= 0) {
7823     if (isPowerOf2_32(MulAmt - 1)) {
7824       // (mul x, 2^N + 1) => (add (shl x, N), x)
7825       Res = DAG.getNode(ISD::ADD, DL, VT,
7826                         V,
7827                         DAG.getNode(ISD::SHL, DL, VT,
7828                                     V,
7829                                     DAG.getConstant(Log2_32(MulAmt - 1),
7830                                                     MVT::i32)));
7831     } else if (isPowerOf2_32(MulAmt + 1)) {
7832       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7833       Res = DAG.getNode(ISD::SUB, DL, VT,
7834                         DAG.getNode(ISD::SHL, DL, VT,
7835                                     V,
7836                                     DAG.getConstant(Log2_32(MulAmt + 1),
7837                                                     MVT::i32)),
7838                         V);
7839     } else
7840       return SDValue();
7841   } else {
7842     uint64_t MulAmtAbs = -MulAmt;
7843     if (isPowerOf2_32(MulAmtAbs + 1)) {
7844       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7845       Res = DAG.getNode(ISD::SUB, DL, VT,
7846                         V,
7847                         DAG.getNode(ISD::SHL, DL, VT,
7848                                     V,
7849                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7850                                                     MVT::i32)));
7851     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7852       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7853       Res = DAG.getNode(ISD::ADD, DL, VT,
7854                         V,
7855                         DAG.getNode(ISD::SHL, DL, VT,
7856                                     V,
7857                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7858                                                     MVT::i32)));
7859       Res = DAG.getNode(ISD::SUB, DL, VT,
7860                         DAG.getConstant(0, MVT::i32),Res);
7861
7862     } else
7863       return SDValue();
7864   }
7865
7866   if (ShiftAmt != 0)
7867     Res = DAG.getNode(ISD::SHL, DL, VT,
7868                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7869
7870   // Do not add new nodes to DAG combiner worklist.
7871   DCI.CombineTo(N, Res, false);
7872   return SDValue();
7873 }
7874
7875 static SDValue PerformANDCombine(SDNode *N,
7876                                  TargetLowering::DAGCombinerInfo &DCI,
7877                                  const ARMSubtarget *Subtarget) {
7878
7879   // Attempt to use immediate-form VBIC
7880   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7881   SDLoc dl(N);
7882   EVT VT = N->getValueType(0);
7883   SelectionDAG &DAG = DCI.DAG;
7884
7885   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7886     return SDValue();
7887
7888   APInt SplatBits, SplatUndef;
7889   unsigned SplatBitSize;
7890   bool HasAnyUndefs;
7891   if (BVN &&
7892       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7893     if (SplatBitSize <= 64) {
7894       EVT VbicVT;
7895       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7896                                       SplatUndef.getZExtValue(), SplatBitSize,
7897                                       DAG, VbicVT, VT.is128BitVector(),
7898                                       OtherModImm);
7899       if (Val.getNode()) {
7900         SDValue Input =
7901           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7902         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7903         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7904       }
7905     }
7906   }
7907
7908   if (!Subtarget->isThumb1Only()) {
7909     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7910     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7911     if (Result.getNode())
7912       return Result;
7913   }
7914
7915   return SDValue();
7916 }
7917
7918 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7919 static SDValue PerformORCombine(SDNode *N,
7920                                 TargetLowering::DAGCombinerInfo &DCI,
7921                                 const ARMSubtarget *Subtarget) {
7922   // Attempt to use immediate-form VORR
7923   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7924   SDLoc dl(N);
7925   EVT VT = N->getValueType(0);
7926   SelectionDAG &DAG = DCI.DAG;
7927
7928   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7929     return SDValue();
7930
7931   APInt SplatBits, SplatUndef;
7932   unsigned SplatBitSize;
7933   bool HasAnyUndefs;
7934   if (BVN && Subtarget->hasNEON() &&
7935       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7936     if (SplatBitSize <= 64) {
7937       EVT VorrVT;
7938       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7939                                       SplatUndef.getZExtValue(), SplatBitSize,
7940                                       DAG, VorrVT, VT.is128BitVector(),
7941                                       OtherModImm);
7942       if (Val.getNode()) {
7943         SDValue Input =
7944           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7945         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7946         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7947       }
7948     }
7949   }
7950
7951   if (!Subtarget->isThumb1Only()) {
7952     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7953     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7954     if (Result.getNode())
7955       return Result;
7956   }
7957
7958   // The code below optimizes (or (and X, Y), Z).
7959   // The AND operand needs to have a single user to make these optimizations
7960   // profitable.
7961   SDValue N0 = N->getOperand(0);
7962   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7963     return SDValue();
7964   SDValue N1 = N->getOperand(1);
7965
7966   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7967   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7968       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7969     APInt SplatUndef;
7970     unsigned SplatBitSize;
7971     bool HasAnyUndefs;
7972
7973     APInt SplatBits0, SplatBits1;
7974     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7975     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7976     // Ensure that the second operand of both ands are constants
7977     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7978                                       HasAnyUndefs) && !HasAnyUndefs) {
7979         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7980                                           HasAnyUndefs) && !HasAnyUndefs) {
7981             // Ensure that the bit width of the constants are the same and that
7982             // the splat arguments are logical inverses as per the pattern we
7983             // are trying to simplify.
7984             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
7985                 SplatBits0 == ~SplatBits1) {
7986                 // Canonicalize the vector type to make instruction selection
7987                 // simpler.
7988                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7989                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7990                                              N0->getOperand(1),
7991                                              N0->getOperand(0),
7992                                              N1->getOperand(0));
7993                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7994             }
7995         }
7996     }
7997   }
7998
7999   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8000   // reasonable.
8001
8002   // BFI is only available on V6T2+
8003   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8004     return SDValue();
8005
8006   SDLoc DL(N);
8007   // 1) or (and A, mask), val => ARMbfi A, val, mask
8008   //      iff (val & mask) == val
8009   //
8010   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8011   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8012   //          && mask == ~mask2
8013   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8014   //          && ~mask == mask2
8015   //  (i.e., copy a bitfield value into another bitfield of the same width)
8016
8017   if (VT != MVT::i32)
8018     return SDValue();
8019
8020   SDValue N00 = N0.getOperand(0);
8021
8022   // The value and the mask need to be constants so we can verify this is
8023   // actually a bitfield set. If the mask is 0xffff, we can do better
8024   // via a movt instruction, so don't use BFI in that case.
8025   SDValue MaskOp = N0.getOperand(1);
8026   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8027   if (!MaskC)
8028     return SDValue();
8029   unsigned Mask = MaskC->getZExtValue();
8030   if (Mask == 0xffff)
8031     return SDValue();
8032   SDValue Res;
8033   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8034   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8035   if (N1C) {
8036     unsigned Val = N1C->getZExtValue();
8037     if ((Val & ~Mask) != Val)
8038       return SDValue();
8039
8040     if (ARM::isBitFieldInvertedMask(Mask)) {
8041       Val >>= countTrailingZeros(~Mask);
8042
8043       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8044                         DAG.getConstant(Val, MVT::i32),
8045                         DAG.getConstant(Mask, MVT::i32));
8046
8047       // Do not add new nodes to DAG combiner worklist.
8048       DCI.CombineTo(N, Res, false);
8049       return SDValue();
8050     }
8051   } else if (N1.getOpcode() == ISD::AND) {
8052     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8053     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8054     if (!N11C)
8055       return SDValue();
8056     unsigned Mask2 = N11C->getZExtValue();
8057
8058     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8059     // as is to match.
8060     if (ARM::isBitFieldInvertedMask(Mask) &&
8061         (Mask == ~Mask2)) {
8062       // The pack halfword instruction works better for masks that fit it,
8063       // so use that when it's available.
8064       if (Subtarget->hasT2ExtractPack() &&
8065           (Mask == 0xffff || Mask == 0xffff0000))
8066         return SDValue();
8067       // 2a
8068       unsigned amt = countTrailingZeros(Mask2);
8069       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8070                         DAG.getConstant(amt, MVT::i32));
8071       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8072                         DAG.getConstant(Mask, MVT::i32));
8073       // Do not add new nodes to DAG combiner worklist.
8074       DCI.CombineTo(N, Res, false);
8075       return SDValue();
8076     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8077                (~Mask == Mask2)) {
8078       // The pack halfword instruction works better for masks that fit it,
8079       // so use that when it's available.
8080       if (Subtarget->hasT2ExtractPack() &&
8081           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8082         return SDValue();
8083       // 2b
8084       unsigned lsb = countTrailingZeros(Mask);
8085       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8086                         DAG.getConstant(lsb, MVT::i32));
8087       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8088                         DAG.getConstant(Mask2, MVT::i32));
8089       // Do not add new nodes to DAG combiner worklist.
8090       DCI.CombineTo(N, Res, false);
8091       return SDValue();
8092     }
8093   }
8094
8095   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8096       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8097       ARM::isBitFieldInvertedMask(~Mask)) {
8098     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8099     // where lsb(mask) == #shamt and masked bits of B are known zero.
8100     SDValue ShAmt = N00.getOperand(1);
8101     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8102     unsigned LSB = countTrailingZeros(Mask);
8103     if (ShAmtC != LSB)
8104       return SDValue();
8105
8106     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8107                       DAG.getConstant(~Mask, MVT::i32));
8108
8109     // Do not add new nodes to DAG combiner worklist.
8110     DCI.CombineTo(N, Res, false);
8111   }
8112
8113   return SDValue();
8114 }
8115
8116 static SDValue PerformXORCombine(SDNode *N,
8117                                  TargetLowering::DAGCombinerInfo &DCI,
8118                                  const ARMSubtarget *Subtarget) {
8119   EVT VT = N->getValueType(0);
8120   SelectionDAG &DAG = DCI.DAG;
8121
8122   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8123     return SDValue();
8124
8125   if (!Subtarget->isThumb1Only()) {
8126     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8127     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8128     if (Result.getNode())
8129       return Result;
8130   }
8131
8132   return SDValue();
8133 }
8134
8135 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8136 /// the bits being cleared by the AND are not demanded by the BFI.
8137 static SDValue PerformBFICombine(SDNode *N,
8138                                  TargetLowering::DAGCombinerInfo &DCI) {
8139   SDValue N1 = N->getOperand(1);
8140   if (N1.getOpcode() == ISD::AND) {
8141     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8142     if (!N11C)
8143       return SDValue();
8144     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8145     unsigned LSB = countTrailingZeros(~InvMask);
8146     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8147     unsigned Mask = (1 << Width)-1;
8148     unsigned Mask2 = N11C->getZExtValue();
8149     if ((Mask & (~Mask2)) == 0)
8150       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8151                              N->getOperand(0), N1.getOperand(0),
8152                              N->getOperand(2));
8153   }
8154   return SDValue();
8155 }
8156
8157 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8158 /// ARMISD::VMOVRRD.
8159 static SDValue PerformVMOVRRDCombine(SDNode *N,
8160                                      TargetLowering::DAGCombinerInfo &DCI) {
8161   // vmovrrd(vmovdrr x, y) -> x,y
8162   SDValue InDouble = N->getOperand(0);
8163   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8164     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8165
8166   // vmovrrd(load f64) -> (load i32), (load i32)
8167   SDNode *InNode = InDouble.getNode();
8168   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8169       InNode->getValueType(0) == MVT::f64 &&
8170       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8171       !cast<LoadSDNode>(InNode)->isVolatile()) {
8172     // TODO: Should this be done for non-FrameIndex operands?
8173     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8174
8175     SelectionDAG &DAG = DCI.DAG;
8176     SDLoc DL(LD);
8177     SDValue BasePtr = LD->getBasePtr();
8178     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8179                                  LD->getPointerInfo(), LD->isVolatile(),
8180                                  LD->isNonTemporal(), LD->isInvariant(),
8181                                  LD->getAlignment());
8182
8183     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8184                                     DAG.getConstant(4, MVT::i32));
8185     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8186                                  LD->getPointerInfo(), LD->isVolatile(),
8187                                  LD->isNonTemporal(), LD->isInvariant(),
8188                                  std::min(4U, LD->getAlignment() / 2));
8189
8190     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8191     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8192     DCI.RemoveFromWorklist(LD);
8193     DAG.DeleteNode(LD);
8194     return Result;
8195   }
8196
8197   return SDValue();
8198 }
8199
8200 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8201 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8202 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8203   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8204   SDValue Op0 = N->getOperand(0);
8205   SDValue Op1 = N->getOperand(1);
8206   if (Op0.getOpcode() == ISD::BITCAST)
8207     Op0 = Op0.getOperand(0);
8208   if (Op1.getOpcode() == ISD::BITCAST)
8209     Op1 = Op1.getOperand(0);
8210   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8211       Op0.getNode() == Op1.getNode() &&
8212       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8213     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8214                        N->getValueType(0), Op0.getOperand(0));
8215   return SDValue();
8216 }
8217
8218 /// PerformSTORECombine - Target-specific dag combine xforms for
8219 /// ISD::STORE.
8220 static SDValue PerformSTORECombine(SDNode *N,
8221                                    TargetLowering::DAGCombinerInfo &DCI) {
8222   StoreSDNode *St = cast<StoreSDNode>(N);
8223   if (St->isVolatile())
8224     return SDValue();
8225
8226   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8227   // pack all of the elements in one place.  Next, store to memory in fewer
8228   // chunks.
8229   SDValue StVal = St->getValue();
8230   EVT VT = StVal.getValueType();
8231   if (St->isTruncatingStore() && VT.isVector()) {
8232     SelectionDAG &DAG = DCI.DAG;
8233     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8234     EVT StVT = St->getMemoryVT();
8235     unsigned NumElems = VT.getVectorNumElements();
8236     assert(StVT != VT && "Cannot truncate to the same type");
8237     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8238     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8239
8240     // From, To sizes and ElemCount must be pow of two
8241     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8242
8243     // We are going to use the original vector elt for storing.
8244     // Accumulated smaller vector elements must be a multiple of the store size.
8245     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8246
8247     unsigned SizeRatio  = FromEltSz / ToEltSz;
8248     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8249
8250     // Create a type on which we perform the shuffle.
8251     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8252                                      NumElems*SizeRatio);
8253     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8254
8255     SDLoc DL(St);
8256     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8257     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8258     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8259
8260     // Can't shuffle using an illegal type.
8261     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8262
8263     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8264                                 DAG.getUNDEF(WideVec.getValueType()),
8265                                 ShuffleVec.data());
8266     // At this point all of the data is stored at the bottom of the
8267     // register. We now need to save it to mem.
8268
8269     // Find the largest store unit
8270     MVT StoreType = MVT::i8;
8271     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8272          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8273       MVT Tp = (MVT::SimpleValueType)tp;
8274       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8275         StoreType = Tp;
8276     }
8277     // Didn't find a legal store type.
8278     if (!TLI.isTypeLegal(StoreType))
8279       return SDValue();
8280
8281     // Bitcast the original vector into a vector of store-size units
8282     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8283             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8284     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8285     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8286     SmallVector<SDValue, 8> Chains;
8287     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8288                                         TLI.getPointerTy());
8289     SDValue BasePtr = St->getBasePtr();
8290
8291     // Perform one or more big stores into memory.
8292     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8293     for (unsigned I = 0; I < E; I++) {
8294       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8295                                    StoreType, ShuffWide,
8296                                    DAG.getIntPtrConstant(I));
8297       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8298                                 St->getPointerInfo(), St->isVolatile(),
8299                                 St->isNonTemporal(), St->getAlignment());
8300       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8301                             Increment);
8302       Chains.push_back(Ch);
8303     }
8304     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8305                        Chains.size());
8306   }
8307
8308   if (!ISD::isNormalStore(St))
8309     return SDValue();
8310
8311   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8312   // ARM stores of arguments in the same cache line.
8313   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8314       StVal.getNode()->hasOneUse()) {
8315     SelectionDAG  &DAG = DCI.DAG;
8316     SDLoc DL(St);
8317     SDValue BasePtr = St->getBasePtr();
8318     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8319                                   StVal.getNode()->getOperand(0), BasePtr,
8320                                   St->getPointerInfo(), St->isVolatile(),
8321                                   St->isNonTemporal(), St->getAlignment());
8322
8323     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8324                                     DAG.getConstant(4, MVT::i32));
8325     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8326                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8327                         St->isNonTemporal(),
8328                         std::min(4U, St->getAlignment() / 2));
8329   }
8330
8331   if (StVal.getValueType() != MVT::i64 ||
8332       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8333     return SDValue();
8334
8335   // Bitcast an i64 store extracted from a vector to f64.
8336   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8337   SelectionDAG &DAG = DCI.DAG;
8338   SDLoc dl(StVal);
8339   SDValue IntVec = StVal.getOperand(0);
8340   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8341                                  IntVec.getValueType().getVectorNumElements());
8342   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8343   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8344                                Vec, StVal.getOperand(1));
8345   dl = SDLoc(N);
8346   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8347   // Make the DAGCombiner fold the bitcasts.
8348   DCI.AddToWorklist(Vec.getNode());
8349   DCI.AddToWorklist(ExtElt.getNode());
8350   DCI.AddToWorklist(V.getNode());
8351   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8352                       St->getPointerInfo(), St->isVolatile(),
8353                       St->isNonTemporal(), St->getAlignment(),
8354                       St->getTBAAInfo());
8355 }
8356
8357 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8358 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8359 /// i64 vector to have f64 elements, since the value can then be loaded
8360 /// directly into a VFP register.
8361 static bool hasNormalLoadOperand(SDNode *N) {
8362   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8363   for (unsigned i = 0; i < NumElts; ++i) {
8364     SDNode *Elt = N->getOperand(i).getNode();
8365     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8366       return true;
8367   }
8368   return false;
8369 }
8370
8371 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8372 /// ISD::BUILD_VECTOR.
8373 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8374                                           TargetLowering::DAGCombinerInfo &DCI){
8375   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8376   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8377   // into a pair of GPRs, which is fine when the value is used as a scalar,
8378   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8379   SelectionDAG &DAG = DCI.DAG;
8380   if (N->getNumOperands() == 2) {
8381     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8382     if (RV.getNode())
8383       return RV;
8384   }
8385
8386   // Load i64 elements as f64 values so that type legalization does not split
8387   // them up into i32 values.
8388   EVT VT = N->getValueType(0);
8389   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8390     return SDValue();
8391   SDLoc dl(N);
8392   SmallVector<SDValue, 8> Ops;
8393   unsigned NumElts = VT.getVectorNumElements();
8394   for (unsigned i = 0; i < NumElts; ++i) {
8395     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8396     Ops.push_back(V);
8397     // Make the DAGCombiner fold the bitcast.
8398     DCI.AddToWorklist(V.getNode());
8399   }
8400   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8401   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8402   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8403 }
8404
8405 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8406 static SDValue
8407 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8408   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8409   // At that time, we may have inserted bitcasts from integer to float.
8410   // If these bitcasts have survived DAGCombine, change the lowering of this
8411   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8412   // force to use floating point types.
8413
8414   // Make sure we can change the type of the vector.
8415   // This is possible iff:
8416   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8417   //    1.1. Vector is used only once.
8418   //    1.2. Use is a bit convert to an integer type.
8419   // 2. The size of its operands are 32-bits (64-bits are not legal).
8420   EVT VT = N->getValueType(0);
8421   EVT EltVT = VT.getVectorElementType();
8422
8423   // Check 1.1. and 2.
8424   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8425     return SDValue();
8426
8427   // By construction, the input type must be float.
8428   assert(EltVT == MVT::f32 && "Unexpected type!");
8429
8430   // Check 1.2.
8431   SDNode *Use = *N->use_begin();
8432   if (Use->getOpcode() != ISD::BITCAST ||
8433       Use->getValueType(0).isFloatingPoint())
8434     return SDValue();
8435
8436   // Check profitability.
8437   // Model is, if more than half of the relevant operands are bitcast from
8438   // i32, turn the build_vector into a sequence of insert_vector_elt.
8439   // Relevant operands are everything that is not statically
8440   // (i.e., at compile time) bitcasted.
8441   unsigned NumOfBitCastedElts = 0;
8442   unsigned NumElts = VT.getVectorNumElements();
8443   unsigned NumOfRelevantElts = NumElts;
8444   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8445     SDValue Elt = N->getOperand(Idx);
8446     if (Elt->getOpcode() == ISD::BITCAST) {
8447       // Assume only bit cast to i32 will go away.
8448       if (Elt->getOperand(0).getValueType() == MVT::i32)
8449         ++NumOfBitCastedElts;
8450     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8451       // Constants are statically casted, thus do not count them as
8452       // relevant operands.
8453       --NumOfRelevantElts;
8454   }
8455
8456   // Check if more than half of the elements require a non-free bitcast.
8457   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8458     return SDValue();
8459
8460   SelectionDAG &DAG = DCI.DAG;
8461   // Create the new vector type.
8462   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8463   // Check if the type is legal.
8464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8465   if (!TLI.isTypeLegal(VecVT))
8466     return SDValue();
8467
8468   // Combine:
8469   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8470   // => BITCAST INSERT_VECTOR_ELT
8471   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8472   //                      (BITCAST EN), N.
8473   SDValue Vec = DAG.getUNDEF(VecVT);
8474   SDLoc dl(N);
8475   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8476     SDValue V = N->getOperand(Idx);
8477     if (V.getOpcode() == ISD::UNDEF)
8478       continue;
8479     if (V.getOpcode() == ISD::BITCAST &&
8480         V->getOperand(0).getValueType() == MVT::i32)
8481       // Fold obvious case.
8482       V = V.getOperand(0);
8483     else {
8484       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8485       // Make the DAGCombiner fold the bitcasts.
8486       DCI.AddToWorklist(V.getNode());
8487     }
8488     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8489     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8490   }
8491   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8492   // Make the DAGCombiner fold the bitcasts.
8493   DCI.AddToWorklist(Vec.getNode());
8494   return Vec;
8495 }
8496
8497 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8498 /// ISD::INSERT_VECTOR_ELT.
8499 static SDValue PerformInsertEltCombine(SDNode *N,
8500                                        TargetLowering::DAGCombinerInfo &DCI) {
8501   // Bitcast an i64 load inserted into a vector to f64.
8502   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8503   EVT VT = N->getValueType(0);
8504   SDNode *Elt = N->getOperand(1).getNode();
8505   if (VT.getVectorElementType() != MVT::i64 ||
8506       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8507     return SDValue();
8508
8509   SelectionDAG &DAG = DCI.DAG;
8510   SDLoc dl(N);
8511   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8512                                  VT.getVectorNumElements());
8513   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8514   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8515   // Make the DAGCombiner fold the bitcasts.
8516   DCI.AddToWorklist(Vec.getNode());
8517   DCI.AddToWorklist(V.getNode());
8518   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8519                                Vec, V, N->getOperand(2));
8520   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8521 }
8522
8523 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8524 /// ISD::VECTOR_SHUFFLE.
8525 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8526   // The LLVM shufflevector instruction does not require the shuffle mask
8527   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8528   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8529   // operands do not match the mask length, they are extended by concatenating
8530   // them with undef vectors.  That is probably the right thing for other
8531   // targets, but for NEON it is better to concatenate two double-register
8532   // size vector operands into a single quad-register size vector.  Do that
8533   // transformation here:
8534   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8535   //   shuffle(concat(v1, v2), undef)
8536   SDValue Op0 = N->getOperand(0);
8537   SDValue Op1 = N->getOperand(1);
8538   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8539       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8540       Op0.getNumOperands() != 2 ||
8541       Op1.getNumOperands() != 2)
8542     return SDValue();
8543   SDValue Concat0Op1 = Op0.getOperand(1);
8544   SDValue Concat1Op1 = Op1.getOperand(1);
8545   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8546       Concat1Op1.getOpcode() != ISD::UNDEF)
8547     return SDValue();
8548   // Skip the transformation if any of the types are illegal.
8549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8550   EVT VT = N->getValueType(0);
8551   if (!TLI.isTypeLegal(VT) ||
8552       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8553       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8554     return SDValue();
8555
8556   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8557                                   Op0.getOperand(0), Op1.getOperand(0));
8558   // Translate the shuffle mask.
8559   SmallVector<int, 16> NewMask;
8560   unsigned NumElts = VT.getVectorNumElements();
8561   unsigned HalfElts = NumElts/2;
8562   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8563   for (unsigned n = 0; n < NumElts; ++n) {
8564     int MaskElt = SVN->getMaskElt(n);
8565     int NewElt = -1;
8566     if (MaskElt < (int)HalfElts)
8567       NewElt = MaskElt;
8568     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8569       NewElt = HalfElts + MaskElt - NumElts;
8570     NewMask.push_back(NewElt);
8571   }
8572   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8573                               DAG.getUNDEF(VT), NewMask.data());
8574 }
8575
8576 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8577 /// NEON load/store intrinsics to merge base address updates.
8578 static SDValue CombineBaseUpdate(SDNode *N,
8579                                  TargetLowering::DAGCombinerInfo &DCI) {
8580   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8581     return SDValue();
8582
8583   SelectionDAG &DAG = DCI.DAG;
8584   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8585                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8586   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8587   SDValue Addr = N->getOperand(AddrOpIdx);
8588
8589   // Search for a use of the address operand that is an increment.
8590   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8591          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8592     SDNode *User = *UI;
8593     if (User->getOpcode() != ISD::ADD ||
8594         UI.getUse().getResNo() != Addr.getResNo())
8595       continue;
8596
8597     // Check that the add is independent of the load/store.  Otherwise, folding
8598     // it would create a cycle.
8599     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8600       continue;
8601
8602     // Find the new opcode for the updating load/store.
8603     bool isLoad = true;
8604     bool isLaneOp = false;
8605     unsigned NewOpc = 0;
8606     unsigned NumVecs = 0;
8607     if (isIntrinsic) {
8608       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8609       switch (IntNo) {
8610       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8611       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8612         NumVecs = 1; break;
8613       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8614         NumVecs = 2; break;
8615       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8616         NumVecs = 3; break;
8617       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8618         NumVecs = 4; break;
8619       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8620         NumVecs = 2; isLaneOp = true; break;
8621       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8622         NumVecs = 3; isLaneOp = true; break;
8623       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8624         NumVecs = 4; isLaneOp = true; break;
8625       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8626         NumVecs = 1; isLoad = false; break;
8627       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8628         NumVecs = 2; isLoad = false; break;
8629       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8630         NumVecs = 3; isLoad = false; break;
8631       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8632         NumVecs = 4; isLoad = false; break;
8633       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8634         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8635       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8636         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8637       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8638         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8639       }
8640     } else {
8641       isLaneOp = true;
8642       switch (N->getOpcode()) {
8643       default: llvm_unreachable("unexpected opcode for Neon base update");
8644       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8645       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8646       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8647       }
8648     }
8649
8650     // Find the size of memory referenced by the load/store.
8651     EVT VecTy;
8652     if (isLoad)
8653       VecTy = N->getValueType(0);
8654     else
8655       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8656     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8657     if (isLaneOp)
8658       NumBytes /= VecTy.getVectorNumElements();
8659
8660     // If the increment is a constant, it must match the memory ref size.
8661     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8662     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8663       uint64_t IncVal = CInc->getZExtValue();
8664       if (IncVal != NumBytes)
8665         continue;
8666     } else if (NumBytes >= 3 * 16) {
8667       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8668       // separate instructions that make it harder to use a non-constant update.
8669       continue;
8670     }
8671
8672     // Create the new updating load/store node.
8673     EVT Tys[6];
8674     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8675     unsigned n;
8676     for (n = 0; n < NumResultVecs; ++n)
8677       Tys[n] = VecTy;
8678     Tys[n++] = MVT::i32;
8679     Tys[n] = MVT::Other;
8680     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8681     SmallVector<SDValue, 8> Ops;
8682     Ops.push_back(N->getOperand(0)); // incoming chain
8683     Ops.push_back(N->getOperand(AddrOpIdx));
8684     Ops.push_back(Inc);
8685     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8686       Ops.push_back(N->getOperand(i));
8687     }
8688     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8689     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8690                                            Ops.data(), Ops.size(),
8691                                            MemInt->getMemoryVT(),
8692                                            MemInt->getMemOperand());
8693
8694     // Update the uses.
8695     std::vector<SDValue> NewResults;
8696     for (unsigned i = 0; i < NumResultVecs; ++i) {
8697       NewResults.push_back(SDValue(UpdN.getNode(), i));
8698     }
8699     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8700     DCI.CombineTo(N, NewResults);
8701     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8702
8703     break;
8704   }
8705   return SDValue();
8706 }
8707
8708 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8709 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8710 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8711 /// return true.
8712 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8713   SelectionDAG &DAG = DCI.DAG;
8714   EVT VT = N->getValueType(0);
8715   // vldN-dup instructions only support 64-bit vectors for N > 1.
8716   if (!VT.is64BitVector())
8717     return false;
8718
8719   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8720   SDNode *VLD = N->getOperand(0).getNode();
8721   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8722     return false;
8723   unsigned NumVecs = 0;
8724   unsigned NewOpc = 0;
8725   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8726   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8727     NumVecs = 2;
8728     NewOpc = ARMISD::VLD2DUP;
8729   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8730     NumVecs = 3;
8731     NewOpc = ARMISD::VLD3DUP;
8732   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8733     NumVecs = 4;
8734     NewOpc = ARMISD::VLD4DUP;
8735   } else {
8736     return false;
8737   }
8738
8739   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8740   // numbers match the load.
8741   unsigned VLDLaneNo =
8742     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8743   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8744        UI != UE; ++UI) {
8745     // Ignore uses of the chain result.
8746     if (UI.getUse().getResNo() == NumVecs)
8747       continue;
8748     SDNode *User = *UI;
8749     if (User->getOpcode() != ARMISD::VDUPLANE ||
8750         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8751       return false;
8752   }
8753
8754   // Create the vldN-dup node.
8755   EVT Tys[5];
8756   unsigned n;
8757   for (n = 0; n < NumVecs; ++n)
8758     Tys[n] = VT;
8759   Tys[n] = MVT::Other;
8760   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8761   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8762   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8763   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8764                                            Ops, 2, VLDMemInt->getMemoryVT(),
8765                                            VLDMemInt->getMemOperand());
8766
8767   // Update the uses.
8768   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8769        UI != UE; ++UI) {
8770     unsigned ResNo = UI.getUse().getResNo();
8771     // Ignore uses of the chain result.
8772     if (ResNo == NumVecs)
8773       continue;
8774     SDNode *User = *UI;
8775     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8776   }
8777
8778   // Now the vldN-lane intrinsic is dead except for its chain result.
8779   // Update uses of the chain.
8780   std::vector<SDValue> VLDDupResults;
8781   for (unsigned n = 0; n < NumVecs; ++n)
8782     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8783   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8784   DCI.CombineTo(VLD, VLDDupResults);
8785
8786   return true;
8787 }
8788
8789 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8790 /// ARMISD::VDUPLANE.
8791 static SDValue PerformVDUPLANECombine(SDNode *N,
8792                                       TargetLowering::DAGCombinerInfo &DCI) {
8793   SDValue Op = N->getOperand(0);
8794
8795   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8796   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8797   if (CombineVLDDUP(N, DCI))
8798     return SDValue(N, 0);
8799
8800   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8801   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8802   while (Op.getOpcode() == ISD::BITCAST)
8803     Op = Op.getOperand(0);
8804   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8805     return SDValue();
8806
8807   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8808   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8809   // The canonical VMOV for a zero vector uses a 32-bit element size.
8810   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8811   unsigned EltBits;
8812   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8813     EltSize = 8;
8814   EVT VT = N->getValueType(0);
8815   if (EltSize > VT.getVectorElementType().getSizeInBits())
8816     return SDValue();
8817
8818   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8819 }
8820
8821 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8822 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8823 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8824 {
8825   integerPart cN;
8826   integerPart c0 = 0;
8827   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8828        I != E; I++) {
8829     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8830     if (!C)
8831       return false;
8832
8833     bool isExact;
8834     APFloat APF = C->getValueAPF();
8835     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8836         != APFloat::opOK || !isExact)
8837       return false;
8838
8839     c0 = (I == 0) ? cN : c0;
8840     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8841       return false;
8842   }
8843   C = c0;
8844   return true;
8845 }
8846
8847 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8848 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8849 /// when the VMUL has a constant operand that is a power of 2.
8850 ///
8851 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8852 ///  vmul.f32        d16, d17, d16
8853 ///  vcvt.s32.f32    d16, d16
8854 /// becomes:
8855 ///  vcvt.s32.f32    d16, d16, #3
8856 static SDValue PerformVCVTCombine(SDNode *N,
8857                                   TargetLowering::DAGCombinerInfo &DCI,
8858                                   const ARMSubtarget *Subtarget) {
8859   SelectionDAG &DAG = DCI.DAG;
8860   SDValue Op = N->getOperand(0);
8861
8862   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8863       Op.getOpcode() != ISD::FMUL)
8864     return SDValue();
8865
8866   uint64_t C;
8867   SDValue N0 = Op->getOperand(0);
8868   SDValue ConstVec = Op->getOperand(1);
8869   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8870
8871   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8872       !isConstVecPow2(ConstVec, isSigned, C))
8873     return SDValue();
8874
8875   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8876   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8877   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8878     // These instructions only exist converting from f32 to i32. We can handle
8879     // smaller integers by generating an extra truncate, but larger ones would
8880     // be lossy.
8881     return SDValue();
8882   }
8883
8884   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8885     Intrinsic::arm_neon_vcvtfp2fxu;
8886   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8887   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8888                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8889                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8890                                  DAG.getConstant(Log2_64(C), MVT::i32));
8891
8892   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8893     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
8894
8895   return FixConv;
8896 }
8897
8898 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8899 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8900 /// when the VDIV has a constant operand that is a power of 2.
8901 ///
8902 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8903 ///  vcvt.f32.s32    d16, d16
8904 ///  vdiv.f32        d16, d17, d16
8905 /// becomes:
8906 ///  vcvt.f32.s32    d16, d16, #3
8907 static SDValue PerformVDIVCombine(SDNode *N,
8908                                   TargetLowering::DAGCombinerInfo &DCI,
8909                                   const ARMSubtarget *Subtarget) {
8910   SelectionDAG &DAG = DCI.DAG;
8911   SDValue Op = N->getOperand(0);
8912   unsigned OpOpcode = Op.getNode()->getOpcode();
8913
8914   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8915       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8916     return SDValue();
8917
8918   uint64_t C;
8919   SDValue ConstVec = N->getOperand(1);
8920   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8921
8922   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8923       !isConstVecPow2(ConstVec, isSigned, C))
8924     return SDValue();
8925
8926   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8927   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8928   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8929     // These instructions only exist converting from i32 to f32. We can handle
8930     // smaller integers by generating an extra extend, but larger ones would
8931     // be lossy.
8932     return SDValue();
8933   }
8934
8935   SDValue ConvInput = Op.getOperand(0);
8936   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8937   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8938     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8939                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8940                             ConvInput);
8941
8942   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8943     Intrinsic::arm_neon_vcvtfxu2fp;
8944   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8945                      Op.getValueType(),
8946                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8947                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
8948 }
8949
8950 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8951 /// operand of a vector shift operation, where all the elements of the
8952 /// build_vector must have the same constant integer value.
8953 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8954   // Ignore bit_converts.
8955   while (Op.getOpcode() == ISD::BITCAST)
8956     Op = Op.getOperand(0);
8957   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8958   APInt SplatBits, SplatUndef;
8959   unsigned SplatBitSize;
8960   bool HasAnyUndefs;
8961   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8962                                       HasAnyUndefs, ElementBits) ||
8963       SplatBitSize > ElementBits)
8964     return false;
8965   Cnt = SplatBits.getSExtValue();
8966   return true;
8967 }
8968
8969 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8970 /// operand of a vector shift left operation.  That value must be in the range:
8971 ///   0 <= Value < ElementBits for a left shift; or
8972 ///   0 <= Value <= ElementBits for a long left shift.
8973 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8974   assert(VT.isVector() && "vector shift count is not a vector type");
8975   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8976   if (! getVShiftImm(Op, ElementBits, Cnt))
8977     return false;
8978   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8979 }
8980
8981 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8982 /// operand of a vector shift right operation.  For a shift opcode, the value
8983 /// is positive, but for an intrinsic the value count must be negative. The
8984 /// absolute value must be in the range:
8985 ///   1 <= |Value| <= ElementBits for a right shift; or
8986 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8987 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8988                          int64_t &Cnt) {
8989   assert(VT.isVector() && "vector shift count is not a vector type");
8990   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8991   if (! getVShiftImm(Op, ElementBits, Cnt))
8992     return false;
8993   if (isIntrinsic)
8994     Cnt = -Cnt;
8995   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8996 }
8997
8998 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8999 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9000   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9001   switch (IntNo) {
9002   default:
9003     // Don't do anything for most intrinsics.
9004     break;
9005
9006   // Vector shifts: check for immediate versions and lower them.
9007   // Note: This is done during DAG combining instead of DAG legalizing because
9008   // the build_vectors for 64-bit vector element shift counts are generally
9009   // not legal, and it is hard to see their values after they get legalized to
9010   // loads from a constant pool.
9011   case Intrinsic::arm_neon_vshifts:
9012   case Intrinsic::arm_neon_vshiftu:
9013   case Intrinsic::arm_neon_vrshifts:
9014   case Intrinsic::arm_neon_vrshiftu:
9015   case Intrinsic::arm_neon_vrshiftn:
9016   case Intrinsic::arm_neon_vqshifts:
9017   case Intrinsic::arm_neon_vqshiftu:
9018   case Intrinsic::arm_neon_vqshiftsu:
9019   case Intrinsic::arm_neon_vqshiftns:
9020   case Intrinsic::arm_neon_vqshiftnu:
9021   case Intrinsic::arm_neon_vqshiftnsu:
9022   case Intrinsic::arm_neon_vqrshiftns:
9023   case Intrinsic::arm_neon_vqrshiftnu:
9024   case Intrinsic::arm_neon_vqrshiftnsu: {
9025     EVT VT = N->getOperand(1).getValueType();
9026     int64_t Cnt;
9027     unsigned VShiftOpc = 0;
9028
9029     switch (IntNo) {
9030     case Intrinsic::arm_neon_vshifts:
9031     case Intrinsic::arm_neon_vshiftu:
9032       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9033         VShiftOpc = ARMISD::VSHL;
9034         break;
9035       }
9036       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9037         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9038                      ARMISD::VSHRs : ARMISD::VSHRu);
9039         break;
9040       }
9041       return SDValue();
9042
9043     case Intrinsic::arm_neon_vrshifts:
9044     case Intrinsic::arm_neon_vrshiftu:
9045       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9046         break;
9047       return SDValue();
9048
9049     case Intrinsic::arm_neon_vqshifts:
9050     case Intrinsic::arm_neon_vqshiftu:
9051       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9052         break;
9053       return SDValue();
9054
9055     case Intrinsic::arm_neon_vqshiftsu:
9056       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9057         break;
9058       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9059
9060     case Intrinsic::arm_neon_vrshiftn:
9061     case Intrinsic::arm_neon_vqshiftns:
9062     case Intrinsic::arm_neon_vqshiftnu:
9063     case Intrinsic::arm_neon_vqshiftnsu:
9064     case Intrinsic::arm_neon_vqrshiftns:
9065     case Intrinsic::arm_neon_vqrshiftnu:
9066     case Intrinsic::arm_neon_vqrshiftnsu:
9067       // Narrowing shifts require an immediate right shift.
9068       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9069         break;
9070       llvm_unreachable("invalid shift count for narrowing vector shift "
9071                        "intrinsic");
9072
9073     default:
9074       llvm_unreachable("unhandled vector shift");
9075     }
9076
9077     switch (IntNo) {
9078     case Intrinsic::arm_neon_vshifts:
9079     case Intrinsic::arm_neon_vshiftu:
9080       // Opcode already set above.
9081       break;
9082     case Intrinsic::arm_neon_vrshifts:
9083       VShiftOpc = ARMISD::VRSHRs; break;
9084     case Intrinsic::arm_neon_vrshiftu:
9085       VShiftOpc = ARMISD::VRSHRu; break;
9086     case Intrinsic::arm_neon_vrshiftn:
9087       VShiftOpc = ARMISD::VRSHRN; break;
9088     case Intrinsic::arm_neon_vqshifts:
9089       VShiftOpc = ARMISD::VQSHLs; break;
9090     case Intrinsic::arm_neon_vqshiftu:
9091       VShiftOpc = ARMISD::VQSHLu; break;
9092     case Intrinsic::arm_neon_vqshiftsu:
9093       VShiftOpc = ARMISD::VQSHLsu; break;
9094     case Intrinsic::arm_neon_vqshiftns:
9095       VShiftOpc = ARMISD::VQSHRNs; break;
9096     case Intrinsic::arm_neon_vqshiftnu:
9097       VShiftOpc = ARMISD::VQSHRNu; break;
9098     case Intrinsic::arm_neon_vqshiftnsu:
9099       VShiftOpc = ARMISD::VQSHRNsu; break;
9100     case Intrinsic::arm_neon_vqrshiftns:
9101       VShiftOpc = ARMISD::VQRSHRNs; break;
9102     case Intrinsic::arm_neon_vqrshiftnu:
9103       VShiftOpc = ARMISD::VQRSHRNu; break;
9104     case Intrinsic::arm_neon_vqrshiftnsu:
9105       VShiftOpc = ARMISD::VQRSHRNsu; break;
9106     }
9107
9108     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9109                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9110   }
9111
9112   case Intrinsic::arm_neon_vshiftins: {
9113     EVT VT = N->getOperand(1).getValueType();
9114     int64_t Cnt;
9115     unsigned VShiftOpc = 0;
9116
9117     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9118       VShiftOpc = ARMISD::VSLI;
9119     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9120       VShiftOpc = ARMISD::VSRI;
9121     else {
9122       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9123     }
9124
9125     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9126                        N->getOperand(1), N->getOperand(2),
9127                        DAG.getConstant(Cnt, MVT::i32));
9128   }
9129
9130   case Intrinsic::arm_neon_vqrshifts:
9131   case Intrinsic::arm_neon_vqrshiftu:
9132     // No immediate versions of these to check for.
9133     break;
9134   }
9135
9136   return SDValue();
9137 }
9138
9139 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9140 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9141 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9142 /// vector element shift counts are generally not legal, and it is hard to see
9143 /// their values after they get legalized to loads from a constant pool.
9144 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9145                                    const ARMSubtarget *ST) {
9146   EVT VT = N->getValueType(0);
9147   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9148     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9149     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9150     SDValue N1 = N->getOperand(1);
9151     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9152       SDValue N0 = N->getOperand(0);
9153       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9154           DAG.MaskedValueIsZero(N0.getOperand(0),
9155                                 APInt::getHighBitsSet(32, 16)))
9156         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9157     }
9158   }
9159
9160   // Nothing to be done for scalar shifts.
9161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9162   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9163     return SDValue();
9164
9165   assert(ST->hasNEON() && "unexpected vector shift");
9166   int64_t Cnt;
9167
9168   switch (N->getOpcode()) {
9169   default: llvm_unreachable("unexpected shift opcode");
9170
9171   case ISD::SHL:
9172     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9173       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9174                          DAG.getConstant(Cnt, MVT::i32));
9175     break;
9176
9177   case ISD::SRA:
9178   case ISD::SRL:
9179     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9180       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9181                             ARMISD::VSHRs : ARMISD::VSHRu);
9182       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9183                          DAG.getConstant(Cnt, MVT::i32));
9184     }
9185   }
9186   return SDValue();
9187 }
9188
9189 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9190 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9191 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9192                                     const ARMSubtarget *ST) {
9193   SDValue N0 = N->getOperand(0);
9194
9195   // Check for sign- and zero-extensions of vector extract operations of 8-
9196   // and 16-bit vector elements.  NEON supports these directly.  They are
9197   // handled during DAG combining because type legalization will promote them
9198   // to 32-bit types and it is messy to recognize the operations after that.
9199   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9200     SDValue Vec = N0.getOperand(0);
9201     SDValue Lane = N0.getOperand(1);
9202     EVT VT = N->getValueType(0);
9203     EVT EltVT = N0.getValueType();
9204     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9205
9206     if (VT == MVT::i32 &&
9207         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9208         TLI.isTypeLegal(Vec.getValueType()) &&
9209         isa<ConstantSDNode>(Lane)) {
9210
9211       unsigned Opc = 0;
9212       switch (N->getOpcode()) {
9213       default: llvm_unreachable("unexpected opcode");
9214       case ISD::SIGN_EXTEND:
9215         Opc = ARMISD::VGETLANEs;
9216         break;
9217       case ISD::ZERO_EXTEND:
9218       case ISD::ANY_EXTEND:
9219         Opc = ARMISD::VGETLANEu;
9220         break;
9221       }
9222       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9223     }
9224   }
9225
9226   return SDValue();
9227 }
9228
9229 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9230 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9231 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9232                                        const ARMSubtarget *ST) {
9233   // If the target supports NEON, try to use vmax/vmin instructions for f32
9234   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9235   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9236   // a NaN; only do the transformation when it matches that behavior.
9237
9238   // For now only do this when using NEON for FP operations; if using VFP, it
9239   // is not obvious that the benefit outweighs the cost of switching to the
9240   // NEON pipeline.
9241   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9242       N->getValueType(0) != MVT::f32)
9243     return SDValue();
9244
9245   SDValue CondLHS = N->getOperand(0);
9246   SDValue CondRHS = N->getOperand(1);
9247   SDValue LHS = N->getOperand(2);
9248   SDValue RHS = N->getOperand(3);
9249   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9250
9251   unsigned Opcode = 0;
9252   bool IsReversed;
9253   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9254     IsReversed = false; // x CC y ? x : y
9255   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9256     IsReversed = true ; // x CC y ? y : x
9257   } else {
9258     return SDValue();
9259   }
9260
9261   bool IsUnordered;
9262   switch (CC) {
9263   default: break;
9264   case ISD::SETOLT:
9265   case ISD::SETOLE:
9266   case ISD::SETLT:
9267   case ISD::SETLE:
9268   case ISD::SETULT:
9269   case ISD::SETULE:
9270     // If LHS is NaN, an ordered comparison will be false and the result will
9271     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9272     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9273     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9274     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9275       break;
9276     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9277     // will return -0, so vmin can only be used for unsafe math or if one of
9278     // the operands is known to be nonzero.
9279     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9280         !DAG.getTarget().Options.UnsafeFPMath &&
9281         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9282       break;
9283     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9284     break;
9285
9286   case ISD::SETOGT:
9287   case ISD::SETOGE:
9288   case ISD::SETGT:
9289   case ISD::SETGE:
9290   case ISD::SETUGT:
9291   case ISD::SETUGE:
9292     // If LHS is NaN, an ordered comparison will be false and the result will
9293     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9294     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9295     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9296     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9297       break;
9298     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9299     // will return +0, so vmax can only be used for unsafe math or if one of
9300     // the operands is known to be nonzero.
9301     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9302         !DAG.getTarget().Options.UnsafeFPMath &&
9303         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9304       break;
9305     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9306     break;
9307   }
9308
9309   if (!Opcode)
9310     return SDValue();
9311   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9312 }
9313
9314 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9315 SDValue
9316 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9317   SDValue Cmp = N->getOperand(4);
9318   if (Cmp.getOpcode() != ARMISD::CMPZ)
9319     // Only looking at EQ and NE cases.
9320     return SDValue();
9321
9322   EVT VT = N->getValueType(0);
9323   SDLoc dl(N);
9324   SDValue LHS = Cmp.getOperand(0);
9325   SDValue RHS = Cmp.getOperand(1);
9326   SDValue FalseVal = N->getOperand(0);
9327   SDValue TrueVal = N->getOperand(1);
9328   SDValue ARMcc = N->getOperand(2);
9329   ARMCC::CondCodes CC =
9330     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9331
9332   // Simplify
9333   //   mov     r1, r0
9334   //   cmp     r1, x
9335   //   mov     r0, y
9336   //   moveq   r0, x
9337   // to
9338   //   cmp     r0, x
9339   //   movne   r0, y
9340   //
9341   //   mov     r1, r0
9342   //   cmp     r1, x
9343   //   mov     r0, x
9344   //   movne   r0, y
9345   // to
9346   //   cmp     r0, x
9347   //   movne   r0, y
9348   /// FIXME: Turn this into a target neutral optimization?
9349   SDValue Res;
9350   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9351     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9352                       N->getOperand(3), Cmp);
9353   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9354     SDValue ARMcc;
9355     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9356     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9357                       N->getOperand(3), NewCmp);
9358   }
9359
9360   if (Res.getNode()) {
9361     APInt KnownZero, KnownOne;
9362     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9363     // Capture demanded bits information that would be otherwise lost.
9364     if (KnownZero == 0xfffffffe)
9365       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9366                         DAG.getValueType(MVT::i1));
9367     else if (KnownZero == 0xffffff00)
9368       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9369                         DAG.getValueType(MVT::i8));
9370     else if (KnownZero == 0xffff0000)
9371       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9372                         DAG.getValueType(MVT::i16));
9373   }
9374
9375   return Res;
9376 }
9377
9378 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9379                                              DAGCombinerInfo &DCI) const {
9380   switch (N->getOpcode()) {
9381   default: break;
9382   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9383   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9384   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9385   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9386   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9387   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9388   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9389   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9390   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9391   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9392   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9393   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9394   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9395   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9396   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9397   case ISD::FP_TO_SINT:
9398   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9399   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9400   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9401   case ISD::SHL:
9402   case ISD::SRA:
9403   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9404   case ISD::SIGN_EXTEND:
9405   case ISD::ZERO_EXTEND:
9406   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9407   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9408   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9409   case ARMISD::VLD2DUP:
9410   case ARMISD::VLD3DUP:
9411   case ARMISD::VLD4DUP:
9412     return CombineBaseUpdate(N, DCI);
9413   case ARMISD::BUILD_VECTOR:
9414     return PerformARMBUILD_VECTORCombine(N, DCI);
9415   case ISD::INTRINSIC_VOID:
9416   case ISD::INTRINSIC_W_CHAIN:
9417     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9418     case Intrinsic::arm_neon_vld1:
9419     case Intrinsic::arm_neon_vld2:
9420     case Intrinsic::arm_neon_vld3:
9421     case Intrinsic::arm_neon_vld4:
9422     case Intrinsic::arm_neon_vld2lane:
9423     case Intrinsic::arm_neon_vld3lane:
9424     case Intrinsic::arm_neon_vld4lane:
9425     case Intrinsic::arm_neon_vst1:
9426     case Intrinsic::arm_neon_vst2:
9427     case Intrinsic::arm_neon_vst3:
9428     case Intrinsic::arm_neon_vst4:
9429     case Intrinsic::arm_neon_vst2lane:
9430     case Intrinsic::arm_neon_vst3lane:
9431     case Intrinsic::arm_neon_vst4lane:
9432       return CombineBaseUpdate(N, DCI);
9433     default: break;
9434     }
9435     break;
9436   }
9437   return SDValue();
9438 }
9439
9440 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9441                                                           EVT VT) const {
9442   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9443 }
9444
9445 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9446                                                       bool *Fast) const {
9447   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9448   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9449
9450   switch (VT.getSimpleVT().SimpleTy) {
9451   default:
9452     return false;
9453   case MVT::i8:
9454   case MVT::i16:
9455   case MVT::i32: {
9456     // Unaligned access can use (for example) LRDB, LRDH, LDR
9457     if (AllowsUnaligned) {
9458       if (Fast)
9459         *Fast = Subtarget->hasV7Ops();
9460       return true;
9461     }
9462     return false;
9463   }
9464   case MVT::f64:
9465   case MVT::v2f64: {
9466     // For any little-endian targets with neon, we can support unaligned ld/st
9467     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9468     // A big-endian target may also explicitly support unaligned accesses
9469     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9470       if (Fast)
9471         *Fast = true;
9472       return true;
9473     }
9474     return false;
9475   }
9476   }
9477 }
9478
9479 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9480                        unsigned AlignCheck) {
9481   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9482           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9483 }
9484
9485 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9486                                            unsigned DstAlign, unsigned SrcAlign,
9487                                            bool IsMemset, bool ZeroMemset,
9488                                            bool MemcpyStrSrc,
9489                                            MachineFunction &MF) const {
9490   const Function *F = MF.getFunction();
9491
9492   // See if we can use NEON instructions for this...
9493   if ((!IsMemset || ZeroMemset) &&
9494       Subtarget->hasNEON() &&
9495       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9496                                        Attribute::NoImplicitFloat)) {
9497     bool Fast;
9498     if (Size >= 16 &&
9499         (memOpAlign(SrcAlign, DstAlign, 16) ||
9500          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9501       return MVT::v2f64;
9502     } else if (Size >= 8 &&
9503                (memOpAlign(SrcAlign, DstAlign, 8) ||
9504                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9505       return MVT::f64;
9506     }
9507   }
9508
9509   // Lowering to i32/i16 if the size permits.
9510   if (Size >= 4)
9511     return MVT::i32;
9512   else if (Size >= 2)
9513     return MVT::i16;
9514
9515   // Let the target-independent logic figure it out.
9516   return MVT::Other;
9517 }
9518
9519 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9520   if (Val.getOpcode() != ISD::LOAD)
9521     return false;
9522
9523   EVT VT1 = Val.getValueType();
9524   if (!VT1.isSimple() || !VT1.isInteger() ||
9525       !VT2.isSimple() || !VT2.isInteger())
9526     return false;
9527
9528   switch (VT1.getSimpleVT().SimpleTy) {
9529   default: break;
9530   case MVT::i1:
9531   case MVT::i8:
9532   case MVT::i16:
9533     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9534     return true;
9535   }
9536
9537   return false;
9538 }
9539
9540 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9541   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9542     return false;
9543
9544   if (!isTypeLegal(EVT::getEVT(Ty1)))
9545     return false;
9546
9547   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9548
9549   // Assuming the caller doesn't have a zeroext or signext return parameter,
9550   // truncation all the way down to i1 is valid.
9551   return true;
9552 }
9553
9554
9555 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9556   if (V < 0)
9557     return false;
9558
9559   unsigned Scale = 1;
9560   switch (VT.getSimpleVT().SimpleTy) {
9561   default: return false;
9562   case MVT::i1:
9563   case MVT::i8:
9564     // Scale == 1;
9565     break;
9566   case MVT::i16:
9567     // Scale == 2;
9568     Scale = 2;
9569     break;
9570   case MVT::i32:
9571     // Scale == 4;
9572     Scale = 4;
9573     break;
9574   }
9575
9576   if ((V & (Scale - 1)) != 0)
9577     return false;
9578   V /= Scale;
9579   return V == (V & ((1LL << 5) - 1));
9580 }
9581
9582 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9583                                       const ARMSubtarget *Subtarget) {
9584   bool isNeg = false;
9585   if (V < 0) {
9586     isNeg = true;
9587     V = - V;
9588   }
9589
9590   switch (VT.getSimpleVT().SimpleTy) {
9591   default: return false;
9592   case MVT::i1:
9593   case MVT::i8:
9594   case MVT::i16:
9595   case MVT::i32:
9596     // + imm12 or - imm8
9597     if (isNeg)
9598       return V == (V & ((1LL << 8) - 1));
9599     return V == (V & ((1LL << 12) - 1));
9600   case MVT::f32:
9601   case MVT::f64:
9602     // Same as ARM mode. FIXME: NEON?
9603     if (!Subtarget->hasVFP2())
9604       return false;
9605     if ((V & 3) != 0)
9606       return false;
9607     V >>= 2;
9608     return V == (V & ((1LL << 8) - 1));
9609   }
9610 }
9611
9612 /// isLegalAddressImmediate - Return true if the integer value can be used
9613 /// as the offset of the target addressing mode for load / store of the
9614 /// given type.
9615 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9616                                     const ARMSubtarget *Subtarget) {
9617   if (V == 0)
9618     return true;
9619
9620   if (!VT.isSimple())
9621     return false;
9622
9623   if (Subtarget->isThumb1Only())
9624     return isLegalT1AddressImmediate(V, VT);
9625   else if (Subtarget->isThumb2())
9626     return isLegalT2AddressImmediate(V, VT, Subtarget);
9627
9628   // ARM mode.
9629   if (V < 0)
9630     V = - V;
9631   switch (VT.getSimpleVT().SimpleTy) {
9632   default: return false;
9633   case MVT::i1:
9634   case MVT::i8:
9635   case MVT::i32:
9636     // +- imm12
9637     return V == (V & ((1LL << 12) - 1));
9638   case MVT::i16:
9639     // +- imm8
9640     return V == (V & ((1LL << 8) - 1));
9641   case MVT::f32:
9642   case MVT::f64:
9643     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9644       return false;
9645     if ((V & 3) != 0)
9646       return false;
9647     V >>= 2;
9648     return V == (V & ((1LL << 8) - 1));
9649   }
9650 }
9651
9652 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9653                                                       EVT VT) const {
9654   int Scale = AM.Scale;
9655   if (Scale < 0)
9656     return false;
9657
9658   switch (VT.getSimpleVT().SimpleTy) {
9659   default: return false;
9660   case MVT::i1:
9661   case MVT::i8:
9662   case MVT::i16:
9663   case MVT::i32:
9664     if (Scale == 1)
9665       return true;
9666     // r + r << imm
9667     Scale = Scale & ~1;
9668     return Scale == 2 || Scale == 4 || Scale == 8;
9669   case MVT::i64:
9670     // r + r
9671     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9672       return true;
9673     return false;
9674   case MVT::isVoid:
9675     // Note, we allow "void" uses (basically, uses that aren't loads or
9676     // stores), because arm allows folding a scale into many arithmetic
9677     // operations.  This should be made more precise and revisited later.
9678
9679     // Allow r << imm, but the imm has to be a multiple of two.
9680     if (Scale & 1) return false;
9681     return isPowerOf2_32(Scale);
9682   }
9683 }
9684
9685 /// isLegalAddressingMode - Return true if the addressing mode represented
9686 /// by AM is legal for this target, for a load/store of the specified type.
9687 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9688                                               Type *Ty) const {
9689   EVT VT = getValueType(Ty, true);
9690   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9691     return false;
9692
9693   // Can never fold addr of global into load/store.
9694   if (AM.BaseGV)
9695     return false;
9696
9697   switch (AM.Scale) {
9698   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9699     break;
9700   case 1:
9701     if (Subtarget->isThumb1Only())
9702       return false;
9703     // FALL THROUGH.
9704   default:
9705     // ARM doesn't support any R+R*scale+imm addr modes.
9706     if (AM.BaseOffs)
9707       return false;
9708
9709     if (!VT.isSimple())
9710       return false;
9711
9712     if (Subtarget->isThumb2())
9713       return isLegalT2ScaledAddressingMode(AM, VT);
9714
9715     int Scale = AM.Scale;
9716     switch (VT.getSimpleVT().SimpleTy) {
9717     default: return false;
9718     case MVT::i1:
9719     case MVT::i8:
9720     case MVT::i32:
9721       if (Scale < 0) Scale = -Scale;
9722       if (Scale == 1)
9723         return true;
9724       // r + r << imm
9725       return isPowerOf2_32(Scale & ~1);
9726     case MVT::i16:
9727     case MVT::i64:
9728       // r + r
9729       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9730         return true;
9731       return false;
9732
9733     case MVT::isVoid:
9734       // Note, we allow "void" uses (basically, uses that aren't loads or
9735       // stores), because arm allows folding a scale into many arithmetic
9736       // operations.  This should be made more precise and revisited later.
9737
9738       // Allow r << imm, but the imm has to be a multiple of two.
9739       if (Scale & 1) return false;
9740       return isPowerOf2_32(Scale);
9741     }
9742   }
9743   return true;
9744 }
9745
9746 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9747 /// icmp immediate, that is the target has icmp instructions which can compare
9748 /// a register against the immediate without having to materialize the
9749 /// immediate into a register.
9750 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9751   // Thumb2 and ARM modes can use cmn for negative immediates.
9752   if (!Subtarget->isThumb())
9753     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9754   if (Subtarget->isThumb2())
9755     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9756   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9757   return Imm >= 0 && Imm <= 255;
9758 }
9759
9760 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9761 /// *or sub* immediate, that is the target has add or sub instructions which can
9762 /// add a register with the immediate without having to materialize the
9763 /// immediate into a register.
9764 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9765   // Same encoding for add/sub, just flip the sign.
9766   int64_t AbsImm = llvm::abs64(Imm);
9767   if (!Subtarget->isThumb())
9768     return ARM_AM::getSOImmVal(AbsImm) != -1;
9769   if (Subtarget->isThumb2())
9770     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9771   // Thumb1 only has 8-bit unsigned immediate.
9772   return AbsImm >= 0 && AbsImm <= 255;
9773 }
9774
9775 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9776                                       bool isSEXTLoad, SDValue &Base,
9777                                       SDValue &Offset, bool &isInc,
9778                                       SelectionDAG &DAG) {
9779   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9780     return false;
9781
9782   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9783     // AddressingMode 3
9784     Base = Ptr->getOperand(0);
9785     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9786       int RHSC = (int)RHS->getZExtValue();
9787       if (RHSC < 0 && RHSC > -256) {
9788         assert(Ptr->getOpcode() == ISD::ADD);
9789         isInc = false;
9790         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9791         return true;
9792       }
9793     }
9794     isInc = (Ptr->getOpcode() == ISD::ADD);
9795     Offset = Ptr->getOperand(1);
9796     return true;
9797   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9798     // AddressingMode 2
9799     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9800       int RHSC = (int)RHS->getZExtValue();
9801       if (RHSC < 0 && RHSC > -0x1000) {
9802         assert(Ptr->getOpcode() == ISD::ADD);
9803         isInc = false;
9804         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9805         Base = Ptr->getOperand(0);
9806         return true;
9807       }
9808     }
9809
9810     if (Ptr->getOpcode() == ISD::ADD) {
9811       isInc = true;
9812       ARM_AM::ShiftOpc ShOpcVal=
9813         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9814       if (ShOpcVal != ARM_AM::no_shift) {
9815         Base = Ptr->getOperand(1);
9816         Offset = Ptr->getOperand(0);
9817       } else {
9818         Base = Ptr->getOperand(0);
9819         Offset = Ptr->getOperand(1);
9820       }
9821       return true;
9822     }
9823
9824     isInc = (Ptr->getOpcode() == ISD::ADD);
9825     Base = Ptr->getOperand(0);
9826     Offset = Ptr->getOperand(1);
9827     return true;
9828   }
9829
9830   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9831   return false;
9832 }
9833
9834 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9835                                      bool isSEXTLoad, SDValue &Base,
9836                                      SDValue &Offset, bool &isInc,
9837                                      SelectionDAG &DAG) {
9838   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9839     return false;
9840
9841   Base = Ptr->getOperand(0);
9842   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9843     int RHSC = (int)RHS->getZExtValue();
9844     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9845       assert(Ptr->getOpcode() == ISD::ADD);
9846       isInc = false;
9847       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9848       return true;
9849     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9850       isInc = Ptr->getOpcode() == ISD::ADD;
9851       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9852       return true;
9853     }
9854   }
9855
9856   return false;
9857 }
9858
9859 /// getPreIndexedAddressParts - returns true by value, base pointer and
9860 /// offset pointer and addressing mode by reference if the node's address
9861 /// can be legally represented as pre-indexed load / store address.
9862 bool
9863 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9864                                              SDValue &Offset,
9865                                              ISD::MemIndexedMode &AM,
9866                                              SelectionDAG &DAG) const {
9867   if (Subtarget->isThumb1Only())
9868     return false;
9869
9870   EVT VT;
9871   SDValue Ptr;
9872   bool isSEXTLoad = false;
9873   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9874     Ptr = LD->getBasePtr();
9875     VT  = LD->getMemoryVT();
9876     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9877   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9878     Ptr = ST->getBasePtr();
9879     VT  = ST->getMemoryVT();
9880   } else
9881     return false;
9882
9883   bool isInc;
9884   bool isLegal = false;
9885   if (Subtarget->isThumb2())
9886     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9887                                        Offset, isInc, DAG);
9888   else
9889     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9890                                         Offset, isInc, DAG);
9891   if (!isLegal)
9892     return false;
9893
9894   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9895   return true;
9896 }
9897
9898 /// getPostIndexedAddressParts - returns true by value, base pointer and
9899 /// offset pointer and addressing mode by reference if this node can be
9900 /// combined with a load / store to form a post-indexed load / store.
9901 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9902                                                    SDValue &Base,
9903                                                    SDValue &Offset,
9904                                                    ISD::MemIndexedMode &AM,
9905                                                    SelectionDAG &DAG) const {
9906   if (Subtarget->isThumb1Only())
9907     return false;
9908
9909   EVT VT;
9910   SDValue Ptr;
9911   bool isSEXTLoad = false;
9912   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9913     VT  = LD->getMemoryVT();
9914     Ptr = LD->getBasePtr();
9915     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9916   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9917     VT  = ST->getMemoryVT();
9918     Ptr = ST->getBasePtr();
9919   } else
9920     return false;
9921
9922   bool isInc;
9923   bool isLegal = false;
9924   if (Subtarget->isThumb2())
9925     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9926                                        isInc, DAG);
9927   else
9928     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9929                                         isInc, DAG);
9930   if (!isLegal)
9931     return false;
9932
9933   if (Ptr != Base) {
9934     // Swap base ptr and offset to catch more post-index load / store when
9935     // it's legal. In Thumb2 mode, offset must be an immediate.
9936     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9937         !Subtarget->isThumb2())
9938       std::swap(Base, Offset);
9939
9940     // Post-indexed load / store update the base pointer.
9941     if (Ptr != Base)
9942       return false;
9943   }
9944
9945   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9946   return true;
9947 }
9948
9949 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9950                                                        APInt &KnownZero,
9951                                                        APInt &KnownOne,
9952                                                        const SelectionDAG &DAG,
9953                                                        unsigned Depth) const {
9954   unsigned BitWidth = KnownOne.getBitWidth();
9955   KnownZero = KnownOne = APInt(BitWidth, 0);
9956   switch (Op.getOpcode()) {
9957   default: break;
9958   case ARMISD::ADDC:
9959   case ARMISD::ADDE:
9960   case ARMISD::SUBC:
9961   case ARMISD::SUBE:
9962     // These nodes' second result is a boolean
9963     if (Op.getResNo() == 0)
9964       break;
9965     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
9966     break;
9967   case ARMISD::CMOV: {
9968     // Bits are known zero/one if known on the LHS and RHS.
9969     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9970     if (KnownZero == 0 && KnownOne == 0) return;
9971
9972     APInt KnownZeroRHS, KnownOneRHS;
9973     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9974     KnownZero &= KnownZeroRHS;
9975     KnownOne  &= KnownOneRHS;
9976     return;
9977   }
9978   case ISD::INTRINSIC_W_CHAIN: {
9979     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
9980     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
9981     switch (IntID) {
9982     default: return;
9983     case Intrinsic::arm_ldaex:
9984     case Intrinsic::arm_ldrex: {
9985       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
9986       unsigned MemBits = VT.getScalarType().getSizeInBits();
9987       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
9988       return;
9989     }
9990     }
9991   }
9992   }
9993 }
9994
9995 //===----------------------------------------------------------------------===//
9996 //                           ARM Inline Assembly Support
9997 //===----------------------------------------------------------------------===//
9998
9999 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10000   // Looking for "rev" which is V6+.
10001   if (!Subtarget->hasV6Ops())
10002     return false;
10003
10004   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10005   std::string AsmStr = IA->getAsmString();
10006   SmallVector<StringRef, 4> AsmPieces;
10007   SplitString(AsmStr, AsmPieces, ";\n");
10008
10009   switch (AsmPieces.size()) {
10010   default: return false;
10011   case 1:
10012     AsmStr = AsmPieces[0];
10013     AsmPieces.clear();
10014     SplitString(AsmStr, AsmPieces, " \t,");
10015
10016     // rev $0, $1
10017     if (AsmPieces.size() == 3 &&
10018         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10019         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10020       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10021       if (Ty && Ty->getBitWidth() == 32)
10022         return IntrinsicLowering::LowerToByteSwap(CI);
10023     }
10024     break;
10025   }
10026
10027   return false;
10028 }
10029
10030 /// getConstraintType - Given a constraint letter, return the type of
10031 /// constraint it is for this target.
10032 ARMTargetLowering::ConstraintType
10033 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10034   if (Constraint.size() == 1) {
10035     switch (Constraint[0]) {
10036     default:  break;
10037     case 'l': return C_RegisterClass;
10038     case 'w': return C_RegisterClass;
10039     case 'h': return C_RegisterClass;
10040     case 'x': return C_RegisterClass;
10041     case 't': return C_RegisterClass;
10042     case 'j': return C_Other; // Constant for movw.
10043       // An address with a single base register. Due to the way we
10044       // currently handle addresses it is the same as an 'r' memory constraint.
10045     case 'Q': return C_Memory;
10046     }
10047   } else if (Constraint.size() == 2) {
10048     switch (Constraint[0]) {
10049     default: break;
10050     // All 'U+' constraints are addresses.
10051     case 'U': return C_Memory;
10052     }
10053   }
10054   return TargetLowering::getConstraintType(Constraint);
10055 }
10056
10057 /// Examine constraint type and operand type and determine a weight value.
10058 /// This object must already have been set up with the operand type
10059 /// and the current alternative constraint selected.
10060 TargetLowering::ConstraintWeight
10061 ARMTargetLowering::getSingleConstraintMatchWeight(
10062     AsmOperandInfo &info, const char *constraint) const {
10063   ConstraintWeight weight = CW_Invalid;
10064   Value *CallOperandVal = info.CallOperandVal;
10065     // If we don't have a value, we can't do a match,
10066     // but allow it at the lowest weight.
10067   if (!CallOperandVal)
10068     return CW_Default;
10069   Type *type = CallOperandVal->getType();
10070   // Look at the constraint type.
10071   switch (*constraint) {
10072   default:
10073     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10074     break;
10075   case 'l':
10076     if (type->isIntegerTy()) {
10077       if (Subtarget->isThumb())
10078         weight = CW_SpecificReg;
10079       else
10080         weight = CW_Register;
10081     }
10082     break;
10083   case 'w':
10084     if (type->isFloatingPointTy())
10085       weight = CW_Register;
10086     break;
10087   }
10088   return weight;
10089 }
10090
10091 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10092 RCPair
10093 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10094                                                 MVT VT) const {
10095   if (Constraint.size() == 1) {
10096     // GCC ARM Constraint Letters
10097     switch (Constraint[0]) {
10098     case 'l': // Low regs or general regs.
10099       if (Subtarget->isThumb())
10100         return RCPair(0U, &ARM::tGPRRegClass);
10101       return RCPair(0U, &ARM::GPRRegClass);
10102     case 'h': // High regs or no regs.
10103       if (Subtarget->isThumb())
10104         return RCPair(0U, &ARM::hGPRRegClass);
10105       break;
10106     case 'r':
10107       return RCPair(0U, &ARM::GPRRegClass);
10108     case 'w':
10109       if (VT == MVT::Other)
10110         break;
10111       if (VT == MVT::f32)
10112         return RCPair(0U, &ARM::SPRRegClass);
10113       if (VT.getSizeInBits() == 64)
10114         return RCPair(0U, &ARM::DPRRegClass);
10115       if (VT.getSizeInBits() == 128)
10116         return RCPair(0U, &ARM::QPRRegClass);
10117       break;
10118     case 'x':
10119       if (VT == MVT::Other)
10120         break;
10121       if (VT == MVT::f32)
10122         return RCPair(0U, &ARM::SPR_8RegClass);
10123       if (VT.getSizeInBits() == 64)
10124         return RCPair(0U, &ARM::DPR_8RegClass);
10125       if (VT.getSizeInBits() == 128)
10126         return RCPair(0U, &ARM::QPR_8RegClass);
10127       break;
10128     case 't':
10129       if (VT == MVT::f32)
10130         return RCPair(0U, &ARM::SPRRegClass);
10131       break;
10132     }
10133   }
10134   if (StringRef("{cc}").equals_lower(Constraint))
10135     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10136
10137   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10138 }
10139
10140 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10141 /// vector.  If it is invalid, don't add anything to Ops.
10142 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10143                                                      std::string &Constraint,
10144                                                      std::vector<SDValue>&Ops,
10145                                                      SelectionDAG &DAG) const {
10146   SDValue Result;
10147
10148   // Currently only support length 1 constraints.
10149   if (Constraint.length() != 1) return;
10150
10151   char ConstraintLetter = Constraint[0];
10152   switch (ConstraintLetter) {
10153   default: break;
10154   case 'j':
10155   case 'I': case 'J': case 'K': case 'L':
10156   case 'M': case 'N': case 'O':
10157     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10158     if (!C)
10159       return;
10160
10161     int64_t CVal64 = C->getSExtValue();
10162     int CVal = (int) CVal64;
10163     // None of these constraints allow values larger than 32 bits.  Check
10164     // that the value fits in an int.
10165     if (CVal != CVal64)
10166       return;
10167
10168     switch (ConstraintLetter) {
10169       case 'j':
10170         // Constant suitable for movw, must be between 0 and
10171         // 65535.
10172         if (Subtarget->hasV6T2Ops())
10173           if (CVal >= 0 && CVal <= 65535)
10174             break;
10175         return;
10176       case 'I':
10177         if (Subtarget->isThumb1Only()) {
10178           // This must be a constant between 0 and 255, for ADD
10179           // immediates.
10180           if (CVal >= 0 && CVal <= 255)
10181             break;
10182         } else if (Subtarget->isThumb2()) {
10183           // A constant that can be used as an immediate value in a
10184           // data-processing instruction.
10185           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10186             break;
10187         } else {
10188           // A constant that can be used as an immediate value in a
10189           // data-processing instruction.
10190           if (ARM_AM::getSOImmVal(CVal) != -1)
10191             break;
10192         }
10193         return;
10194
10195       case 'J':
10196         if (Subtarget->isThumb()) {  // FIXME thumb2
10197           // This must be a constant between -255 and -1, for negated ADD
10198           // immediates. This can be used in GCC with an "n" modifier that
10199           // prints the negated value, for use with SUB instructions. It is
10200           // not useful otherwise but is implemented for compatibility.
10201           if (CVal >= -255 && CVal <= -1)
10202             break;
10203         } else {
10204           // This must be a constant between -4095 and 4095. It is not clear
10205           // what this constraint is intended for. Implemented for
10206           // compatibility with GCC.
10207           if (CVal >= -4095 && CVal <= 4095)
10208             break;
10209         }
10210         return;
10211
10212       case 'K':
10213         if (Subtarget->isThumb1Only()) {
10214           // A 32-bit value where only one byte has a nonzero value. Exclude
10215           // zero to match GCC. This constraint is used by GCC internally for
10216           // constants that can be loaded with a move/shift combination.
10217           // It is not useful otherwise but is implemented for compatibility.
10218           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10219             break;
10220         } else if (Subtarget->isThumb2()) {
10221           // A constant whose bitwise inverse can be used as an immediate
10222           // value in a data-processing instruction. This can be used in GCC
10223           // with a "B" modifier that prints the inverted value, for use with
10224           // BIC and MVN instructions. It is not useful otherwise but is
10225           // implemented for compatibility.
10226           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10227             break;
10228         } else {
10229           // A constant whose bitwise inverse can be used as an immediate
10230           // value in a data-processing instruction. This can be used in GCC
10231           // with a "B" modifier that prints the inverted value, for use with
10232           // BIC and MVN instructions. It is not useful otherwise but is
10233           // implemented for compatibility.
10234           if (ARM_AM::getSOImmVal(~CVal) != -1)
10235             break;
10236         }
10237         return;
10238
10239       case 'L':
10240         if (Subtarget->isThumb1Only()) {
10241           // This must be a constant between -7 and 7,
10242           // for 3-operand ADD/SUB immediate instructions.
10243           if (CVal >= -7 && CVal < 7)
10244             break;
10245         } else if (Subtarget->isThumb2()) {
10246           // A constant whose negation can be used as an immediate value in a
10247           // data-processing instruction. This can be used in GCC with an "n"
10248           // modifier that prints the negated value, for use with SUB
10249           // instructions. It is not useful otherwise but is implemented for
10250           // compatibility.
10251           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10252             break;
10253         } else {
10254           // A constant whose negation can be used as an immediate value in a
10255           // data-processing instruction. This can be used in GCC with an "n"
10256           // modifier that prints the negated value, for use with SUB
10257           // instructions. It is not useful otherwise but is implemented for
10258           // compatibility.
10259           if (ARM_AM::getSOImmVal(-CVal) != -1)
10260             break;
10261         }
10262         return;
10263
10264       case 'M':
10265         if (Subtarget->isThumb()) { // FIXME thumb2
10266           // This must be a multiple of 4 between 0 and 1020, for
10267           // ADD sp + immediate.
10268           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10269             break;
10270         } else {
10271           // A power of two or a constant between 0 and 32.  This is used in
10272           // GCC for the shift amount on shifted register operands, but it is
10273           // useful in general for any shift amounts.
10274           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10275             break;
10276         }
10277         return;
10278
10279       case 'N':
10280         if (Subtarget->isThumb()) {  // FIXME thumb2
10281           // This must be a constant between 0 and 31, for shift amounts.
10282           if (CVal >= 0 && CVal <= 31)
10283             break;
10284         }
10285         return;
10286
10287       case 'O':
10288         if (Subtarget->isThumb()) {  // FIXME thumb2
10289           // This must be a multiple of 4 between -508 and 508, for
10290           // ADD/SUB sp = sp + immediate.
10291           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10292             break;
10293         }
10294         return;
10295     }
10296     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10297     break;
10298   }
10299
10300   if (Result.getNode()) {
10301     Ops.push_back(Result);
10302     return;
10303   }
10304   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10305 }
10306
10307 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10308   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10309   unsigned Opcode = Op->getOpcode();
10310   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10311       "Invalid opcode for Div/Rem lowering");
10312   bool isSigned = (Opcode == ISD::SDIVREM);
10313   EVT VT = Op->getValueType(0);
10314   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10315
10316   RTLIB::Libcall LC;
10317   switch (VT.getSimpleVT().SimpleTy) {
10318   default: llvm_unreachable("Unexpected request for libcall!");
10319   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10320   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10321   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10322   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10323   }
10324
10325   SDValue InChain = DAG.getEntryNode();
10326
10327   TargetLowering::ArgListTy Args;
10328   TargetLowering::ArgListEntry Entry;
10329   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10330     EVT ArgVT = Op->getOperand(i).getValueType();
10331     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10332     Entry.Node = Op->getOperand(i);
10333     Entry.Ty = ArgTy;
10334     Entry.isSExt = isSigned;
10335     Entry.isZExt = !isSigned;
10336     Args.push_back(Entry);
10337   }
10338
10339   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10340                                          getPointerTy());
10341
10342   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10343
10344   SDLoc dl(Op);
10345   TargetLowering::
10346   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10347                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10348                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10349                     Callee, Args, DAG, dl);
10350   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10351
10352   return CallInfo.first;
10353 }
10354
10355 bool
10356 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10357   // The ARM target isn't yet aware of offsets.
10358   return false;
10359 }
10360
10361 bool ARM::isBitFieldInvertedMask(unsigned v) {
10362   if (v == 0xffffffff)
10363     return false;
10364
10365   // there can be 1's on either or both "outsides", all the "inside"
10366   // bits must be 0's
10367   unsigned TO = CountTrailingOnes_32(v);
10368   unsigned LO = CountLeadingOnes_32(v);
10369   v = (v >> TO) << TO;
10370   v = (v << LO) >> LO;
10371   return v == 0;
10372 }
10373
10374 /// isFPImmLegal - Returns true if the target can instruction select the
10375 /// specified FP immediate natively. If false, the legalizer will
10376 /// materialize the FP immediate as a load from a constant pool.
10377 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10378   if (!Subtarget->hasVFP3())
10379     return false;
10380   if (VT == MVT::f32)
10381     return ARM_AM::getFP32Imm(Imm) != -1;
10382   if (VT == MVT::f64)
10383     return ARM_AM::getFP64Imm(Imm) != -1;
10384   return false;
10385 }
10386
10387 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10388 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10389 /// specified in the intrinsic calls.
10390 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10391                                            const CallInst &I,
10392                                            unsigned Intrinsic) const {
10393   switch (Intrinsic) {
10394   case Intrinsic::arm_neon_vld1:
10395   case Intrinsic::arm_neon_vld2:
10396   case Intrinsic::arm_neon_vld3:
10397   case Intrinsic::arm_neon_vld4:
10398   case Intrinsic::arm_neon_vld2lane:
10399   case Intrinsic::arm_neon_vld3lane:
10400   case Intrinsic::arm_neon_vld4lane: {
10401     Info.opc = ISD::INTRINSIC_W_CHAIN;
10402     // Conservatively set memVT to the entire set of vectors loaded.
10403     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10404     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10405     Info.ptrVal = I.getArgOperand(0);
10406     Info.offset = 0;
10407     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10408     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10409     Info.vol = false; // volatile loads with NEON intrinsics not supported
10410     Info.readMem = true;
10411     Info.writeMem = false;
10412     return true;
10413   }
10414   case Intrinsic::arm_neon_vst1:
10415   case Intrinsic::arm_neon_vst2:
10416   case Intrinsic::arm_neon_vst3:
10417   case Intrinsic::arm_neon_vst4:
10418   case Intrinsic::arm_neon_vst2lane:
10419   case Intrinsic::arm_neon_vst3lane:
10420   case Intrinsic::arm_neon_vst4lane: {
10421     Info.opc = ISD::INTRINSIC_VOID;
10422     // Conservatively set memVT to the entire set of vectors stored.
10423     unsigned NumElts = 0;
10424     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10425       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10426       if (!ArgTy->isVectorTy())
10427         break;
10428       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10429     }
10430     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10431     Info.ptrVal = I.getArgOperand(0);
10432     Info.offset = 0;
10433     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10434     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10435     Info.vol = false; // volatile stores with NEON intrinsics not supported
10436     Info.readMem = false;
10437     Info.writeMem = true;
10438     return true;
10439   }
10440   case Intrinsic::arm_ldaex:
10441   case Intrinsic::arm_ldrex: {
10442     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10443     Info.opc = ISD::INTRINSIC_W_CHAIN;
10444     Info.memVT = MVT::getVT(PtrTy->getElementType());
10445     Info.ptrVal = I.getArgOperand(0);
10446     Info.offset = 0;
10447     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10448     Info.vol = true;
10449     Info.readMem = true;
10450     Info.writeMem = false;
10451     return true;
10452   }
10453   case Intrinsic::arm_stlex:
10454   case Intrinsic::arm_strex: {
10455     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10456     Info.opc = ISD::INTRINSIC_W_CHAIN;
10457     Info.memVT = MVT::getVT(PtrTy->getElementType());
10458     Info.ptrVal = I.getArgOperand(1);
10459     Info.offset = 0;
10460     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10461     Info.vol = true;
10462     Info.readMem = false;
10463     Info.writeMem = true;
10464     return true;
10465   }
10466   case Intrinsic::arm_stlexd:
10467   case Intrinsic::arm_strexd: {
10468     Info.opc = ISD::INTRINSIC_W_CHAIN;
10469     Info.memVT = MVT::i64;
10470     Info.ptrVal = I.getArgOperand(2);
10471     Info.offset = 0;
10472     Info.align = 8;
10473     Info.vol = true;
10474     Info.readMem = false;
10475     Info.writeMem = true;
10476     return true;
10477   }
10478   case Intrinsic::arm_ldaexd:
10479   case Intrinsic::arm_ldrexd: {
10480     Info.opc = ISD::INTRINSIC_W_CHAIN;
10481     Info.memVT = MVT::i64;
10482     Info.ptrVal = I.getArgOperand(0);
10483     Info.offset = 0;
10484     Info.align = 8;
10485     Info.vol = true;
10486     Info.readMem = true;
10487     Info.writeMem = false;
10488     return true;
10489   }
10490   default:
10491     break;
10492   }
10493
10494   return false;
10495 }
10496
10497 /// \brief Returns true if it is beneficial to convert a load of a constant
10498 /// to just the constant itself.
10499 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10500                                                           Type *Ty) const {
10501   assert(Ty->isIntegerTy());
10502
10503   unsigned Bits = Ty->getPrimitiveSizeInBits();
10504   if (Bits == 0 || Bits > 32)
10505     return false;
10506   return true;
10507 }
10508
10509 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10510   // Loads and stores less than 64-bits are already atomic; ones above that
10511   // are doomed anyway, so defer to the default libcall and blame the OS when
10512   // things go wrong:
10513   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10514     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10515   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10516     return LI->getType()->getPrimitiveSizeInBits() == 64;
10517
10518   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10519   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10520 }
10521
10522 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10523                                          AtomicOrdering Ord) const {
10524   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10525   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10526   bool IsAcquire =
10527       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10528
10529   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10530   // intrinsic must return {i32, i32} and we have to recombine them into a
10531   // single i64 here.
10532   if (ValTy->getPrimitiveSizeInBits() == 64) {
10533     Intrinsic::ID Int =
10534         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10535     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10536
10537     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10538     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10539
10540     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10541     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10542     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10543     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10544     return Builder.CreateOr(
10545         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10546   }
10547
10548   Type *Tys[] = { Addr->getType() };
10549   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10550   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10551
10552   return Builder.CreateTruncOrBitCast(
10553       Builder.CreateCall(Ldrex, Addr),
10554       cast<PointerType>(Addr->getType())->getElementType());
10555 }
10556
10557 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10558                                                Value *Addr,
10559                                                AtomicOrdering Ord) const {
10560   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10561   bool IsRelease =
10562       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10563
10564   // Since the intrinsics must have legal type, the i64 intrinsics take two
10565   // parameters: "i32, i32". We must marshal Val into the appropriate form
10566   // before the call.
10567   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10568     Intrinsic::ID Int =
10569         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10570     Function *Strex = Intrinsic::getDeclaration(M, Int);
10571     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10572
10573     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10574     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10575     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10576     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10577   }
10578
10579   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10580   Type *Tys[] = { Addr->getType() };
10581   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10582
10583   return Builder.CreateCall2(
10584       Strex, Builder.CreateZExtOrBitCast(
10585                  Val, Strex->getFunctionType()->getParamType(0)),
10586       Addr);
10587 }