[X86][Haswell][SchedModel] Add architecture specific scheduling models.
[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/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <utility>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "arm-isel"
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 cl::opt<bool>
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61   cl::desc("Generate calls via indirect call instructions"),
62   cl::init(false));
63
64 static cl::opt<bool>
65 ARMInterworking("arm-interworking", cl::Hidden,
66   cl::desc("Enable / disable ARM interworking (for debugging only)"),
67   cl::init(true));
68
69 namespace {
70   class ARMCCState : public CCState {
71   public:
72     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74                ParmContext PC)
75         : CCState(CC, isVarArg, MF, locs, C) {
76       assert(((PC == Call) || (PC == Prologue)) &&
77              "ARMCCState users must specify whether their context is call"
78              "or prologue generation.");
79       CallOrPrologue = PC;
80     }
81   };
82 }
83
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86   ARM::R0, ARM::R1, ARM::R2, ARM::R3
87 };
88
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90                                        MVT PromotedBitwiseVT) {
91   if (VT != PromotedLdStVT) {
92     setOperationAction(ISD::LOAD, VT, Promote);
93     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94
95     setOperationAction(ISD::STORE, VT, Promote);
96     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
97   }
98
99   MVT ElemTy = VT.getVectorElementType();
100   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101     setOperationAction(ISD::SETCC, VT, Custom);
102   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104   if (ElemTy == MVT::i32) {
105     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109   } else {
110     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114   }
115   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
116   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
117   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
118   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119   setOperationAction(ISD::SELECT,            VT, Expand);
120   setOperationAction(ISD::SELECT_CC,         VT, Expand);
121   setOperationAction(ISD::VSELECT,           VT, Expand);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT, Custom);
125     setOperationAction(ISD::SRA, VT, Custom);
126     setOperationAction(ISD::SRL, VT, Custom);
127   }
128
129   // Promote all bit-wise operations.
130   if (VT.isInteger() && VT != PromotedBitwiseVT) {
131     setOperationAction(ISD::AND, VT, Promote);
132     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133     setOperationAction(ISD::OR,  VT, Promote);
134     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
135     setOperationAction(ISD::XOR, VT, Promote);
136     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
137   }
138
139   // Neon does not support vector divide/remainder operations.
140   setOperationAction(ISD::SDIV, VT, Expand);
141   setOperationAction(ISD::UDIV, VT, Expand);
142   setOperationAction(ISD::FDIV, VT, Expand);
143   setOperationAction(ISD::SREM, VT, Expand);
144   setOperationAction(ISD::UREM, VT, Expand);
145   setOperationAction(ISD::FREM, VT, Expand);
146 }
147
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149   addRegisterClass(VT, &ARM::DPRRegClass);
150   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
151 }
152
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPairRegClass);
155   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
156 }
157
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159   if (TT.isOSBinFormatMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TT.isOSWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
170   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
171
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   if (Subtarget->isTargetMachO()) {
175     // Uses VFP for Thumb libfuncs if available.
176     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178       // Single-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183
184       // Double-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189
190       // Single-precision comparisons.
191       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
198       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
199
200       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
207       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
208
209       // Double-precision comparisons.
210       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
217       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
218
219       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
226       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
227
228       // Floating-point to integer conversions.
229       // i64 conversions are done via library routines even when generating VFP
230       // instructions, so use the same ones.
231       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235
236       // Conversions between floating types.
237       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
239
240       // Integer to floating-point conversions.
241       // i64 conversions are done via library routines even when generating VFP
242       // instructions, so use the same ones.
243       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244       // e.g., __floatunsidf vs. __floatunssidfvfp.
245       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
249     }
250   }
251
252   // These libcalls are not available in 32-bit.
253   setLibcallName(RTLIB::SHL_I128, nullptr);
254   setLibcallName(RTLIB::SRL_I128, nullptr);
255   setLibcallName(RTLIB::SRA_I128, nullptr);
256
257   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258       !Subtarget->isTargetWindows()) {
259     static const struct {
260       const RTLIB::Libcall Op;
261       const char * const Name;
262       const CallingConv::ID CC;
263       const ISD::CondCode Cond;
264     } LibraryCalls[] = {
265       // Double-precision floating-point arithmetic helper functions
266       // RTABI chapter 4.1.2, Table 2
267       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       // FIXME: double __aeabi_drsub(double x, double y) (rsub)
271       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272
273       // Double-precision floating-point comparison helper functions
274       // RTABI chapter 4.1.2, Table 3
275       // FIXME: void __aeabi_cdcmpeq(double, double)
276       // FIXME: void __aeabi_cdcmple(double, double)
277       // FIXME: void __aeabi_cdrcmple(double, double)
278       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
280       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
284       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
285       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
286
287       // Single-precision floating-point arithmetic helper functions
288       // RTABI chapter 4.1.2, Table 4
289       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292       // FIXME: void __aeabi_frsub(float x, float y)
293       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294
295       // Single-precision floating-point comparison helper functions
296       // RTABI chapter 4.1.2, Table 5
297       // FIXME: void __aeabi_cfcmpeq(float, float)
298       // FIXME: void __aeabi_cfcmple(float, float)
299       // FIXME: void __aeabi_cfrcmple(float, float)
300       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
301       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
302       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
303       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
304       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
305       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
306       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
307       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
308
309       // Floating-point to integer conversions.
310       // RTABI chapter 4.1.2, Table 6
311       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319
320       // Conversions between floating types.
321       // RTABI chapter 4.1.2, Table 7
322       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       // FIXME: float __aeabi_f2f(short)
325       // FIXME: float __aeabi_h2f_alt(short)
326       // FIXME: short __aeabi_f2h(float)
327       // FIXME: short __aeabi_f2h_alt(float)
328       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       // FIXME: short __aeabi_d2h_alt(double)
330
331       // Integer to floating-point conversions.
332       // RTABI chapter 4.1.2, Table 8
333       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Long long helper functions
343       // RTABI chapter 4.2, Table 9
344       { RTLIB::MUL_I64,     "__aeabi_lmul",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       // FIXME: __aeabi_ldivmod is SDIVREM not SDIV; we should custom lower this
346       { RTLIB::SDIV_I64,    "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::SDIVREM_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348       // FIXME: __aeabi_uldivmod is UDIVREM not UDIV; we should custom lower this
349       { RTLIB::UDIV_I64,    "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::SHL_I64,     "__aeabi_llsl",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::SRL_I64,     "__aeabi_llsr",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353       { RTLIB::SRA_I64,     "__aeabi_lasr",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354       // FIXME: int __aeabi_lcmp(long long, long long)
355       // FIXME: int __aeabi_ulcmp(unsigned long long, unsigned long long)
356
357       // Integer division functions
358       // RTABI chapter 4.3.1
359       { RTLIB::SDIV_I8,     "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360       { RTLIB::SDIV_I16,    "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
361       { RTLIB::SDIV_I32,    "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
362       { RTLIB::UDIV_I8,     "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
363       { RTLIB::UDIV_I16,    "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
364       { RTLIB::UDIV_I32,    "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
365       { RTLIB::SDIVREM_I8,  "__aeabi_idivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366       { RTLIB::SDIVREM_I16, "__aeabi_idivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367       { RTLIB::SDIVREM_I32, "__aeabi_idivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368       { RTLIB::UDIVREM_I8,  "__aeabi_uidivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
369       { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370       { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371
372       // Memory operations
373       // RTABI chapter 4.3.4
374       // FIXME: void __aeabi_memcpy8(void *, const void *, size_t)
375       // FIXME: void __aeabi_memcpy4(void *, const void *, size_t)
376       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       // FIXME: void __aeabi_memmove8(void *, const void *, size_t)
378       // FIXME: void __aeabi_memmove4(void *, const void *, size_t)
379       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       // FIXME: void __aeabi_memset8(void *, size_t, int)
381       // FIXME: void __aeabi_memset4(void *, size_t, int)
382       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383       // FIXME: void __aeabi_memclr8(void *, size_t)
384       // FIXME: void __aeabi_memclr4(void *, size_t)
385       // FIXME: void __aeabi_memclr(void *, size_t)
386     };
387
388     for (const auto &LC : LibraryCalls) {
389       setLibcallName(LC.Op, LC.Name);
390       setLibcallCallingConv(LC.Op, LC.CC);
391       if (LC.Cond != ISD::SETCC_INVALID)
392         setCmpLibcallCC(LC.Op, LC.Cond);
393     }
394
395     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
396     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
397   }
398
399   if (Subtarget->isTargetWindows()) {
400     static const struct {
401       const RTLIB::Libcall Op;
402       const char * const Name;
403       const CallingConv::ID CC;
404     } LibraryCalls[] = {
405       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
406       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
407       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
408       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
409       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
410       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
411       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
412       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
413     };
414
415     for (const auto &LC : LibraryCalls) {
416       setLibcallName(LC.Op, LC.Name);
417       setLibcallCallingConv(LC.Op, LC.CC);
418     }
419   }
420
421   // Use divmod compiler-rt calls for iOS 5.0 and later.
422   if (Subtarget->getTargetTriple().isiOS() &&
423       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
424     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
425     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
426   }
427
428   // The half <-> float conversion functions are always soft-float, but are
429   // needed for some targets which use a hard-float calling convention by
430   // default.
431   if (Subtarget->isAAPCS_ABI()) {
432     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
433     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
434     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
435   } else {
436     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
437     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
438     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
439   }
440
441   if (Subtarget->isThumb1Only())
442     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
443   else
444     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
445   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
446       !Subtarget->isThumb1Only()) {
447     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
448     if (!Subtarget->isFPOnlySP())
449       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
450   }
451
452   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
453        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
454     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
455          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
456       setTruncStoreAction((MVT::SimpleValueType)VT,
457                           (MVT::SimpleValueType)InnerVT, Expand);
458     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
459     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
460     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
461
462     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
463     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
464     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
465     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
466
467     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
468   }
469
470   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
471   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
472
473   if (Subtarget->hasNEON()) {
474     addDRTypeForNEON(MVT::v2f32);
475     addDRTypeForNEON(MVT::v8i8);
476     addDRTypeForNEON(MVT::v4i16);
477     addDRTypeForNEON(MVT::v2i32);
478     addDRTypeForNEON(MVT::v1i64);
479
480     addQRTypeForNEON(MVT::v4f32);
481     addQRTypeForNEON(MVT::v2f64);
482     addQRTypeForNEON(MVT::v16i8);
483     addQRTypeForNEON(MVT::v8i16);
484     addQRTypeForNEON(MVT::v4i32);
485     addQRTypeForNEON(MVT::v2i64);
486
487     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
488     // neither Neon nor VFP support any arithmetic operations on it.
489     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
490     // supported for v4f32.
491     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
493     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
494     // FIXME: Code duplication: FDIV and FREM are expanded always, see
495     // ARMTargetLowering::addTypeForNEON method for details.
496     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
497     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
498     // FIXME: Create unittest.
499     // In another words, find a way when "copysign" appears in DAG with vector
500     // operands.
501     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
502     // FIXME: Code duplication: SETCC has custom operation action, see
503     // ARMTargetLowering::addTypeForNEON method for details.
504     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
505     // FIXME: Create unittest for FNEG and for FABS.
506     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
507     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
508     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
510     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
511     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
512     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
513     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
514     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
515     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
516     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
517     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
518     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
519     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
521     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
524     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
525
526     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
527     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
528     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
529     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
530     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
531     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
532     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
533     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
534     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
535     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
536     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
537     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
538     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
540     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
541
542     // Mark v2f32 intrinsics.
543     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
544     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
545     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
546     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
547     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
548     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
549     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
550     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
551     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
552     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
553     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
554     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
555     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
556     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
557     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
558
559     // Neon does not support some operations on v1i64 and v2i64 types.
560     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
561     // Custom handling for some quad-vector types to detect VMULL.
562     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
563     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
564     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
565     // Custom handling for some vector types to avoid expensive expansions
566     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
567     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
568     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
569     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
570     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
571     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
572     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
573     // a destination type that is wider than the source, and nor does
574     // it have a FP_TO_[SU]INT instruction with a narrower destination than
575     // source.
576     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
577     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
578     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
579     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
580
581     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
582     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
583
584     // NEON does not have single instruction CTPOP for vectors with element
585     // types wider than 8-bits.  However, custom lowering can leverage the
586     // v8i8/v16i8 vcnt instruction.
587     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
588     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
589     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
590     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
591
592     // NEON only has FMA instructions as of VFP4.
593     if (!Subtarget->hasVFP4()) {
594       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
595       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
596     }
597
598     setTargetDAGCombine(ISD::INTRINSIC_VOID);
599     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
600     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
601     setTargetDAGCombine(ISD::SHL);
602     setTargetDAGCombine(ISD::SRL);
603     setTargetDAGCombine(ISD::SRA);
604     setTargetDAGCombine(ISD::SIGN_EXTEND);
605     setTargetDAGCombine(ISD::ZERO_EXTEND);
606     setTargetDAGCombine(ISD::ANY_EXTEND);
607     setTargetDAGCombine(ISD::SELECT_CC);
608     setTargetDAGCombine(ISD::BUILD_VECTOR);
609     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
610     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
611     setTargetDAGCombine(ISD::STORE);
612     setTargetDAGCombine(ISD::FP_TO_SINT);
613     setTargetDAGCombine(ISD::FP_TO_UINT);
614     setTargetDAGCombine(ISD::FDIV);
615
616     // It is legal to extload from v4i8 to v4i16 or v4i32.
617     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
618                   MVT::v4i16, MVT::v2i16,
619                   MVT::v2i32};
620     for (unsigned i = 0; i < 6; ++i) {
621       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
622       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
623       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
624     }
625   }
626
627   // ARM and Thumb2 support UMLAL/SMLAL.
628   if (!Subtarget->isThumb1Only())
629     setTargetDAGCombine(ISD::ADDC);
630
631
632   computeRegisterProperties();
633
634   // ARM does not have floating-point extending loads.
635   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
636   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
637
638   // ... or truncating stores
639   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
640   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
641   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
642
643   // ARM does not have i1 sign extending load.
644   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
645
646   // ARM supports all 4 flavors of integer indexed load / store.
647   if (!Subtarget->isThumb1Only()) {
648     for (unsigned im = (unsigned)ISD::PRE_INC;
649          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
650       setIndexedLoadAction(im,  MVT::i1,  Legal);
651       setIndexedLoadAction(im,  MVT::i8,  Legal);
652       setIndexedLoadAction(im,  MVT::i16, Legal);
653       setIndexedLoadAction(im,  MVT::i32, Legal);
654       setIndexedStoreAction(im, MVT::i1,  Legal);
655       setIndexedStoreAction(im, MVT::i8,  Legal);
656       setIndexedStoreAction(im, MVT::i16, Legal);
657       setIndexedStoreAction(im, MVT::i32, Legal);
658     }
659   }
660
661   setOperationAction(ISD::SADDO, MVT::i32, Custom);
662   setOperationAction(ISD::UADDO, MVT::i32, Custom);
663   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
664   setOperationAction(ISD::USUBO, MVT::i32, Custom);
665
666   // i64 operation support.
667   setOperationAction(ISD::MUL,     MVT::i64, Expand);
668   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
669   if (Subtarget->isThumb1Only()) {
670     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
671     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
672   }
673   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
674       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
675     setOperationAction(ISD::MULHS, MVT::i32, Expand);
676
677   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
678   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
679   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
680   setOperationAction(ISD::SRL,       MVT::i64, Custom);
681   setOperationAction(ISD::SRA,       MVT::i64, Custom);
682
683   if (!Subtarget->isThumb1Only()) {
684     // FIXME: We should do this for Thumb1 as well.
685     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
686     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
687     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
688     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
689   }
690
691   // ARM does not have ROTL.
692   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
693   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
694   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
695   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
696     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
697
698   // These just redirect to CTTZ and CTLZ on ARM.
699   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
700   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
701
702   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
703
704   // Only ARMv6 has BSWAP.
705   if (!Subtarget->hasV6Ops())
706     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
707
708   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
709       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
710     // These are expanded into libcalls if the cpu doesn't have HW divider.
711     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
712     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
713   }
714
715   // FIXME: Also set divmod for SREM on EABI
716   setOperationAction(ISD::SREM, MVT::i32, Expand);
717   setOperationAction(ISD::UREM, MVT::i32, Expand);
718   if (!Subtarget->isTargetAEABI()) {
719     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
720     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
721   }
722
723   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
724   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
725   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
726   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
727   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
728
729   setOperationAction(ISD::TRAP, MVT::Other, Legal);
730
731   // Use the default implementation.
732   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
733   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
734   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
735   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
736   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
737   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
738
739   if (!Subtarget->isTargetMachO()) {
740     // Non-MachO platforms may return values in these registers via the
741     // personality function.
742     setExceptionPointerRegister(ARM::R0);
743     setExceptionSelectorRegister(ARM::R1);
744   }
745
746   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
747     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
748   else
749     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
750
751   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
752   // the default expansion.
753   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
754     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
755     // to ldrex/strex loops already.
756     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
757
758     // On v8, we have particularly efficient implementations of atomic fences
759     // if they can be combined with nearby atomic loads and stores.
760     if (!Subtarget->hasV8Ops()) {
761       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
762       setInsertFencesForAtomic(true);
763     }
764   } else {
765     // If there's anything we can use as a barrier, go through custom lowering
766     // for ATOMIC_FENCE.
767     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
768                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
769
770     // Set them all for expansion, which will force libcalls.
771     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
772     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
773     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
774     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
775     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
776     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
777     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
782     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
783     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
784     // Unordered/Monotonic case.
785     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
786     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
787   }
788
789   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
790
791   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
792   if (!Subtarget->hasV6Ops()) {
793     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
794     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
795   }
796   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
797
798   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
799       !Subtarget->isThumb1Only()) {
800     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
801     // iff target supports vfp2.
802     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
803     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
804   }
805
806   // We want to custom lower some of our intrinsics.
807   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
808   if (Subtarget->isTargetDarwin()) {
809     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
810     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
811     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
812   }
813
814   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
815   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
816   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
817   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
818   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
819   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
820   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
821   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
822   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
823
824   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
825   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
826   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
827   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
828   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
829
830   // We don't support sin/cos/fmod/copysign/pow
831   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
832   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
833   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
834   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
835   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
836   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
837   setOperationAction(ISD::FREM,      MVT::f64, Expand);
838   setOperationAction(ISD::FREM,      MVT::f32, Expand);
839   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
840       !Subtarget->isThumb1Only()) {
841     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
842     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
843   }
844   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
845   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
846
847   if (!Subtarget->hasVFP4()) {
848     setOperationAction(ISD::FMA, MVT::f64, Expand);
849     setOperationAction(ISD::FMA, MVT::f32, Expand);
850   }
851
852   // Various VFP goodness
853   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
854     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
855     if (Subtarget->hasVFP2()) {
856       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
857       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
858       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
859       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
860     }
861
862     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
863     if (!Subtarget->hasV8Ops()) {
864       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
865       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
866     }
867
868     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
869     if (!Subtarget->hasFP16()) {
870       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
871       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
872     }
873   }
874
875   // Combine sin / cos into one node or libcall if possible.
876   if (Subtarget->hasSinCos()) {
877     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
878     setLibcallName(RTLIB::SINCOS_F64, "sincos");
879     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
880       // For iOS, we don't want to the normal expansion of a libcall to
881       // sincos. We want to issue a libcall to __sincos_stret.
882       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
883       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
884     }
885   }
886
887   // ARMv8 implements a lot of rounding-like FP operations.
888   if (Subtarget->hasV8Ops()) {
889     static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
890     for (const auto Ty : RoundingTypes) {
891       setOperationAction(ISD::FFLOOR, Ty, Legal);
892       setOperationAction(ISD::FCEIL, Ty, Legal);
893       setOperationAction(ISD::FROUND, Ty, Legal);
894       setOperationAction(ISD::FTRUNC, Ty, Legal);
895       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
896       setOperationAction(ISD::FRINT, Ty, Legal);
897     }
898   }
899   // We have target-specific dag combine patterns for the following nodes:
900   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
901   setTargetDAGCombine(ISD::ADD);
902   setTargetDAGCombine(ISD::SUB);
903   setTargetDAGCombine(ISD::MUL);
904   setTargetDAGCombine(ISD::AND);
905   setTargetDAGCombine(ISD::OR);
906   setTargetDAGCombine(ISD::XOR);
907
908   if (Subtarget->hasV6Ops())
909     setTargetDAGCombine(ISD::SRL);
910
911   setStackPointerRegisterToSaveRestore(ARM::SP);
912
913   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
914       !Subtarget->hasVFP2())
915     setSchedulingPreference(Sched::RegPressure);
916   else
917     setSchedulingPreference(Sched::Hybrid);
918
919   //// temporary - rewrite interface to use type
920   MaxStoresPerMemset = 8;
921   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
922   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
923   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
924   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
925   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
926
927   // On ARM arguments smaller than 4 bytes are extended, so all arguments
928   // are at least 4 bytes aligned.
929   setMinStackArgumentAlignment(4);
930
931   // Prefer likely predicted branches to selects on out-of-order cores.
932   PredictableSelectIsExpensive = Subtarget->isLikeA9();
933
934   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
935 }
936
937 // FIXME: It might make sense to define the representative register class as the
938 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
939 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
940 // SPR's representative would be DPR_VFP2. This should work well if register
941 // pressure tracking were modified such that a register use would increment the
942 // pressure of the register class's representative and all of it's super
943 // classes' representatives transitively. We have not implemented this because
944 // of the difficulty prior to coalescing of modeling operand register classes
945 // due to the common occurrence of cross class copies and subregister insertions
946 // and extractions.
947 std::pair<const TargetRegisterClass*, uint8_t>
948 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
949   const TargetRegisterClass *RRC = nullptr;
950   uint8_t Cost = 1;
951   switch (VT.SimpleTy) {
952   default:
953     return TargetLowering::findRepresentativeClass(VT);
954   // Use DPR as representative register class for all floating point
955   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
956   // the cost is 1 for both f32 and f64.
957   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
958   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
959     RRC = &ARM::DPRRegClass;
960     // When NEON is used for SP, only half of the register file is available
961     // because operations that define both SP and DP results will be constrained
962     // to the VFP2 class (D0-D15). We currently model this constraint prior to
963     // coalescing by double-counting the SP regs. See the FIXME above.
964     if (Subtarget->useNEONForSinglePrecisionFP())
965       Cost = 2;
966     break;
967   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
968   case MVT::v4f32: case MVT::v2f64:
969     RRC = &ARM::DPRRegClass;
970     Cost = 2;
971     break;
972   case MVT::v4i64:
973     RRC = &ARM::DPRRegClass;
974     Cost = 4;
975     break;
976   case MVT::v8i64:
977     RRC = &ARM::DPRRegClass;
978     Cost = 8;
979     break;
980   }
981   return std::make_pair(RRC, Cost);
982 }
983
984 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
985   switch (Opcode) {
986   default: return nullptr;
987   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
988   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
989   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
990   case ARMISD::CALL:          return "ARMISD::CALL";
991   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
992   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
993   case ARMISD::tCALL:         return "ARMISD::tCALL";
994   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
995   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
996   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
997   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
998   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
999   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1000   case ARMISD::CMP:           return "ARMISD::CMP";
1001   case ARMISD::CMN:           return "ARMISD::CMN";
1002   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1003   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1004   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1005   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1006   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1007
1008   case ARMISD::CMOV:          return "ARMISD::CMOV";
1009
1010   case ARMISD::RBIT:          return "ARMISD::RBIT";
1011
1012   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1013   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1014   case ARMISD::SITOF:         return "ARMISD::SITOF";
1015   case ARMISD::UITOF:         return "ARMISD::UITOF";
1016
1017   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1018   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1019   case ARMISD::RRX:           return "ARMISD::RRX";
1020
1021   case ARMISD::ADDC:          return "ARMISD::ADDC";
1022   case ARMISD::ADDE:          return "ARMISD::ADDE";
1023   case ARMISD::SUBC:          return "ARMISD::SUBC";
1024   case ARMISD::SUBE:          return "ARMISD::SUBE";
1025
1026   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1027   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1028
1029   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1030   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1031
1032   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1033
1034   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1035
1036   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1037
1038   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1039
1040   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1041
1042   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1043
1044   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1045   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1046   case ARMISD::VCGE:          return "ARMISD::VCGE";
1047   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1048   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1049   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1050   case ARMISD::VCGT:          return "ARMISD::VCGT";
1051   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1052   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1053   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1054   case ARMISD::VTST:          return "ARMISD::VTST";
1055
1056   case ARMISD::VSHL:          return "ARMISD::VSHL";
1057   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1058   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1059   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1060   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1061   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1062   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1063   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1064   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1065   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1066   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1067   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1068   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1069   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1070   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1071   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1072   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1073   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1074   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1075   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1076   case ARMISD::VDUP:          return "ARMISD::VDUP";
1077   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1078   case ARMISD::VEXT:          return "ARMISD::VEXT";
1079   case ARMISD::VREV64:        return "ARMISD::VREV64";
1080   case ARMISD::VREV32:        return "ARMISD::VREV32";
1081   case ARMISD::VREV16:        return "ARMISD::VREV16";
1082   case ARMISD::VZIP:          return "ARMISD::VZIP";
1083   case ARMISD::VUZP:          return "ARMISD::VUZP";
1084   case ARMISD::VTRN:          return "ARMISD::VTRN";
1085   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1086   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1087   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1088   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1089   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1090   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1091   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1092   case ARMISD::FMAX:          return "ARMISD::FMAX";
1093   case ARMISD::FMIN:          return "ARMISD::FMIN";
1094   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1095   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1096   case ARMISD::BFI:           return "ARMISD::BFI";
1097   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1098   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1099   case ARMISD::VBSL:          return "ARMISD::VBSL";
1100   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1101   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1102   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1103   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1104   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1105   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1106   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1107   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1108   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1109   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1110   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1111   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1112   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1113   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1114   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1115   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1116   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1117   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1118   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1119   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1120   }
1121 }
1122
1123 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1124   if (!VT.isVector()) return getPointerTy();
1125   return VT.changeVectorElementTypeToInteger();
1126 }
1127
1128 /// getRegClassFor - Return the register class that should be used for the
1129 /// specified value type.
1130 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1131   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1132   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1133   // load / store 4 to 8 consecutive D registers.
1134   if (Subtarget->hasNEON()) {
1135     if (VT == MVT::v4i64)
1136       return &ARM::QQPRRegClass;
1137     if (VT == MVT::v8i64)
1138       return &ARM::QQQQPRRegClass;
1139   }
1140   return TargetLowering::getRegClassFor(VT);
1141 }
1142
1143 // Create a fast isel object.
1144 FastISel *
1145 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1146                                   const TargetLibraryInfo *libInfo) const {
1147   return ARM::createFastISel(funcInfo, libInfo);
1148 }
1149
1150 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1151 /// be used for loads / stores from the global.
1152 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1153   return (Subtarget->isThumb1Only() ? 127 : 4095);
1154 }
1155
1156 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1157   unsigned NumVals = N->getNumValues();
1158   if (!NumVals)
1159     return Sched::RegPressure;
1160
1161   for (unsigned i = 0; i != NumVals; ++i) {
1162     EVT VT = N->getValueType(i);
1163     if (VT == MVT::Glue || VT == MVT::Other)
1164       continue;
1165     if (VT.isFloatingPoint() || VT.isVector())
1166       return Sched::ILP;
1167   }
1168
1169   if (!N->isMachineOpcode())
1170     return Sched::RegPressure;
1171
1172   // Load are scheduled for latency even if there instruction itinerary
1173   // is not available.
1174   const TargetInstrInfo *TII =
1175       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1176   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1177
1178   if (MCID.getNumDefs() == 0)
1179     return Sched::RegPressure;
1180   if (!Itins->isEmpty() &&
1181       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1182     return Sched::ILP;
1183
1184   return Sched::RegPressure;
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 // Lowering Code
1189 //===----------------------------------------------------------------------===//
1190
1191 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1192 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1193   switch (CC) {
1194   default: llvm_unreachable("Unknown condition code!");
1195   case ISD::SETNE:  return ARMCC::NE;
1196   case ISD::SETEQ:  return ARMCC::EQ;
1197   case ISD::SETGT:  return ARMCC::GT;
1198   case ISD::SETGE:  return ARMCC::GE;
1199   case ISD::SETLT:  return ARMCC::LT;
1200   case ISD::SETLE:  return ARMCC::LE;
1201   case ISD::SETUGT: return ARMCC::HI;
1202   case ISD::SETUGE: return ARMCC::HS;
1203   case ISD::SETULT: return ARMCC::LO;
1204   case ISD::SETULE: return ARMCC::LS;
1205   }
1206 }
1207
1208 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1209 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1210                         ARMCC::CondCodes &CondCode2) {
1211   CondCode2 = ARMCC::AL;
1212   switch (CC) {
1213   default: llvm_unreachable("Unknown FP condition!");
1214   case ISD::SETEQ:
1215   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1216   case ISD::SETGT:
1217   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1218   case ISD::SETGE:
1219   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1220   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1221   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1222   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1223   case ISD::SETO:   CondCode = ARMCC::VC; break;
1224   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1225   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1226   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1227   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1228   case ISD::SETLT:
1229   case ISD::SETULT: CondCode = ARMCC::LT; break;
1230   case ISD::SETLE:
1231   case ISD::SETULE: CondCode = ARMCC::LE; break;
1232   case ISD::SETNE:
1233   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1234   }
1235 }
1236
1237 //===----------------------------------------------------------------------===//
1238 //                      Calling Convention Implementation
1239 //===----------------------------------------------------------------------===//
1240
1241 #include "ARMGenCallingConv.inc"
1242
1243 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1244 /// account presence of floating point hardware and calling convention
1245 /// limitations, such as support for variadic functions.
1246 CallingConv::ID
1247 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1248                                            bool isVarArg) const {
1249   switch (CC) {
1250   default:
1251     llvm_unreachable("Unsupported calling convention");
1252   case CallingConv::ARM_AAPCS:
1253   case CallingConv::ARM_APCS:
1254   case CallingConv::GHC:
1255     return CC;
1256   case CallingConv::ARM_AAPCS_VFP:
1257     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1258   case CallingConv::C:
1259     if (!Subtarget->isAAPCS_ABI())
1260       return CallingConv::ARM_APCS;
1261     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1262              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1263              !isVarArg)
1264       return CallingConv::ARM_AAPCS_VFP;
1265     else
1266       return CallingConv::ARM_AAPCS;
1267   case CallingConv::Fast:
1268     if (!Subtarget->isAAPCS_ABI()) {
1269       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1270         return CallingConv::Fast;
1271       return CallingConv::ARM_APCS;
1272     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1273       return CallingConv::ARM_AAPCS_VFP;
1274     else
1275       return CallingConv::ARM_AAPCS;
1276   }
1277 }
1278
1279 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1280 /// CallingConvention.
1281 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1282                                                  bool Return,
1283                                                  bool isVarArg) const {
1284   switch (getEffectiveCallingConv(CC, isVarArg)) {
1285   default:
1286     llvm_unreachable("Unsupported calling convention");
1287   case CallingConv::ARM_APCS:
1288     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1289   case CallingConv::ARM_AAPCS:
1290     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1291   case CallingConv::ARM_AAPCS_VFP:
1292     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293   case CallingConv::Fast:
1294     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1295   case CallingConv::GHC:
1296     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1297   }
1298 }
1299
1300 /// LowerCallResult - Lower the result values of a call into the
1301 /// appropriate copies out of appropriate physical registers.
1302 SDValue
1303 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1304                                    CallingConv::ID CallConv, bool isVarArg,
1305                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1306                                    SDLoc dl, SelectionDAG &DAG,
1307                                    SmallVectorImpl<SDValue> &InVals,
1308                                    bool isThisReturn, SDValue ThisVal) const {
1309
1310   // Assign locations to each value returned by this call.
1311   SmallVector<CCValAssign, 16> RVLocs;
1312   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1313                     *DAG.getContext(), Call);
1314   CCInfo.AnalyzeCallResult(Ins,
1315                            CCAssignFnForNode(CallConv, /* Return*/ true,
1316                                              isVarArg));
1317
1318   // Copy all of the result registers out of their specified physreg.
1319   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1320     CCValAssign VA = RVLocs[i];
1321
1322     // Pass 'this' value directly from the argument to return value, to avoid
1323     // reg unit interference
1324     if (i == 0 && isThisReturn) {
1325       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1326              "unexpected return calling convention register assignment");
1327       InVals.push_back(ThisVal);
1328       continue;
1329     }
1330
1331     SDValue Val;
1332     if (VA.needsCustom()) {
1333       // Handle f64 or half of a v2f64.
1334       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1335                                       InFlag);
1336       Chain = Lo.getValue(1);
1337       InFlag = Lo.getValue(2);
1338       VA = RVLocs[++i]; // skip ahead to next loc
1339       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1340                                       InFlag);
1341       Chain = Hi.getValue(1);
1342       InFlag = Hi.getValue(2);
1343       if (!Subtarget->isLittle())
1344         std::swap (Lo, Hi);
1345       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1346
1347       if (VA.getLocVT() == MVT::v2f64) {
1348         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1349         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1350                           DAG.getConstant(0, MVT::i32));
1351
1352         VA = RVLocs[++i]; // skip ahead to next loc
1353         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1354         Chain = Lo.getValue(1);
1355         InFlag = Lo.getValue(2);
1356         VA = RVLocs[++i]; // skip ahead to next loc
1357         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1358         Chain = Hi.getValue(1);
1359         InFlag = Hi.getValue(2);
1360         if (!Subtarget->isLittle())
1361           std::swap (Lo, Hi);
1362         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1364                           DAG.getConstant(1, MVT::i32));
1365       }
1366     } else {
1367       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1368                                InFlag);
1369       Chain = Val.getValue(1);
1370       InFlag = Val.getValue(2);
1371     }
1372
1373     switch (VA.getLocInfo()) {
1374     default: llvm_unreachable("Unknown loc info!");
1375     case CCValAssign::Full: break;
1376     case CCValAssign::BCvt:
1377       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1378       break;
1379     }
1380
1381     InVals.push_back(Val);
1382   }
1383
1384   return Chain;
1385 }
1386
1387 /// LowerMemOpCallTo - Store the argument to the stack.
1388 SDValue
1389 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1390                                     SDValue StackPtr, SDValue Arg,
1391                                     SDLoc dl, SelectionDAG &DAG,
1392                                     const CCValAssign &VA,
1393                                     ISD::ArgFlagsTy Flags) const {
1394   unsigned LocMemOffset = VA.getLocMemOffset();
1395   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1396   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1397   return DAG.getStore(Chain, dl, Arg, PtrOff,
1398                       MachinePointerInfo::getStack(LocMemOffset),
1399                       false, false, 0);
1400 }
1401
1402 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1403                                          SDValue Chain, SDValue &Arg,
1404                                          RegsToPassVector &RegsToPass,
1405                                          CCValAssign &VA, CCValAssign &NextVA,
1406                                          SDValue &StackPtr,
1407                                          SmallVectorImpl<SDValue> &MemOpChains,
1408                                          ISD::ArgFlagsTy Flags) const {
1409
1410   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1411                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1412   unsigned id = Subtarget->isLittle() ? 0 : 1;
1413   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1414
1415   if (NextVA.isRegLoc())
1416     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1417   else {
1418     assert(NextVA.isMemLoc());
1419     if (!StackPtr.getNode())
1420       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1421
1422     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1423                                            dl, DAG, NextVA,
1424                                            Flags));
1425   }
1426 }
1427
1428 /// LowerCall - Lowering a call into a callseq_start <-
1429 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1430 /// nodes.
1431 SDValue
1432 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1433                              SmallVectorImpl<SDValue> &InVals) const {
1434   SelectionDAG &DAG                     = CLI.DAG;
1435   SDLoc &dl                          = CLI.DL;
1436   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1437   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1438   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1439   SDValue Chain                         = CLI.Chain;
1440   SDValue Callee                        = CLI.Callee;
1441   bool &isTailCall                      = CLI.IsTailCall;
1442   CallingConv::ID CallConv              = CLI.CallConv;
1443   bool doesNotRet                       = CLI.DoesNotReturn;
1444   bool isVarArg                         = CLI.IsVarArg;
1445
1446   MachineFunction &MF = DAG.getMachineFunction();
1447   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1448   bool isThisReturn   = false;
1449   bool isSibCall      = false;
1450
1451   // Disable tail calls if they're not supported.
1452   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1453     isTailCall = false;
1454
1455   if (isTailCall) {
1456     // Check if it's really possible to do a tail call.
1457     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1458                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1459                                                    Outs, OutVals, Ins, DAG);
1460     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1461       report_fatal_error("failed to perform tail call elimination on a call "
1462                          "site marked musttail");
1463     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1464     // detected sibcalls.
1465     if (isTailCall) {
1466       ++NumTailCalls;
1467       isSibCall = true;
1468     }
1469   }
1470
1471   // Analyze operands of the call, assigning locations to each operand.
1472   SmallVector<CCValAssign, 16> ArgLocs;
1473   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1474                     *DAG.getContext(), Call);
1475   CCInfo.AnalyzeCallOperands(Outs,
1476                              CCAssignFnForNode(CallConv, /* Return*/ false,
1477                                                isVarArg));
1478
1479   // Get a count of how many bytes are to be pushed on the stack.
1480   unsigned NumBytes = CCInfo.getNextStackOffset();
1481
1482   // For tail calls, memory operands are available in our caller's stack.
1483   if (isSibCall)
1484     NumBytes = 0;
1485
1486   // Adjust the stack pointer for the new arguments...
1487   // These operations are automatically eliminated by the prolog/epilog pass
1488   if (!isSibCall)
1489     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1490                                  dl);
1491
1492   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1493
1494   RegsToPassVector RegsToPass;
1495   SmallVector<SDValue, 8> MemOpChains;
1496
1497   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1498   // of tail call optimization, arguments are handled later.
1499   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1500        i != e;
1501        ++i, ++realArgIdx) {
1502     CCValAssign &VA = ArgLocs[i];
1503     SDValue Arg = OutVals[realArgIdx];
1504     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1505     bool isByVal = Flags.isByVal();
1506
1507     // Promote the value if needed.
1508     switch (VA.getLocInfo()) {
1509     default: llvm_unreachable("Unknown loc info!");
1510     case CCValAssign::Full: break;
1511     case CCValAssign::SExt:
1512       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1513       break;
1514     case CCValAssign::ZExt:
1515       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1516       break;
1517     case CCValAssign::AExt:
1518       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1519       break;
1520     case CCValAssign::BCvt:
1521       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1522       break;
1523     }
1524
1525     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1526     if (VA.needsCustom()) {
1527       if (VA.getLocVT() == MVT::v2f64) {
1528         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1529                                   DAG.getConstant(0, MVT::i32));
1530         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1531                                   DAG.getConstant(1, MVT::i32));
1532
1533         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1534                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1535
1536         VA = ArgLocs[++i]; // skip ahead to next loc
1537         if (VA.isRegLoc()) {
1538           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1539                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1540         } else {
1541           assert(VA.isMemLoc());
1542
1543           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1544                                                  dl, DAG, VA, Flags));
1545         }
1546       } else {
1547         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1548                          StackPtr, MemOpChains, Flags);
1549       }
1550     } else if (VA.isRegLoc()) {
1551       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1552         assert(VA.getLocVT() == MVT::i32 &&
1553                "unexpected calling convention register assignment");
1554         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1555                "unexpected use of 'returned'");
1556         isThisReturn = true;
1557       }
1558       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1559     } else if (isByVal) {
1560       assert(VA.isMemLoc());
1561       unsigned offset = 0;
1562
1563       // True if this byval aggregate will be split between registers
1564       // and memory.
1565       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1566       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1567
1568       if (CurByValIdx < ByValArgsCount) {
1569
1570         unsigned RegBegin, RegEnd;
1571         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1572
1573         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1574         unsigned int i, j;
1575         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1576           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1577           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1578           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1579                                      MachinePointerInfo(),
1580                                      false, false, false,
1581                                      DAG.InferPtrAlignment(AddArg));
1582           MemOpChains.push_back(Load.getValue(1));
1583           RegsToPass.push_back(std::make_pair(j, Load));
1584         }
1585
1586         // If parameter size outsides register area, "offset" value
1587         // helps us to calculate stack slot for remained part properly.
1588         offset = RegEnd - RegBegin;
1589
1590         CCInfo.nextInRegsParam();
1591       }
1592
1593       if (Flags.getByValSize() > 4*offset) {
1594         unsigned LocMemOffset = VA.getLocMemOffset();
1595         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1596         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1597                                   StkPtrOff);
1598         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1599         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1600         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1601                                            MVT::i32);
1602         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1603
1604         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1605         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1606         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1607                                           Ops));
1608       }
1609     } else if (!isSibCall) {
1610       assert(VA.isMemLoc());
1611
1612       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1613                                              dl, DAG, VA, Flags));
1614     }
1615   }
1616
1617   if (!MemOpChains.empty())
1618     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1619
1620   // Build a sequence of copy-to-reg nodes chained together with token chain
1621   // and flag operands which copy the outgoing args into the appropriate regs.
1622   SDValue InFlag;
1623   // Tail call byval lowering might overwrite argument registers so in case of
1624   // tail call optimization the copies to registers are lowered later.
1625   if (!isTailCall)
1626     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1627       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1628                                RegsToPass[i].second, InFlag);
1629       InFlag = Chain.getValue(1);
1630     }
1631
1632   // For tail calls lower the arguments to the 'real' stack slot.
1633   if (isTailCall) {
1634     // Force all the incoming stack arguments to be loaded from the stack
1635     // before any new outgoing arguments are stored to the stack, because the
1636     // outgoing stack slots may alias the incoming argument stack slots, and
1637     // the alias isn't otherwise explicit. This is slightly more conservative
1638     // than necessary, because it means that each store effectively depends
1639     // on every argument instead of just those arguments it would clobber.
1640
1641     // Do not flag preceding copytoreg stuff together with the following stuff.
1642     InFlag = SDValue();
1643     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1644       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1645                                RegsToPass[i].second, InFlag);
1646       InFlag = Chain.getValue(1);
1647     }
1648     InFlag = SDValue();
1649   }
1650
1651   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1652   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1653   // node so that legalize doesn't hack it.
1654   bool isDirect = false;
1655   bool isARMFunc = false;
1656   bool isLocalARMFunc = false;
1657   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1658
1659   if (EnableARMLongCalls) {
1660     assert((Subtarget->isTargetWindows() ||
1661             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1662            "long-calls with non-static relocation model!");
1663     // Handle a global address or an external symbol. If it's not one of
1664     // those, the target's already in a register, so we don't need to do
1665     // anything extra.
1666     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1667       const GlobalValue *GV = G->getGlobal();
1668       // Create a constant pool entry for the callee address
1669       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1670       ARMConstantPoolValue *CPV =
1671         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1672
1673       // Get the address of the callee into a register
1674       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1675       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1676       Callee = DAG.getLoad(getPointerTy(), dl,
1677                            DAG.getEntryNode(), CPAddr,
1678                            MachinePointerInfo::getConstantPool(),
1679                            false, false, false, 0);
1680     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1681       const char *Sym = S->getSymbol();
1682
1683       // Create a constant pool entry for the callee address
1684       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1685       ARMConstantPoolValue *CPV =
1686         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1687                                       ARMPCLabelIndex, 0);
1688       // Get the address of the callee into a register
1689       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1690       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1691       Callee = DAG.getLoad(getPointerTy(), dl,
1692                            DAG.getEntryNode(), CPAddr,
1693                            MachinePointerInfo::getConstantPool(),
1694                            false, false, false, 0);
1695     }
1696   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1697     const GlobalValue *GV = G->getGlobal();
1698     isDirect = true;
1699     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1700     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1701                    getTargetMachine().getRelocationModel() != Reloc::Static;
1702     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1703     // ARM call to a local ARM function is predicable.
1704     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1705     // tBX takes a register source operand.
1706     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1707       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1708       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1709                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1710                                                       0, ARMII::MO_NONLAZY));
1711       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1712                            MachinePointerInfo::getGOT(), false, false, true, 0);
1713     } else if (Subtarget->isTargetCOFF()) {
1714       assert(Subtarget->isTargetWindows() &&
1715              "Windows is the only supported COFF target");
1716       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1717                                  ? ARMII::MO_DLLIMPORT
1718                                  : ARMII::MO_NO_FLAG;
1719       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1720                                           TargetFlags);
1721       if (GV->hasDLLImportStorageClass())
1722         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1723                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1724                                          Callee), MachinePointerInfo::getGOT(),
1725                              false, false, false, 0);
1726     } else {
1727       // On ELF targets for PIC code, direct calls should go through the PLT
1728       unsigned OpFlags = 0;
1729       if (Subtarget->isTargetELF() &&
1730           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1731         OpFlags = ARMII::MO_PLT;
1732       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1733     }
1734   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1735     isDirect = true;
1736     bool isStub = Subtarget->isTargetMachO() &&
1737                   getTargetMachine().getRelocationModel() != Reloc::Static;
1738     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1739     // tBX takes a register source operand.
1740     const char *Sym = S->getSymbol();
1741     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1742       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1743       ARMConstantPoolValue *CPV =
1744         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1745                                       ARMPCLabelIndex, 4);
1746       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1747       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1748       Callee = DAG.getLoad(getPointerTy(), dl,
1749                            DAG.getEntryNode(), CPAddr,
1750                            MachinePointerInfo::getConstantPool(),
1751                            false, false, false, 0);
1752       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1753       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1754                            getPointerTy(), Callee, PICLabel);
1755     } else {
1756       unsigned OpFlags = 0;
1757       // On ELF targets for PIC code, direct calls should go through the PLT
1758       if (Subtarget->isTargetELF() &&
1759                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1760         OpFlags = ARMII::MO_PLT;
1761       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1762     }
1763   }
1764
1765   // FIXME: handle tail calls differently.
1766   unsigned CallOpc;
1767   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1768       AttributeSet::FunctionIndex, Attribute::MinSize);
1769   if (Subtarget->isThumb()) {
1770     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1771       CallOpc = ARMISD::CALL_NOLINK;
1772     else
1773       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1774   } else {
1775     if (!isDirect && !Subtarget->hasV5TOps())
1776       CallOpc = ARMISD::CALL_NOLINK;
1777     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1778                // Emit regular call when code size is the priority
1779                !HasMinSizeAttr)
1780       // "mov lr, pc; b _foo" to avoid confusing the RSP
1781       CallOpc = ARMISD::CALL_NOLINK;
1782     else
1783       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1784   }
1785
1786   std::vector<SDValue> Ops;
1787   Ops.push_back(Chain);
1788   Ops.push_back(Callee);
1789
1790   // Add argument registers to the end of the list so that they are known live
1791   // into the call.
1792   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1793     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1794                                   RegsToPass[i].second.getValueType()));
1795
1796   // Add a register mask operand representing the call-preserved registers.
1797   if (!isTailCall) {
1798     const uint32_t *Mask;
1799     const TargetRegisterInfo *TRI =
1800         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1801     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1802     if (isThisReturn) {
1803       // For 'this' returns, use the R0-preserving mask if applicable
1804       Mask = ARI->getThisReturnPreservedMask(CallConv);
1805       if (!Mask) {
1806         // Set isThisReturn to false if the calling convention is not one that
1807         // allows 'returned' to be modeled in this way, so LowerCallResult does
1808         // not try to pass 'this' straight through
1809         isThisReturn = false;
1810         Mask = ARI->getCallPreservedMask(CallConv);
1811       }
1812     } else
1813       Mask = ARI->getCallPreservedMask(CallConv);
1814
1815     assert(Mask && "Missing call preserved mask for calling convention");
1816     Ops.push_back(DAG.getRegisterMask(Mask));
1817   }
1818
1819   if (InFlag.getNode())
1820     Ops.push_back(InFlag);
1821
1822   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1823   if (isTailCall)
1824     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1825
1826   // Returns a chain and a flag for retval copy to use.
1827   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1828   InFlag = Chain.getValue(1);
1829
1830   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1831                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1832   if (!Ins.empty())
1833     InFlag = Chain.getValue(1);
1834
1835   // Handle result values, copying them out of physregs into vregs that we
1836   // return.
1837   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1838                          InVals, isThisReturn,
1839                          isThisReturn ? OutVals[0] : SDValue());
1840 }
1841
1842 /// HandleByVal - Every parameter *after* a byval parameter is passed
1843 /// on the stack.  Remember the next parameter register to allocate,
1844 /// and then confiscate the rest of the parameter registers to insure
1845 /// this.
1846 void
1847 ARMTargetLowering::HandleByVal(
1848     CCState *State, unsigned &size, unsigned Align) const {
1849   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1850   assert((State->getCallOrPrologue() == Prologue ||
1851           State->getCallOrPrologue() == Call) &&
1852          "unhandled ParmContext");
1853
1854   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1855     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1856       unsigned AlignInRegs = Align / 4;
1857       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1858       for (unsigned i = 0; i < Waste; ++i)
1859         reg = State->AllocateReg(GPRArgRegs, 4);
1860     }
1861     if (reg != 0) {
1862       unsigned excess = 4 * (ARM::R4 - reg);
1863
1864       // Special case when NSAA != SP and parameter size greater than size of
1865       // all remained GPR regs. In that case we can't split parameter, we must
1866       // send it to stack. We also must set NCRN to R4, so waste all
1867       // remained registers.
1868       const unsigned NSAAOffset = State->getNextStackOffset();
1869       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1870         while (State->AllocateReg(GPRArgRegs, 4))
1871           ;
1872         return;
1873       }
1874
1875       // First register for byval parameter is the first register that wasn't
1876       // allocated before this method call, so it would be "reg".
1877       // If parameter is small enough to be saved in range [reg, r4), then
1878       // the end (first after last) register would be reg + param-size-in-regs,
1879       // else parameter would be splitted between registers and stack,
1880       // end register would be r4 in this case.
1881       unsigned ByValRegBegin = reg;
1882       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1883       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1884       // Note, first register is allocated in the beginning of function already,
1885       // allocate remained amount of registers we need.
1886       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1887         State->AllocateReg(GPRArgRegs, 4);
1888       // A byval parameter that is split between registers and memory needs its
1889       // size truncated here.
1890       // In the case where the entire structure fits in registers, we set the
1891       // size in memory to zero.
1892       if (size < excess)
1893         size = 0;
1894       else
1895         size -= excess;
1896     }
1897   }
1898 }
1899
1900 /// MatchingStackOffset - Return true if the given stack call argument is
1901 /// already available in the same position (relatively) of the caller's
1902 /// incoming argument stack.
1903 static
1904 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1905                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1906                          const TargetInstrInfo *TII) {
1907   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1908   int FI = INT_MAX;
1909   if (Arg.getOpcode() == ISD::CopyFromReg) {
1910     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1911     if (!TargetRegisterInfo::isVirtualRegister(VR))
1912       return false;
1913     MachineInstr *Def = MRI->getVRegDef(VR);
1914     if (!Def)
1915       return false;
1916     if (!Flags.isByVal()) {
1917       if (!TII->isLoadFromStackSlot(Def, FI))
1918         return false;
1919     } else {
1920       return false;
1921     }
1922   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1923     if (Flags.isByVal())
1924       // ByVal argument is passed in as a pointer but it's now being
1925       // dereferenced. e.g.
1926       // define @foo(%struct.X* %A) {
1927       //   tail call @bar(%struct.X* byval %A)
1928       // }
1929       return false;
1930     SDValue Ptr = Ld->getBasePtr();
1931     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1932     if (!FINode)
1933       return false;
1934     FI = FINode->getIndex();
1935   } else
1936     return false;
1937
1938   assert(FI != INT_MAX);
1939   if (!MFI->isFixedObjectIndex(FI))
1940     return false;
1941   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1942 }
1943
1944 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1945 /// for tail call optimization. Targets which want to do tail call
1946 /// optimization should implement this function.
1947 bool
1948 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1949                                                      CallingConv::ID CalleeCC,
1950                                                      bool isVarArg,
1951                                                      bool isCalleeStructRet,
1952                                                      bool isCallerStructRet,
1953                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1954                                     const SmallVectorImpl<SDValue> &OutVals,
1955                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1956                                                      SelectionDAG& DAG) const {
1957   const Function *CallerF = DAG.getMachineFunction().getFunction();
1958   CallingConv::ID CallerCC = CallerF->getCallingConv();
1959   bool CCMatch = CallerCC == CalleeCC;
1960
1961   // Look for obvious safe cases to perform tail call optimization that do not
1962   // require ABI changes. This is what gcc calls sibcall.
1963
1964   // Do not sibcall optimize vararg calls unless the call site is not passing
1965   // any arguments.
1966   if (isVarArg && !Outs.empty())
1967     return false;
1968
1969   // Exception-handling functions need a special set of instructions to indicate
1970   // a return to the hardware. Tail-calling another function would probably
1971   // break this.
1972   if (CallerF->hasFnAttribute("interrupt"))
1973     return false;
1974
1975   // Also avoid sibcall optimization if either caller or callee uses struct
1976   // return semantics.
1977   if (isCalleeStructRet || isCallerStructRet)
1978     return false;
1979
1980   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1981   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1982   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1983   // support in the assembler and linker to be used. This would need to be
1984   // fixed to fully support tail calls in Thumb1.
1985   //
1986   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1987   // LR.  This means if we need to reload LR, it takes an extra instructions,
1988   // which outweighs the value of the tail call; but here we don't know yet
1989   // whether LR is going to be used.  Probably the right approach is to
1990   // generate the tail call here and turn it back into CALL/RET in
1991   // emitEpilogue if LR is used.
1992
1993   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1994   // but we need to make sure there are enough registers; the only valid
1995   // registers are the 4 used for parameters.  We don't currently do this
1996   // case.
1997   if (Subtarget->isThumb1Only())
1998     return false;
1999
2000   // Externally-defined functions with weak linkage should not be
2001   // tail-called on ARM when the OS does not support dynamic
2002   // pre-emption of symbols, as the AAELF spec requires normal calls
2003   // to undefined weak functions to be replaced with a NOP or jump to the
2004   // next instruction. The behaviour of branch instructions in this
2005   // situation (as used for tail calls) is implementation-defined, so we
2006   // cannot rely on the linker replacing the tail call with a return.
2007   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2008     const GlobalValue *GV = G->getGlobal();
2009     if (GV->hasExternalWeakLinkage())
2010       return false;
2011   }
2012
2013   // If the calling conventions do not match, then we'd better make sure the
2014   // results are returned in the same way as what the caller expects.
2015   if (!CCMatch) {
2016     SmallVector<CCValAssign, 16> RVLocs1;
2017     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2018                        *DAG.getContext(), Call);
2019     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2020
2021     SmallVector<CCValAssign, 16> RVLocs2;
2022     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2023                        *DAG.getContext(), Call);
2024     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2025
2026     if (RVLocs1.size() != RVLocs2.size())
2027       return false;
2028     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2029       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2030         return false;
2031       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2032         return false;
2033       if (RVLocs1[i].isRegLoc()) {
2034         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2035           return false;
2036       } else {
2037         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2038           return false;
2039       }
2040     }
2041   }
2042
2043   // If Caller's vararg or byval argument has been split between registers and
2044   // stack, do not perform tail call, since part of the argument is in caller's
2045   // local frame.
2046   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2047                                       getInfo<ARMFunctionInfo>();
2048   if (AFI_Caller->getArgRegsSaveSize())
2049     return false;
2050
2051   // If the callee takes no arguments then go on to check the results of the
2052   // call.
2053   if (!Outs.empty()) {
2054     // Check if stack adjustment is needed. For now, do not do this if any
2055     // argument is passed on the stack.
2056     SmallVector<CCValAssign, 16> ArgLocs;
2057     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2058                       *DAG.getContext(), Call);
2059     CCInfo.AnalyzeCallOperands(Outs,
2060                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2061     if (CCInfo.getNextStackOffset()) {
2062       MachineFunction &MF = DAG.getMachineFunction();
2063
2064       // Check if the arguments are already laid out in the right way as
2065       // the caller's fixed stack objects.
2066       MachineFrameInfo *MFI = MF.getFrameInfo();
2067       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2068       const TargetInstrInfo *TII =
2069           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2070       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2071            i != e;
2072            ++i, ++realArgIdx) {
2073         CCValAssign &VA = ArgLocs[i];
2074         EVT RegVT = VA.getLocVT();
2075         SDValue Arg = OutVals[realArgIdx];
2076         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2077         if (VA.getLocInfo() == CCValAssign::Indirect)
2078           return false;
2079         if (VA.needsCustom()) {
2080           // f64 and vector types are split into multiple registers or
2081           // register/stack-slot combinations.  The types will not match
2082           // the registers; give up on memory f64 refs until we figure
2083           // out what to do about this.
2084           if (!VA.isRegLoc())
2085             return false;
2086           if (!ArgLocs[++i].isRegLoc())
2087             return false;
2088           if (RegVT == MVT::v2f64) {
2089             if (!ArgLocs[++i].isRegLoc())
2090               return false;
2091             if (!ArgLocs[++i].isRegLoc())
2092               return false;
2093           }
2094         } else if (!VA.isRegLoc()) {
2095           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2096                                    MFI, MRI, TII))
2097             return false;
2098         }
2099       }
2100     }
2101   }
2102
2103   return true;
2104 }
2105
2106 bool
2107 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2108                                   MachineFunction &MF, bool isVarArg,
2109                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2110                                   LLVMContext &Context) const {
2111   SmallVector<CCValAssign, 16> RVLocs;
2112   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2113   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2114                                                     isVarArg));
2115 }
2116
2117 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2118                                     SDLoc DL, SelectionDAG &DAG) {
2119   const MachineFunction &MF = DAG.getMachineFunction();
2120   const Function *F = MF.getFunction();
2121
2122   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2123
2124   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2125   // version of the "preferred return address". These offsets affect the return
2126   // instruction if this is a return from PL1 without hypervisor extensions.
2127   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2128   //    SWI:     0      "subs pc, lr, #0"
2129   //    ABORT:   +4     "subs pc, lr, #4"
2130   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2131   // UNDEF varies depending on where the exception came from ARM or Thumb
2132   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2133
2134   int64_t LROffset;
2135   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2136       IntKind == "ABORT")
2137     LROffset = 4;
2138   else if (IntKind == "SWI" || IntKind == "UNDEF")
2139     LROffset = 0;
2140   else
2141     report_fatal_error("Unsupported interrupt attribute. If present, value "
2142                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2143
2144   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2145
2146   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2147 }
2148
2149 SDValue
2150 ARMTargetLowering::LowerReturn(SDValue Chain,
2151                                CallingConv::ID CallConv, bool isVarArg,
2152                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2153                                const SmallVectorImpl<SDValue> &OutVals,
2154                                SDLoc dl, SelectionDAG &DAG) const {
2155
2156   // CCValAssign - represent the assignment of the return value to a location.
2157   SmallVector<CCValAssign, 16> RVLocs;
2158
2159   // CCState - Info about the registers and stack slots.
2160   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2161                     *DAG.getContext(), Call);
2162
2163   // Analyze outgoing return values.
2164   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2165                                                isVarArg));
2166
2167   SDValue Flag;
2168   SmallVector<SDValue, 4> RetOps;
2169   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2170   bool isLittleEndian = Subtarget->isLittle();
2171
2172   MachineFunction &MF = DAG.getMachineFunction();
2173   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2174   AFI->setReturnRegsCount(RVLocs.size());
2175
2176   // Copy the result values into the output registers.
2177   for (unsigned i = 0, realRVLocIdx = 0;
2178        i != RVLocs.size();
2179        ++i, ++realRVLocIdx) {
2180     CCValAssign &VA = RVLocs[i];
2181     assert(VA.isRegLoc() && "Can only return in registers!");
2182
2183     SDValue Arg = OutVals[realRVLocIdx];
2184
2185     switch (VA.getLocInfo()) {
2186     default: llvm_unreachable("Unknown loc info!");
2187     case CCValAssign::Full: break;
2188     case CCValAssign::BCvt:
2189       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2190       break;
2191     }
2192
2193     if (VA.needsCustom()) {
2194       if (VA.getLocVT() == MVT::v2f64) {
2195         // Extract the first half and return it in two registers.
2196         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2197                                    DAG.getConstant(0, MVT::i32));
2198         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2199                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2200
2201         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2202                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2203                                  Flag);
2204         Flag = Chain.getValue(1);
2205         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2206         VA = RVLocs[++i]; // skip ahead to next loc
2207         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2208                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2209                                  Flag);
2210         Flag = Chain.getValue(1);
2211         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2212         VA = RVLocs[++i]; // skip ahead to next loc
2213
2214         // Extract the 2nd half and fall through to handle it as an f64 value.
2215         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2216                           DAG.getConstant(1, MVT::i32));
2217       }
2218       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2219       // available.
2220       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2221                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2222       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2223                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2224                                Flag);
2225       Flag = Chain.getValue(1);
2226       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2227       VA = RVLocs[++i]; // skip ahead to next loc
2228       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2229                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2230                                Flag);
2231     } else
2232       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2233
2234     // Guarantee that all emitted copies are
2235     // stuck together, avoiding something bad.
2236     Flag = Chain.getValue(1);
2237     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2238   }
2239
2240   // Update chain and glue.
2241   RetOps[0] = Chain;
2242   if (Flag.getNode())
2243     RetOps.push_back(Flag);
2244
2245   // CPUs which aren't M-class use a special sequence to return from
2246   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2247   // though we use "subs pc, lr, #N").
2248   //
2249   // M-class CPUs actually use a normal return sequence with a special
2250   // (hardware-provided) value in LR, so the normal code path works.
2251   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2252       !Subtarget->isMClass()) {
2253     if (Subtarget->isThumb1Only())
2254       report_fatal_error("interrupt attribute is not supported in Thumb1");
2255     return LowerInterruptReturn(RetOps, dl, DAG);
2256   }
2257
2258   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2259 }
2260
2261 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2262   if (N->getNumValues() != 1)
2263     return false;
2264   if (!N->hasNUsesOfValue(1, 0))
2265     return false;
2266
2267   SDValue TCChain = Chain;
2268   SDNode *Copy = *N->use_begin();
2269   if (Copy->getOpcode() == ISD::CopyToReg) {
2270     // If the copy has a glue operand, we conservatively assume it isn't safe to
2271     // perform a tail call.
2272     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2273       return false;
2274     TCChain = Copy->getOperand(0);
2275   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2276     SDNode *VMov = Copy;
2277     // f64 returned in a pair of GPRs.
2278     SmallPtrSet<SDNode*, 2> Copies;
2279     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2280          UI != UE; ++UI) {
2281       if (UI->getOpcode() != ISD::CopyToReg)
2282         return false;
2283       Copies.insert(*UI);
2284     }
2285     if (Copies.size() > 2)
2286       return false;
2287
2288     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2289          UI != UE; ++UI) {
2290       SDValue UseChain = UI->getOperand(0);
2291       if (Copies.count(UseChain.getNode()))
2292         // Second CopyToReg
2293         Copy = *UI;
2294       else
2295         // First CopyToReg
2296         TCChain = UseChain;
2297     }
2298   } else if (Copy->getOpcode() == ISD::BITCAST) {
2299     // f32 returned in a single GPR.
2300     if (!Copy->hasOneUse())
2301       return false;
2302     Copy = *Copy->use_begin();
2303     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2304       return false;
2305     TCChain = Copy->getOperand(0);
2306   } else {
2307     return false;
2308   }
2309
2310   bool HasRet = false;
2311   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2312        UI != UE; ++UI) {
2313     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2314         UI->getOpcode() != ARMISD::INTRET_FLAG)
2315       return false;
2316     HasRet = true;
2317   }
2318
2319   if (!HasRet)
2320     return false;
2321
2322   Chain = TCChain;
2323   return true;
2324 }
2325
2326 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2327   if (!Subtarget->supportsTailCall())
2328     return false;
2329
2330   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2331     return false;
2332
2333   return !Subtarget->isThumb1Only();
2334 }
2335
2336 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2337 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2338 // one of the above mentioned nodes. It has to be wrapped because otherwise
2339 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2340 // be used to form addressing mode. These wrapped nodes will be selected
2341 // into MOVi.
2342 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2343   EVT PtrVT = Op.getValueType();
2344   // FIXME there is no actual debug info here
2345   SDLoc dl(Op);
2346   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2347   SDValue Res;
2348   if (CP->isMachineConstantPoolEntry())
2349     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2350                                     CP->getAlignment());
2351   else
2352     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2353                                     CP->getAlignment());
2354   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2355 }
2356
2357 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2358   return MachineJumpTableInfo::EK_Inline;
2359 }
2360
2361 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2362                                              SelectionDAG &DAG) const {
2363   MachineFunction &MF = DAG.getMachineFunction();
2364   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2365   unsigned ARMPCLabelIndex = 0;
2366   SDLoc DL(Op);
2367   EVT PtrVT = getPointerTy();
2368   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2369   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2370   SDValue CPAddr;
2371   if (RelocM == Reloc::Static) {
2372     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2373   } else {
2374     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2375     ARMPCLabelIndex = AFI->createPICLabelUId();
2376     ARMConstantPoolValue *CPV =
2377       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2378                                       ARMCP::CPBlockAddress, PCAdj);
2379     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2380   }
2381   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2382   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2383                                MachinePointerInfo::getConstantPool(),
2384                                false, false, false, 0);
2385   if (RelocM == Reloc::Static)
2386     return Result;
2387   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2388   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2389 }
2390
2391 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2392 SDValue
2393 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2394                                                  SelectionDAG &DAG) const {
2395   SDLoc dl(GA);
2396   EVT PtrVT = getPointerTy();
2397   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2398   MachineFunction &MF = DAG.getMachineFunction();
2399   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2400   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2401   ARMConstantPoolValue *CPV =
2402     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2403                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2404   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2405   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2406   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2407                          MachinePointerInfo::getConstantPool(),
2408                          false, false, false, 0);
2409   SDValue Chain = Argument.getValue(1);
2410
2411   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2412   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2413
2414   // call __tls_get_addr.
2415   ArgListTy Args;
2416   ArgListEntry Entry;
2417   Entry.Node = Argument;
2418   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2419   Args.push_back(Entry);
2420
2421   // FIXME: is there useful debug info available here?
2422   TargetLowering::CallLoweringInfo CLI(DAG);
2423   CLI.setDebugLoc(dl).setChain(Chain)
2424     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2425                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2426                0);
2427
2428   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2429   return CallResult.first;
2430 }
2431
2432 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2433 // "local exec" model.
2434 SDValue
2435 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2436                                         SelectionDAG &DAG,
2437                                         TLSModel::Model model) const {
2438   const GlobalValue *GV = GA->getGlobal();
2439   SDLoc dl(GA);
2440   SDValue Offset;
2441   SDValue Chain = DAG.getEntryNode();
2442   EVT PtrVT = getPointerTy();
2443   // Get the Thread Pointer
2444   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2445
2446   if (model == TLSModel::InitialExec) {
2447     MachineFunction &MF = DAG.getMachineFunction();
2448     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2449     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2450     // Initial exec model.
2451     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2452     ARMConstantPoolValue *CPV =
2453       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2454                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2455                                       true);
2456     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2457     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2458     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2459                          MachinePointerInfo::getConstantPool(),
2460                          false, false, false, 0);
2461     Chain = Offset.getValue(1);
2462
2463     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2464     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2465
2466     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2467                          MachinePointerInfo::getConstantPool(),
2468                          false, false, false, 0);
2469   } else {
2470     // local exec model
2471     assert(model == TLSModel::LocalExec);
2472     ARMConstantPoolValue *CPV =
2473       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2474     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2475     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2476     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2477                          MachinePointerInfo::getConstantPool(),
2478                          false, false, false, 0);
2479   }
2480
2481   // The address of the thread local variable is the add of the thread
2482   // pointer with the offset of the variable.
2483   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2484 }
2485
2486 SDValue
2487 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2488   // TODO: implement the "local dynamic" model
2489   assert(Subtarget->isTargetELF() &&
2490          "TLS not implemented for non-ELF targets");
2491   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2492
2493   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2494
2495   switch (model) {
2496     case TLSModel::GeneralDynamic:
2497     case TLSModel::LocalDynamic:
2498       return LowerToTLSGeneralDynamicModel(GA, DAG);
2499     case TLSModel::InitialExec:
2500     case TLSModel::LocalExec:
2501       return LowerToTLSExecModels(GA, DAG, model);
2502   }
2503   llvm_unreachable("bogus TLS model");
2504 }
2505
2506 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2507                                                  SelectionDAG &DAG) const {
2508   EVT PtrVT = getPointerTy();
2509   SDLoc dl(Op);
2510   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2511   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2512     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2513     ARMConstantPoolValue *CPV =
2514       ARMConstantPoolConstant::Create(GV,
2515                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2516     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2517     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2518     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2519                                  CPAddr,
2520                                  MachinePointerInfo::getConstantPool(),
2521                                  false, false, false, 0);
2522     SDValue Chain = Result.getValue(1);
2523     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2524     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2525     if (!UseGOTOFF)
2526       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2527                            MachinePointerInfo::getGOT(),
2528                            false, false, false, 0);
2529     return Result;
2530   }
2531
2532   // If we have T2 ops, we can materialize the address directly via movt/movw
2533   // pair. This is always cheaper.
2534   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2535     ++NumMovwMovt;
2536     // FIXME: Once remat is capable of dealing with instructions with register
2537     // operands, expand this into two nodes.
2538     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2539                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2540   } else {
2541     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2542     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2543     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2544                        MachinePointerInfo::getConstantPool(),
2545                        false, false, false, 0);
2546   }
2547 }
2548
2549 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2550                                                     SelectionDAG &DAG) const {
2551   EVT PtrVT = getPointerTy();
2552   SDLoc dl(Op);
2553   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2554   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2555
2556   if (Subtarget->useMovt(DAG.getMachineFunction()))
2557     ++NumMovwMovt;
2558
2559   // FIXME: Once remat is capable of dealing with instructions with register
2560   // operands, expand this into multiple nodes
2561   unsigned Wrapper =
2562       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2563
2564   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2565   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2566
2567   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2568     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2569                          MachinePointerInfo::getGOT(), false, false, false, 0);
2570   return Result;
2571 }
2572
2573 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2574                                                      SelectionDAG &DAG) const {
2575   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2576   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2577          "Windows on ARM expects to use movw/movt");
2578
2579   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2580   const ARMII::TOF TargetFlags =
2581     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2582   EVT PtrVT = getPointerTy();
2583   SDValue Result;
2584   SDLoc DL(Op);
2585
2586   ++NumMovwMovt;
2587
2588   // FIXME: Once remat is capable of dealing with instructions with register
2589   // operands, expand this into two nodes.
2590   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2591                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2592                                                   TargetFlags));
2593   if (GV->hasDLLImportStorageClass())
2594     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2595                          MachinePointerInfo::getGOT(), false, false, false, 0);
2596   return Result;
2597 }
2598
2599 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2600                                                     SelectionDAG &DAG) const {
2601   assert(Subtarget->isTargetELF() &&
2602          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2603   MachineFunction &MF = DAG.getMachineFunction();
2604   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2605   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2606   EVT PtrVT = getPointerTy();
2607   SDLoc dl(Op);
2608   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2609   ARMConstantPoolValue *CPV =
2610     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2611                                   ARMPCLabelIndex, PCAdj);
2612   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2613   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2614   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2615                                MachinePointerInfo::getConstantPool(),
2616                                false, false, false, 0);
2617   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2618   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2619 }
2620
2621 SDValue
2622 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2623   SDLoc dl(Op);
2624   SDValue Val = DAG.getConstant(0, MVT::i32);
2625   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2626                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2627                      Op.getOperand(1), Val);
2628 }
2629
2630 SDValue
2631 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2632   SDLoc dl(Op);
2633   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2634                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2635 }
2636
2637 SDValue
2638 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2639                                           const ARMSubtarget *Subtarget) const {
2640   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2641   SDLoc dl(Op);
2642   switch (IntNo) {
2643   default: return SDValue();    // Don't custom lower most intrinsics.
2644   case Intrinsic::arm_rbit: {
2645     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2646            "RBIT intrinsic must have i32 type!");
2647     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2648   }
2649   case Intrinsic::arm_thread_pointer: {
2650     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2651     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2652   }
2653   case Intrinsic::eh_sjlj_lsda: {
2654     MachineFunction &MF = DAG.getMachineFunction();
2655     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2656     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2657     EVT PtrVT = getPointerTy();
2658     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2659     SDValue CPAddr;
2660     unsigned PCAdj = (RelocM != Reloc::PIC_)
2661       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2662     ARMConstantPoolValue *CPV =
2663       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2664                                       ARMCP::CPLSDA, PCAdj);
2665     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2666     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2667     SDValue Result =
2668       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2669                   MachinePointerInfo::getConstantPool(),
2670                   false, false, false, 0);
2671
2672     if (RelocM == Reloc::PIC_) {
2673       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2674       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2675     }
2676     return Result;
2677   }
2678   case Intrinsic::arm_neon_vmulls:
2679   case Intrinsic::arm_neon_vmullu: {
2680     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2681       ? ARMISD::VMULLs : ARMISD::VMULLu;
2682     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2683                        Op.getOperand(1), Op.getOperand(2));
2684   }
2685   }
2686 }
2687
2688 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2689                                  const ARMSubtarget *Subtarget) {
2690   // FIXME: handle "fence singlethread" more efficiently.
2691   SDLoc dl(Op);
2692   if (!Subtarget->hasDataBarrier()) {
2693     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2694     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2695     // here.
2696     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2697            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2698     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2699                        DAG.getConstant(0, MVT::i32));
2700   }
2701
2702   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2703   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2704   unsigned Domain = ARM_MB::ISH;
2705   if (Subtarget->isMClass()) {
2706     // Only a full system barrier exists in the M-class architectures.
2707     Domain = ARM_MB::SY;
2708   } else if (Subtarget->isSwift() && Ord == Release) {
2709     // Swift happens to implement ISHST barriers in a way that's compatible with
2710     // Release semantics but weaker than ISH so we'd be fools not to use
2711     // it. Beware: other processors probably don't!
2712     Domain = ARM_MB::ISHST;
2713   }
2714
2715   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2716                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2717                      DAG.getConstant(Domain, MVT::i32));
2718 }
2719
2720 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2721                              const ARMSubtarget *Subtarget) {
2722   // ARM pre v5TE and Thumb1 does not have preload instructions.
2723   if (!(Subtarget->isThumb2() ||
2724         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2725     // Just preserve the chain.
2726     return Op.getOperand(0);
2727
2728   SDLoc dl(Op);
2729   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2730   if (!isRead &&
2731       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2732     // ARMv7 with MP extension has PLDW.
2733     return Op.getOperand(0);
2734
2735   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2736   if (Subtarget->isThumb()) {
2737     // Invert the bits.
2738     isRead = ~isRead & 1;
2739     isData = ~isData & 1;
2740   }
2741
2742   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2743                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2744                      DAG.getConstant(isData, MVT::i32));
2745 }
2746
2747 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2748   MachineFunction &MF = DAG.getMachineFunction();
2749   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2750
2751   // vastart just stores the address of the VarArgsFrameIndex slot into the
2752   // memory location argument.
2753   SDLoc dl(Op);
2754   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2755   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2756   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2757   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2758                       MachinePointerInfo(SV), false, false, 0);
2759 }
2760
2761 SDValue
2762 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2763                                         SDValue &Root, SelectionDAG &DAG,
2764                                         SDLoc dl) const {
2765   MachineFunction &MF = DAG.getMachineFunction();
2766   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2767
2768   const TargetRegisterClass *RC;
2769   if (AFI->isThumb1OnlyFunction())
2770     RC = &ARM::tGPRRegClass;
2771   else
2772     RC = &ARM::GPRRegClass;
2773
2774   // Transform the arguments stored in physical registers into virtual ones.
2775   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2776   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2777
2778   SDValue ArgValue2;
2779   if (NextVA.isMemLoc()) {
2780     MachineFrameInfo *MFI = MF.getFrameInfo();
2781     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2782
2783     // Create load node to retrieve arguments from the stack.
2784     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2785     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2786                             MachinePointerInfo::getFixedStack(FI),
2787                             false, false, false, 0);
2788   } else {
2789     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2790     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2791   }
2792   if (!Subtarget->isLittle())
2793     std::swap (ArgValue, ArgValue2);
2794   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2795 }
2796
2797 void
2798 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2799                                   unsigned InRegsParamRecordIdx,
2800                                   unsigned ArgSize,
2801                                   unsigned &ArgRegsSize,
2802                                   unsigned &ArgRegsSaveSize)
2803   const {
2804   unsigned NumGPRs;
2805   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2806     unsigned RBegin, REnd;
2807     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2808     NumGPRs = REnd - RBegin;
2809   } else {
2810     unsigned int firstUnalloced;
2811     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2812                                                 sizeof(GPRArgRegs) /
2813                                                 sizeof(GPRArgRegs[0]));
2814     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2815   }
2816
2817   unsigned Align = MF.getTarget()
2818                        .getSubtargetImpl()
2819                        ->getFrameLowering()
2820                        ->getStackAlignment();
2821   ArgRegsSize = NumGPRs * 4;
2822
2823   // If parameter is split between stack and GPRs...
2824   if (NumGPRs && Align > 4 &&
2825       (ArgRegsSize < ArgSize ||
2826         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2827     // Add padding for part of param recovered from GPRs.  For example,
2828     // if Align == 8, its last byte must be at address K*8 - 1.
2829     // We need to do it, since remained (stack) part of parameter has
2830     // stack alignment, and we need to "attach" "GPRs head" without gaps
2831     // to it:
2832     // Stack:
2833     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2834     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2835     //
2836     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2837     unsigned Padding =
2838         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2839     ArgRegsSaveSize = ArgRegsSize + Padding;
2840   } else
2841     // We don't need to extend regs save size for byval parameters if they
2842     // are passed via GPRs only.
2843     ArgRegsSaveSize = ArgRegsSize;
2844 }
2845
2846 // The remaining GPRs hold either the beginning of variable-argument
2847 // data, or the beginning of an aggregate passed by value (usually
2848 // byval).  Either way, we allocate stack slots adjacent to the data
2849 // provided by our caller, and store the unallocated registers there.
2850 // If this is a variadic function, the va_list pointer will begin with
2851 // these values; otherwise, this reassembles a (byval) structure that
2852 // was split between registers and memory.
2853 // Return: The frame index registers were stored into.
2854 int
2855 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2856                                   SDLoc dl, SDValue &Chain,
2857                                   const Value *OrigArg,
2858                                   unsigned InRegsParamRecordIdx,
2859                                   unsigned OffsetFromOrigArg,
2860                                   unsigned ArgOffset,
2861                                   unsigned ArgSize,
2862                                   bool ForceMutable,
2863                                   unsigned ByValStoreOffset,
2864                                   unsigned TotalArgRegsSaveSize) const {
2865
2866   // Currently, two use-cases possible:
2867   // Case #1. Non-var-args function, and we meet first byval parameter.
2868   //          Setup first unallocated register as first byval register;
2869   //          eat all remained registers
2870   //          (these two actions are performed by HandleByVal method).
2871   //          Then, here, we initialize stack frame with
2872   //          "store-reg" instructions.
2873   // Case #2. Var-args function, that doesn't contain byval parameters.
2874   //          The same: eat all remained unallocated registers,
2875   //          initialize stack frame.
2876
2877   MachineFunction &MF = DAG.getMachineFunction();
2878   MachineFrameInfo *MFI = MF.getFrameInfo();
2879   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2880   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2881   unsigned RBegin, REnd;
2882   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2883     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2884     firstRegToSaveIndex = RBegin - ARM::R0;
2885     lastRegToSaveIndex = REnd - ARM::R0;
2886   } else {
2887     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2888       (GPRArgRegs, array_lengthof(GPRArgRegs));
2889     lastRegToSaveIndex = 4;
2890   }
2891
2892   unsigned ArgRegsSize, ArgRegsSaveSize;
2893   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2894                  ArgRegsSize, ArgRegsSaveSize);
2895
2896   // Store any by-val regs to their spots on the stack so that they may be
2897   // loaded by deferencing the result of formal parameter pointer or va_next.
2898   // Note: once stack area for byval/varargs registers
2899   // was initialized, it can't be initialized again.
2900   if (ArgRegsSaveSize) {
2901     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2902
2903     if (Padding) {
2904       assert(AFI->getStoredByValParamsPadding() == 0 &&
2905              "The only parameter may be padded.");
2906       AFI->setStoredByValParamsPadding(Padding);
2907     }
2908
2909     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2910                                             Padding +
2911                                               ByValStoreOffset -
2912                                               (int64_t)TotalArgRegsSaveSize,
2913                                             false);
2914     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2915     if (Padding) {
2916        MFI->CreateFixedObject(Padding,
2917                               ArgOffset + ByValStoreOffset -
2918                                 (int64_t)ArgRegsSaveSize,
2919                               false);
2920     }
2921
2922     SmallVector<SDValue, 4> MemOps;
2923     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2924          ++firstRegToSaveIndex, ++i) {
2925       const TargetRegisterClass *RC;
2926       if (AFI->isThumb1OnlyFunction())
2927         RC = &ARM::tGPRRegClass;
2928       else
2929         RC = &ARM::GPRRegClass;
2930
2931       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2932       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2933       SDValue Store =
2934         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2935                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2936                      false, false, 0);
2937       MemOps.push_back(Store);
2938       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2939                         DAG.getConstant(4, getPointerTy()));
2940     }
2941
2942     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2943
2944     if (!MemOps.empty())
2945       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2946     return FrameIndex;
2947   } else {
2948     if (ArgSize == 0) {
2949       // We cannot allocate a zero-byte object for the first variadic argument,
2950       // so just make up a size.
2951       ArgSize = 4;
2952     }
2953     // This will point to the next argument passed via stack.
2954     return MFI->CreateFixedObject(
2955       ArgSize, ArgOffset, !ForceMutable);
2956   }
2957 }
2958
2959 // Setup stack frame, the va_list pointer will start from.
2960 void
2961 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2962                                         SDLoc dl, SDValue &Chain,
2963                                         unsigned ArgOffset,
2964                                         unsigned TotalArgRegsSaveSize,
2965                                         bool ForceMutable) const {
2966   MachineFunction &MF = DAG.getMachineFunction();
2967   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2968
2969   // Try to store any remaining integer argument regs
2970   // to their spots on the stack so that they may be loaded by deferencing
2971   // the result of va_next.
2972   // If there is no regs to be stored, just point address after last
2973   // argument passed via stack.
2974   int FrameIndex =
2975     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2976                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2977                    0, TotalArgRegsSaveSize);
2978
2979   AFI->setVarArgsFrameIndex(FrameIndex);
2980 }
2981
2982 SDValue
2983 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2984                                         CallingConv::ID CallConv, bool isVarArg,
2985                                         const SmallVectorImpl<ISD::InputArg>
2986                                           &Ins,
2987                                         SDLoc dl, SelectionDAG &DAG,
2988                                         SmallVectorImpl<SDValue> &InVals)
2989                                           const {
2990   MachineFunction &MF = DAG.getMachineFunction();
2991   MachineFrameInfo *MFI = MF.getFrameInfo();
2992
2993   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2994
2995   // Assign locations to all of the incoming arguments.
2996   SmallVector<CCValAssign, 16> ArgLocs;
2997   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2998                     *DAG.getContext(), Prologue);
2999   CCInfo.AnalyzeFormalArguments(Ins,
3000                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3001                                                   isVarArg));
3002
3003   SmallVector<SDValue, 16> ArgValues;
3004   int lastInsIndex = -1;
3005   SDValue ArgValue;
3006   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3007   unsigned CurArgIdx = 0;
3008
3009   // Initially ArgRegsSaveSize is zero.
3010   // Then we increase this value each time we meet byval parameter.
3011   // We also increase this value in case of varargs function.
3012   AFI->setArgRegsSaveSize(0);
3013
3014   unsigned ByValStoreOffset = 0;
3015   unsigned TotalArgRegsSaveSize = 0;
3016   unsigned ArgRegsSaveSizeMaxAlign = 4;
3017
3018   // Calculate the amount of stack space that we need to allocate to store
3019   // byval and variadic arguments that are passed in registers.
3020   // We need to know this before we allocate the first byval or variadic
3021   // argument, as they will be allocated a stack slot below the CFA (Canonical
3022   // Frame Address, the stack pointer at entry to the function).
3023   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3024     CCValAssign &VA = ArgLocs[i];
3025     if (VA.isMemLoc()) {
3026       int index = VA.getValNo();
3027       if (index != lastInsIndex) {
3028         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3029         if (Flags.isByVal()) {
3030           unsigned ExtraArgRegsSize;
3031           unsigned ExtraArgRegsSaveSize;
3032           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3033                          Flags.getByValSize(),
3034                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3035
3036           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3037           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3038               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3039           CCInfo.nextInRegsParam();
3040         }
3041         lastInsIndex = index;
3042       }
3043     }
3044   }
3045   CCInfo.rewindByValRegsInfo();
3046   lastInsIndex = -1;
3047   if (isVarArg) {
3048     unsigned ExtraArgRegsSize;
3049     unsigned ExtraArgRegsSaveSize;
3050     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3051                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3052     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3053   }
3054   // If the arg regs save area contains N-byte aligned values, the
3055   // bottom of it must be at least N-byte aligned.
3056   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3057   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3058
3059   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3060     CCValAssign &VA = ArgLocs[i];
3061     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3062     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3063     // Arguments stored in registers.
3064     if (VA.isRegLoc()) {
3065       EVT RegVT = VA.getLocVT();
3066
3067       if (VA.needsCustom()) {
3068         // f64 and vector types are split up into multiple registers or
3069         // combinations of registers and stack slots.
3070         if (VA.getLocVT() == MVT::v2f64) {
3071           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3072                                                    Chain, DAG, dl);
3073           VA = ArgLocs[++i]; // skip ahead to next loc
3074           SDValue ArgValue2;
3075           if (VA.isMemLoc()) {
3076             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3077             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3078             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3079                                     MachinePointerInfo::getFixedStack(FI),
3080                                     false, false, false, 0);
3081           } else {
3082             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3083                                              Chain, DAG, dl);
3084           }
3085           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3086           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3087                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3088           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3089                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3090         } else
3091           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3092
3093       } else {
3094         const TargetRegisterClass *RC;
3095
3096         if (RegVT == MVT::f32)
3097           RC = &ARM::SPRRegClass;
3098         else if (RegVT == MVT::f64)
3099           RC = &ARM::DPRRegClass;
3100         else if (RegVT == MVT::v2f64)
3101           RC = &ARM::QPRRegClass;
3102         else if (RegVT == MVT::i32)
3103           RC = AFI->isThumb1OnlyFunction() ?
3104             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3105             (const TargetRegisterClass*)&ARM::GPRRegClass;
3106         else
3107           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3108
3109         // Transform the arguments in physical registers into virtual ones.
3110         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3111         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3112       }
3113
3114       // If this is an 8 or 16-bit value, it is really passed promoted
3115       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3116       // truncate to the right size.
3117       switch (VA.getLocInfo()) {
3118       default: llvm_unreachable("Unknown loc info!");
3119       case CCValAssign::Full: break;
3120       case CCValAssign::BCvt:
3121         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3122         break;
3123       case CCValAssign::SExt:
3124         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3125                                DAG.getValueType(VA.getValVT()));
3126         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3127         break;
3128       case CCValAssign::ZExt:
3129         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3130                                DAG.getValueType(VA.getValVT()));
3131         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3132         break;
3133       }
3134
3135       InVals.push_back(ArgValue);
3136
3137     } else { // VA.isRegLoc()
3138
3139       // sanity check
3140       assert(VA.isMemLoc());
3141       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3142
3143       int index = ArgLocs[i].getValNo();
3144
3145       // Some Ins[] entries become multiple ArgLoc[] entries.
3146       // Process them only once.
3147       if (index != lastInsIndex)
3148         {
3149           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3150           // FIXME: For now, all byval parameter objects are marked mutable.
3151           // This can be changed with more analysis.
3152           // In case of tail call optimization mark all arguments mutable.
3153           // Since they could be overwritten by lowering of arguments in case of
3154           // a tail call.
3155           if (Flags.isByVal()) {
3156             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3157
3158             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3159             int FrameIndex = StoreByValRegs(
3160                 CCInfo, DAG, dl, Chain, CurOrigArg,
3161                 CurByValIndex,
3162                 Ins[VA.getValNo()].PartOffset,
3163                 VA.getLocMemOffset(),
3164                 Flags.getByValSize(),
3165                 true /*force mutable frames*/,
3166                 ByValStoreOffset,
3167                 TotalArgRegsSaveSize);
3168             ByValStoreOffset += Flags.getByValSize();
3169             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3170             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3171             CCInfo.nextInRegsParam();
3172           } else {
3173             unsigned FIOffset = VA.getLocMemOffset();
3174             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3175                                             FIOffset, true);
3176
3177             // Create load nodes to retrieve arguments from the stack.
3178             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3179             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3180                                          MachinePointerInfo::getFixedStack(FI),
3181                                          false, false, false, 0));
3182           }
3183           lastInsIndex = index;
3184         }
3185     }
3186   }
3187
3188   // varargs
3189   if (isVarArg)
3190     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3191                          CCInfo.getNextStackOffset(),
3192                          TotalArgRegsSaveSize);
3193
3194   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3195
3196   return Chain;
3197 }
3198
3199 /// isFloatingPointZero - Return true if this is +0.0.
3200 static bool isFloatingPointZero(SDValue Op) {
3201   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3202     return CFP->getValueAPF().isPosZero();
3203   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3204     // Maybe this has already been legalized into the constant pool?
3205     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3206       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3207       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3208         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3209           return CFP->getValueAPF().isPosZero();
3210     }
3211   }
3212   return false;
3213 }
3214
3215 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3216 /// the given operands.
3217 SDValue
3218 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3219                              SDValue &ARMcc, SelectionDAG &DAG,
3220                              SDLoc dl) const {
3221   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3222     unsigned C = RHSC->getZExtValue();
3223     if (!isLegalICmpImmediate(C)) {
3224       // Constant does not fit, try adjusting it by one?
3225       switch (CC) {
3226       default: break;
3227       case ISD::SETLT:
3228       case ISD::SETGE:
3229         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3230           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3231           RHS = DAG.getConstant(C-1, MVT::i32);
3232         }
3233         break;
3234       case ISD::SETULT:
3235       case ISD::SETUGE:
3236         if (C != 0 && isLegalICmpImmediate(C-1)) {
3237           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3238           RHS = DAG.getConstant(C-1, MVT::i32);
3239         }
3240         break;
3241       case ISD::SETLE:
3242       case ISD::SETGT:
3243         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3244           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3245           RHS = DAG.getConstant(C+1, MVT::i32);
3246         }
3247         break;
3248       case ISD::SETULE:
3249       case ISD::SETUGT:
3250         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3251           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3252           RHS = DAG.getConstant(C+1, MVT::i32);
3253         }
3254         break;
3255       }
3256     }
3257   }
3258
3259   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3260   ARMISD::NodeType CompareType;
3261   switch (CondCode) {
3262   default:
3263     CompareType = ARMISD::CMP;
3264     break;
3265   case ARMCC::EQ:
3266   case ARMCC::NE:
3267     // Uses only Z Flag
3268     CompareType = ARMISD::CMPZ;
3269     break;
3270   }
3271   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3272   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3273 }
3274
3275 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3276 SDValue
3277 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3278                              SDLoc dl) const {
3279   SDValue Cmp;
3280   if (!isFloatingPointZero(RHS))
3281     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3282   else
3283     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3284   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3285 }
3286
3287 /// duplicateCmp - Glue values can have only one use, so this function
3288 /// duplicates a comparison node.
3289 SDValue
3290 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3291   unsigned Opc = Cmp.getOpcode();
3292   SDLoc DL(Cmp);
3293   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3294     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3295
3296   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3297   Cmp = Cmp.getOperand(0);
3298   Opc = Cmp.getOpcode();
3299   if (Opc == ARMISD::CMPFP)
3300     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3301   else {
3302     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3303     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3304   }
3305   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3306 }
3307
3308 std::pair<SDValue, SDValue>
3309 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3310                                  SDValue &ARMcc) const {
3311   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3312
3313   SDValue Value, OverflowCmp;
3314   SDValue LHS = Op.getOperand(0);
3315   SDValue RHS = Op.getOperand(1);
3316
3317
3318   // FIXME: We are currently always generating CMPs because we don't support
3319   // generating CMN through the backend. This is not as good as the natural
3320   // CMP case because it causes a register dependency and cannot be folded
3321   // later.
3322
3323   switch (Op.getOpcode()) {
3324   default:
3325     llvm_unreachable("Unknown overflow instruction!");
3326   case ISD::SADDO:
3327     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3328     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3329     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3330     break;
3331   case ISD::UADDO:
3332     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3333     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3334     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3335     break;
3336   case ISD::SSUBO:
3337     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3338     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3339     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3340     break;
3341   case ISD::USUBO:
3342     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3343     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3344     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3345     break;
3346   } // switch (...)
3347
3348   return std::make_pair(Value, OverflowCmp);
3349 }
3350
3351
3352 SDValue
3353 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3354   // Let legalize expand this if it isn't a legal type yet.
3355   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3356     return SDValue();
3357
3358   SDValue Value, OverflowCmp;
3359   SDValue ARMcc;
3360   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3361   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3362   // We use 0 and 1 as false and true values.
3363   SDValue TVal = DAG.getConstant(1, MVT::i32);
3364   SDValue FVal = DAG.getConstant(0, MVT::i32);
3365   EVT VT = Op.getValueType();
3366
3367   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3368                                  ARMcc, CCR, OverflowCmp);
3369
3370   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3371   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3372 }
3373
3374
3375 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3376   SDValue Cond = Op.getOperand(0);
3377   SDValue SelectTrue = Op.getOperand(1);
3378   SDValue SelectFalse = Op.getOperand(2);
3379   SDLoc dl(Op);
3380   unsigned Opc = Cond.getOpcode();
3381
3382   if (Cond.getResNo() == 1 &&
3383       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3384        Opc == ISD::USUBO)) {
3385     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3386       return SDValue();
3387
3388     SDValue Value, OverflowCmp;
3389     SDValue ARMcc;
3390     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3391     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3392     EVT VT = Op.getValueType();
3393
3394     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3395                        ARMcc, CCR, OverflowCmp);
3396
3397   }
3398
3399   // Convert:
3400   //
3401   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3402   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3403   //
3404   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3405     const ConstantSDNode *CMOVTrue =
3406       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3407     const ConstantSDNode *CMOVFalse =
3408       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3409
3410     if (CMOVTrue && CMOVFalse) {
3411       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3412       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3413
3414       SDValue True;
3415       SDValue False;
3416       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3417         True = SelectTrue;
3418         False = SelectFalse;
3419       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3420         True = SelectFalse;
3421         False = SelectTrue;
3422       }
3423
3424       if (True.getNode() && False.getNode()) {
3425         EVT VT = Op.getValueType();
3426         SDValue ARMcc = Cond.getOperand(2);
3427         SDValue CCR = Cond.getOperand(3);
3428         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3429         assert(True.getValueType() == VT);
3430         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3431       }
3432     }
3433   }
3434
3435   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3436   // undefined bits before doing a full-word comparison with zero.
3437   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3438                      DAG.getConstant(1, Cond.getValueType()));
3439
3440   return DAG.getSelectCC(dl, Cond,
3441                          DAG.getConstant(0, Cond.getValueType()),
3442                          SelectTrue, SelectFalse, ISD::SETNE);
3443 }
3444
3445 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3446   if (CC == ISD::SETNE)
3447     return ISD::SETEQ;
3448   return ISD::getSetCCInverse(CC, true);
3449 }
3450
3451 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3452                                  bool &swpCmpOps, bool &swpVselOps) {
3453   // Start by selecting the GE condition code for opcodes that return true for
3454   // 'equality'
3455   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3456       CC == ISD::SETULE)
3457     CondCode = ARMCC::GE;
3458
3459   // and GT for opcodes that return false for 'equality'.
3460   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3461            CC == ISD::SETULT)
3462     CondCode = ARMCC::GT;
3463
3464   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3465   // to swap the compare operands.
3466   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3467       CC == ISD::SETULT)
3468     swpCmpOps = true;
3469
3470   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3471   // If we have an unordered opcode, we need to swap the operands to the VSEL
3472   // instruction (effectively negating the condition).
3473   //
3474   // This also has the effect of swapping which one of 'less' or 'greater'
3475   // returns true, so we also swap the compare operands. It also switches
3476   // whether we return true for 'equality', so we compensate by picking the
3477   // opposite condition code to our original choice.
3478   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3479       CC == ISD::SETUGT) {
3480     swpCmpOps = !swpCmpOps;
3481     swpVselOps = !swpVselOps;
3482     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3483   }
3484
3485   // 'ordered' is 'anything but unordered', so use the VS condition code and
3486   // swap the VSEL operands.
3487   if (CC == ISD::SETO) {
3488     CondCode = ARMCC::VS;
3489     swpVselOps = true;
3490   }
3491
3492   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3493   // code and swap the VSEL operands.
3494   if (CC == ISD::SETUNE) {
3495     CondCode = ARMCC::EQ;
3496     swpVselOps = true;
3497   }
3498 }
3499
3500 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3501   EVT VT = Op.getValueType();
3502   SDValue LHS = Op.getOperand(0);
3503   SDValue RHS = Op.getOperand(1);
3504   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3505   SDValue TrueVal = Op.getOperand(2);
3506   SDValue FalseVal = Op.getOperand(3);
3507   SDLoc dl(Op);
3508
3509   if (LHS.getValueType() == MVT::i32) {
3510     // Try to generate VSEL on ARMv8.
3511     // The VSEL instruction can't use all the usual ARM condition
3512     // codes: it only has two bits to select the condition code, so it's
3513     // constrained to use only GE, GT, VS and EQ.
3514     //
3515     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3516     // swap the operands of the previous compare instruction (effectively
3517     // inverting the compare condition, swapping 'less' and 'greater') and
3518     // sometimes need to swap the operands to the VSEL (which inverts the
3519     // condition in the sense of firing whenever the previous condition didn't)
3520     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3521                                       TrueVal.getValueType() == MVT::f64)) {
3522       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3523       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3524           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3525         CC = getInverseCCForVSEL(CC);
3526         std::swap(TrueVal, FalseVal);
3527       }
3528     }
3529
3530     SDValue ARMcc;
3531     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3532     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3533     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3534                        Cmp);
3535   }
3536
3537   ARMCC::CondCodes CondCode, CondCode2;
3538   FPCCToARMCC(CC, CondCode, CondCode2);
3539
3540   // Try to generate VSEL on ARMv8.
3541   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3542                                     TrueVal.getValueType() == MVT::f64)) {
3543     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3544     // same operands, as follows:
3545     //   c = fcmp [ogt, olt, ugt, ult] a, b
3546     //   select c, a, b
3547     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3548     // handled differently than the original code sequence.
3549     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3550         RHS == FalseVal) {
3551       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3552         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3553       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3554         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3555     }
3556
3557     bool swpCmpOps = false;
3558     bool swpVselOps = false;
3559     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3560
3561     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3562         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3563       if (swpCmpOps)
3564         std::swap(LHS, RHS);
3565       if (swpVselOps)
3566         std::swap(TrueVal, FalseVal);
3567     }
3568   }
3569
3570   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3571   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3572   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3573   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3574                                ARMcc, CCR, Cmp);
3575   if (CondCode2 != ARMCC::AL) {
3576     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3577     // FIXME: Needs another CMP because flag can have but one use.
3578     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3579     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3580                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3581   }
3582   return Result;
3583 }
3584
3585 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3586 /// to morph to an integer compare sequence.
3587 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3588                            const ARMSubtarget *Subtarget) {
3589   SDNode *N = Op.getNode();
3590   if (!N->hasOneUse())
3591     // Otherwise it requires moving the value from fp to integer registers.
3592     return false;
3593   if (!N->getNumValues())
3594     return false;
3595   EVT VT = Op.getValueType();
3596   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3597     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3598     // vmrs are very slow, e.g. cortex-a8.
3599     return false;
3600
3601   if (isFloatingPointZero(Op)) {
3602     SeenZero = true;
3603     return true;
3604   }
3605   return ISD::isNormalLoad(N);
3606 }
3607
3608 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3609   if (isFloatingPointZero(Op))
3610     return DAG.getConstant(0, MVT::i32);
3611
3612   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3613     return DAG.getLoad(MVT::i32, SDLoc(Op),
3614                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3615                        Ld->isVolatile(), Ld->isNonTemporal(),
3616                        Ld->isInvariant(), Ld->getAlignment());
3617
3618   llvm_unreachable("Unknown VFP cmp argument!");
3619 }
3620
3621 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3622                            SDValue &RetVal1, SDValue &RetVal2) {
3623   if (isFloatingPointZero(Op)) {
3624     RetVal1 = DAG.getConstant(0, MVT::i32);
3625     RetVal2 = DAG.getConstant(0, MVT::i32);
3626     return;
3627   }
3628
3629   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3630     SDValue Ptr = Ld->getBasePtr();
3631     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3632                           Ld->getChain(), Ptr,
3633                           Ld->getPointerInfo(),
3634                           Ld->isVolatile(), Ld->isNonTemporal(),
3635                           Ld->isInvariant(), Ld->getAlignment());
3636
3637     EVT PtrType = Ptr.getValueType();
3638     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3639     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3640                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3641     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3642                           Ld->getChain(), NewPtr,
3643                           Ld->getPointerInfo().getWithOffset(4),
3644                           Ld->isVolatile(), Ld->isNonTemporal(),
3645                           Ld->isInvariant(), NewAlign);
3646     return;
3647   }
3648
3649   llvm_unreachable("Unknown VFP cmp argument!");
3650 }
3651
3652 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3653 /// f32 and even f64 comparisons to integer ones.
3654 SDValue
3655 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3656   SDValue Chain = Op.getOperand(0);
3657   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3658   SDValue LHS = Op.getOperand(2);
3659   SDValue RHS = Op.getOperand(3);
3660   SDValue Dest = Op.getOperand(4);
3661   SDLoc dl(Op);
3662
3663   bool LHSSeenZero = false;
3664   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3665   bool RHSSeenZero = false;
3666   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3667   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3668     // If unsafe fp math optimization is enabled and there are no other uses of
3669     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3670     // to an integer comparison.
3671     if (CC == ISD::SETOEQ)
3672       CC = ISD::SETEQ;
3673     else if (CC == ISD::SETUNE)
3674       CC = ISD::SETNE;
3675
3676     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3677     SDValue ARMcc;
3678     if (LHS.getValueType() == MVT::f32) {
3679       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3680                         bitcastf32Toi32(LHS, DAG), Mask);
3681       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3682                         bitcastf32Toi32(RHS, DAG), Mask);
3683       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3684       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3685       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3686                          Chain, Dest, ARMcc, CCR, Cmp);
3687     }
3688
3689     SDValue LHS1, LHS2;
3690     SDValue RHS1, RHS2;
3691     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3692     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3693     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3694     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3695     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3696     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3697     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3698     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3699     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3700   }
3701
3702   return SDValue();
3703 }
3704
3705 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3706   SDValue Chain = Op.getOperand(0);
3707   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3708   SDValue LHS = Op.getOperand(2);
3709   SDValue RHS = Op.getOperand(3);
3710   SDValue Dest = Op.getOperand(4);
3711   SDLoc dl(Op);
3712
3713   if (LHS.getValueType() == MVT::i32) {
3714     SDValue ARMcc;
3715     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3716     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3717     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3718                        Chain, Dest, ARMcc, CCR, Cmp);
3719   }
3720
3721   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3722
3723   if (getTargetMachine().Options.UnsafeFPMath &&
3724       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3725        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3726     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3727     if (Result.getNode())
3728       return Result;
3729   }
3730
3731   ARMCC::CondCodes CondCode, CondCode2;
3732   FPCCToARMCC(CC, CondCode, CondCode2);
3733
3734   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3735   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3736   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3737   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3738   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3739   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3740   if (CondCode2 != ARMCC::AL) {
3741     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3742     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3743     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3744   }
3745   return Res;
3746 }
3747
3748 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3749   SDValue Chain = Op.getOperand(0);
3750   SDValue Table = Op.getOperand(1);
3751   SDValue Index = Op.getOperand(2);
3752   SDLoc dl(Op);
3753
3754   EVT PTy = getPointerTy();
3755   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3756   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3757   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3758   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3759   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3760   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3761   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3762   if (Subtarget->isThumb2()) {
3763     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3764     // which does another jump to the destination. This also makes it easier
3765     // to translate it to TBB / TBH later.
3766     // FIXME: This might not work if the function is extremely large.
3767     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3768                        Addr, Op.getOperand(2), JTI, UId);
3769   }
3770   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3771     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3772                        MachinePointerInfo::getJumpTable(),
3773                        false, false, false, 0);
3774     Chain = Addr.getValue(1);
3775     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3776     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3777   } else {
3778     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3779                        MachinePointerInfo::getJumpTable(),
3780                        false, false, false, 0);
3781     Chain = Addr.getValue(1);
3782     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3783   }
3784 }
3785
3786 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3787   EVT VT = Op.getValueType();
3788   SDLoc dl(Op);
3789
3790   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3791     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3792       return Op;
3793     return DAG.UnrollVectorOp(Op.getNode());
3794   }
3795
3796   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3797          "Invalid type for custom lowering!");
3798   if (VT != MVT::v4i16)
3799     return DAG.UnrollVectorOp(Op.getNode());
3800
3801   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3802   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3803 }
3804
3805 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3806   EVT VT = Op.getValueType();
3807   if (VT.isVector())
3808     return LowerVectorFP_TO_INT(Op, DAG);
3809
3810   SDLoc dl(Op);
3811   unsigned Opc;
3812
3813   switch (Op.getOpcode()) {
3814   default: llvm_unreachable("Invalid opcode!");
3815   case ISD::FP_TO_SINT:
3816     Opc = ARMISD::FTOSI;
3817     break;
3818   case ISD::FP_TO_UINT:
3819     Opc = ARMISD::FTOUI;
3820     break;
3821   }
3822   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3823   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3824 }
3825
3826 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3827   EVT VT = Op.getValueType();
3828   SDLoc dl(Op);
3829
3830   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3831     if (VT.getVectorElementType() == MVT::f32)
3832       return Op;
3833     return DAG.UnrollVectorOp(Op.getNode());
3834   }
3835
3836   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3837          "Invalid type for custom lowering!");
3838   if (VT != MVT::v4f32)
3839     return DAG.UnrollVectorOp(Op.getNode());
3840
3841   unsigned CastOpc;
3842   unsigned Opc;
3843   switch (Op.getOpcode()) {
3844   default: llvm_unreachable("Invalid opcode!");
3845   case ISD::SINT_TO_FP:
3846     CastOpc = ISD::SIGN_EXTEND;
3847     Opc = ISD::SINT_TO_FP;
3848     break;
3849   case ISD::UINT_TO_FP:
3850     CastOpc = ISD::ZERO_EXTEND;
3851     Opc = ISD::UINT_TO_FP;
3852     break;
3853   }
3854
3855   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3856   return DAG.getNode(Opc, dl, VT, Op);
3857 }
3858
3859 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3860   EVT VT = Op.getValueType();
3861   if (VT.isVector())
3862     return LowerVectorINT_TO_FP(Op, DAG);
3863
3864   SDLoc dl(Op);
3865   unsigned Opc;
3866
3867   switch (Op.getOpcode()) {
3868   default: llvm_unreachable("Invalid opcode!");
3869   case ISD::SINT_TO_FP:
3870     Opc = ARMISD::SITOF;
3871     break;
3872   case ISD::UINT_TO_FP:
3873     Opc = ARMISD::UITOF;
3874     break;
3875   }
3876
3877   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3878   return DAG.getNode(Opc, dl, VT, Op);
3879 }
3880
3881 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3882   // Implement fcopysign with a fabs and a conditional fneg.
3883   SDValue Tmp0 = Op.getOperand(0);
3884   SDValue Tmp1 = Op.getOperand(1);
3885   SDLoc dl(Op);
3886   EVT VT = Op.getValueType();
3887   EVT SrcVT = Tmp1.getValueType();
3888   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3889     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3890   bool UseNEON = !InGPR && Subtarget->hasNEON();
3891
3892   if (UseNEON) {
3893     // Use VBSL to copy the sign bit.
3894     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3895     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3896                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3897     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3898     if (VT == MVT::f64)
3899       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3900                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3901                          DAG.getConstant(32, MVT::i32));
3902     else /*if (VT == MVT::f32)*/
3903       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3904     if (SrcVT == MVT::f32) {
3905       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3906       if (VT == MVT::f64)
3907         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3908                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3909                            DAG.getConstant(32, MVT::i32));
3910     } else if (VT == MVT::f32)
3911       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3912                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3913                          DAG.getConstant(32, MVT::i32));
3914     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3915     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3916
3917     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3918                                             MVT::i32);
3919     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3920     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3921                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3922
3923     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3924                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3925                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3926     if (VT == MVT::f32) {
3927       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3928       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3929                         DAG.getConstant(0, MVT::i32));
3930     } else {
3931       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3932     }
3933
3934     return Res;
3935   }
3936
3937   // Bitcast operand 1 to i32.
3938   if (SrcVT == MVT::f64)
3939     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3940                        Tmp1).getValue(1);
3941   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3942
3943   // Or in the signbit with integer operations.
3944   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3945   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3946   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3947   if (VT == MVT::f32) {
3948     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3949                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3950     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3951                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3952   }
3953
3954   // f64: Or the high part with signbit and then combine two parts.
3955   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3956                      Tmp0);
3957   SDValue Lo = Tmp0.getValue(0);
3958   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3959   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3960   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3961 }
3962
3963 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3964   MachineFunction &MF = DAG.getMachineFunction();
3965   MachineFrameInfo *MFI = MF.getFrameInfo();
3966   MFI->setReturnAddressIsTaken(true);
3967
3968   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3969     return SDValue();
3970
3971   EVT VT = Op.getValueType();
3972   SDLoc dl(Op);
3973   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3974   if (Depth) {
3975     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3976     SDValue Offset = DAG.getConstant(4, MVT::i32);
3977     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3978                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3979                        MachinePointerInfo(), false, false, false, 0);
3980   }
3981
3982   // Return LR, which contains the return address. Mark it an implicit live-in.
3983   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3984   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3985 }
3986
3987 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3988   const ARMBaseRegisterInfo &ARI =
3989     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3990   MachineFunction &MF = DAG.getMachineFunction();
3991   MachineFrameInfo *MFI = MF.getFrameInfo();
3992   MFI->setFrameAddressIsTaken(true);
3993
3994   EVT VT = Op.getValueType();
3995   SDLoc dl(Op);  // FIXME probably not meaningful
3996   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3997   unsigned FrameReg = ARI.getFrameRegister(MF);
3998   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3999   while (Depth--)
4000     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4001                             MachinePointerInfo(),
4002                             false, false, false, 0);
4003   return FrameAddr;
4004 }
4005
4006 // FIXME? Maybe this could be a TableGen attribute on some registers and
4007 // this table could be generated automatically from RegInfo.
4008 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4009                                               EVT VT) const {
4010   unsigned Reg = StringSwitch<unsigned>(RegName)
4011                        .Case("sp", ARM::SP)
4012                        .Default(0);
4013   if (Reg)
4014     return Reg;
4015   report_fatal_error("Invalid register name global variable");
4016 }
4017
4018 /// ExpandBITCAST - If the target supports VFP, this function is called to
4019 /// expand a bit convert where either the source or destination type is i64 to
4020 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4021 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4022 /// vectors), since the legalizer won't know what to do with that.
4023 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4025   SDLoc dl(N);
4026   SDValue Op = N->getOperand(0);
4027
4028   // This function is only supposed to be called for i64 types, either as the
4029   // source or destination of the bit convert.
4030   EVT SrcVT = Op.getValueType();
4031   EVT DstVT = N->getValueType(0);
4032   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4033          "ExpandBITCAST called for non-i64 type");
4034
4035   // Turn i64->f64 into VMOVDRR.
4036   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4037     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4038                              DAG.getConstant(0, MVT::i32));
4039     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4040                              DAG.getConstant(1, MVT::i32));
4041     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4042                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4043   }
4044
4045   // Turn f64->i64 into VMOVRRD.
4046   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4047     SDValue Cvt;
4048     if (TLI.isBigEndian() && SrcVT.isVector() &&
4049         SrcVT.getVectorNumElements() > 1)
4050       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4051                         DAG.getVTList(MVT::i32, MVT::i32),
4052                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4053     else
4054       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4055                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4056     // Merge the pieces into a single i64 value.
4057     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4058   }
4059
4060   return SDValue();
4061 }
4062
4063 /// getZeroVector - Returns a vector of specified type with all zero elements.
4064 /// Zero vectors are used to represent vector negation and in those cases
4065 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4066 /// not support i64 elements, so sometimes the zero vectors will need to be
4067 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4068 /// zero vector.
4069 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4070   assert(VT.isVector() && "Expected a vector type");
4071   // The canonical modified immediate encoding of a zero vector is....0!
4072   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4073   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4074   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4075   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4076 }
4077
4078 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4079 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4080 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4081                                                 SelectionDAG &DAG) const {
4082   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4083   EVT VT = Op.getValueType();
4084   unsigned VTBits = VT.getSizeInBits();
4085   SDLoc dl(Op);
4086   SDValue ShOpLo = Op.getOperand(0);
4087   SDValue ShOpHi = Op.getOperand(1);
4088   SDValue ShAmt  = Op.getOperand(2);
4089   SDValue ARMcc;
4090   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4091
4092   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4093
4094   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4095                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4096   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4097   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4098                                    DAG.getConstant(VTBits, MVT::i32));
4099   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4100   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4101   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4102
4103   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4104   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4105                           ARMcc, DAG, dl);
4106   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4107   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4108                            CCR, Cmp);
4109
4110   SDValue Ops[2] = { Lo, Hi };
4111   return DAG.getMergeValues(Ops, dl);
4112 }
4113
4114 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4115 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4116 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4117                                                SelectionDAG &DAG) const {
4118   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4119   EVT VT = Op.getValueType();
4120   unsigned VTBits = VT.getSizeInBits();
4121   SDLoc dl(Op);
4122   SDValue ShOpLo = Op.getOperand(0);
4123   SDValue ShOpHi = Op.getOperand(1);
4124   SDValue ShAmt  = Op.getOperand(2);
4125   SDValue ARMcc;
4126
4127   assert(Op.getOpcode() == ISD::SHL_PARTS);
4128   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4129                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4130   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4131   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4132                                    DAG.getConstant(VTBits, MVT::i32));
4133   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4134   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4135
4136   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4137   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4138   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4139                           ARMcc, DAG, dl);
4140   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4141   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4142                            CCR, Cmp);
4143
4144   SDValue Ops[2] = { Lo, Hi };
4145   return DAG.getMergeValues(Ops, dl);
4146 }
4147
4148 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4149                                             SelectionDAG &DAG) const {
4150   // The rounding mode is in bits 23:22 of the FPSCR.
4151   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4152   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4153   // so that the shift + and get folded into a bitfield extract.
4154   SDLoc dl(Op);
4155   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4156                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4157                                               MVT::i32));
4158   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4159                                   DAG.getConstant(1U << 22, MVT::i32));
4160   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4161                               DAG.getConstant(22, MVT::i32));
4162   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4163                      DAG.getConstant(3, MVT::i32));
4164 }
4165
4166 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4167                          const ARMSubtarget *ST) {
4168   EVT VT = N->getValueType(0);
4169   SDLoc dl(N);
4170
4171   if (!ST->hasV6T2Ops())
4172     return SDValue();
4173
4174   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4175   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4176 }
4177
4178 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4179 /// for each 16-bit element from operand, repeated.  The basic idea is to
4180 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4181 ///
4182 /// Trace for v4i16:
4183 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4184 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4185 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4186 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4187 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4188 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4189 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4190 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4191 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4192   EVT VT = N->getValueType(0);
4193   SDLoc DL(N);
4194
4195   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4196   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4197   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4198   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4199   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4200   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4201 }
4202
4203 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4204 /// bit-count for each 16-bit element from the operand.  We need slightly
4205 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4206 /// 64/128-bit registers.
4207 ///
4208 /// Trace for v4i16:
4209 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4210 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4211 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4212 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4213 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4214   EVT VT = N->getValueType(0);
4215   SDLoc DL(N);
4216
4217   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4218   if (VT.is64BitVector()) {
4219     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4220     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4221                        DAG.getIntPtrConstant(0));
4222   } else {
4223     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4224                                     BitCounts, DAG.getIntPtrConstant(0));
4225     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4226   }
4227 }
4228
4229 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4230 /// bit-count for each 32-bit element from the operand.  The idea here is
4231 /// to split the vector into 16-bit elements, leverage the 16-bit count
4232 /// routine, and then combine the results.
4233 ///
4234 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4235 /// input    = [v0    v1    ] (vi: 32-bit elements)
4236 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4237 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4238 /// vrev: N0 = [k1 k0 k3 k2 ]
4239 ///            [k0 k1 k2 k3 ]
4240 ///       N1 =+[k1 k0 k3 k2 ]
4241 ///            [k0 k2 k1 k3 ]
4242 ///       N2 =+[k1 k3 k0 k2 ]
4243 ///            [k0    k2    k1    k3    ]
4244 /// Extended =+[k1    k3    k0    k2    ]
4245 ///            [k0    k2    ]
4246 /// Extracted=+[k1    k3    ]
4247 ///
4248 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4249   EVT VT = N->getValueType(0);
4250   SDLoc DL(N);
4251
4252   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4253
4254   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4255   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4256   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4257   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4258   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4259
4260   if (VT.is64BitVector()) {
4261     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4262     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4263                        DAG.getIntPtrConstant(0));
4264   } else {
4265     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4266                                     DAG.getIntPtrConstant(0));
4267     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4268   }
4269 }
4270
4271 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4272                           const ARMSubtarget *ST) {
4273   EVT VT = N->getValueType(0);
4274
4275   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4276   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4277           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4278          "Unexpected type for custom ctpop lowering");
4279
4280   if (VT.getVectorElementType() == MVT::i32)
4281     return lowerCTPOP32BitElements(N, DAG);
4282   else
4283     return lowerCTPOP16BitElements(N, DAG);
4284 }
4285
4286 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4287                           const ARMSubtarget *ST) {
4288   EVT VT = N->getValueType(0);
4289   SDLoc dl(N);
4290
4291   if (!VT.isVector())
4292     return SDValue();
4293
4294   // Lower vector shifts on NEON to use VSHL.
4295   assert(ST->hasNEON() && "unexpected vector shift");
4296
4297   // Left shifts translate directly to the vshiftu intrinsic.
4298   if (N->getOpcode() == ISD::SHL)
4299     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4300                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4301                        N->getOperand(0), N->getOperand(1));
4302
4303   assert((N->getOpcode() == ISD::SRA ||
4304           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4305
4306   // NEON uses the same intrinsics for both left and right shifts.  For
4307   // right shifts, the shift amounts are negative, so negate the vector of
4308   // shift amounts.
4309   EVT ShiftVT = N->getOperand(1).getValueType();
4310   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4311                                      getZeroVector(ShiftVT, DAG, dl),
4312                                      N->getOperand(1));
4313   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4314                              Intrinsic::arm_neon_vshifts :
4315                              Intrinsic::arm_neon_vshiftu);
4316   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4317                      DAG.getConstant(vshiftInt, MVT::i32),
4318                      N->getOperand(0), NegatedCount);
4319 }
4320
4321 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4322                                 const ARMSubtarget *ST) {
4323   EVT VT = N->getValueType(0);
4324   SDLoc dl(N);
4325
4326   // We can get here for a node like i32 = ISD::SHL i32, i64
4327   if (VT != MVT::i64)
4328     return SDValue();
4329
4330   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4331          "Unknown shift to lower!");
4332
4333   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4334   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4335       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4336     return SDValue();
4337
4338   // If we are in thumb mode, we don't have RRX.
4339   if (ST->isThumb1Only()) return SDValue();
4340
4341   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4342   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4343                            DAG.getConstant(0, MVT::i32));
4344   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4345                            DAG.getConstant(1, MVT::i32));
4346
4347   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4348   // captures the result into a carry flag.
4349   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4350   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4351
4352   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4353   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4354
4355   // Merge the pieces into a single i64 value.
4356  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4357 }
4358
4359 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4360   SDValue TmpOp0, TmpOp1;
4361   bool Invert = false;
4362   bool Swap = false;
4363   unsigned Opc = 0;
4364
4365   SDValue Op0 = Op.getOperand(0);
4366   SDValue Op1 = Op.getOperand(1);
4367   SDValue CC = Op.getOperand(2);
4368   EVT VT = Op.getValueType();
4369   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4370   SDLoc dl(Op);
4371
4372   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4373     switch (SetCCOpcode) {
4374     default: llvm_unreachable("Illegal FP comparison");
4375     case ISD::SETUNE:
4376     case ISD::SETNE:  Invert = true; // Fallthrough
4377     case ISD::SETOEQ:
4378     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4379     case ISD::SETOLT:
4380     case ISD::SETLT: Swap = true; // Fallthrough
4381     case ISD::SETOGT:
4382     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4383     case ISD::SETOLE:
4384     case ISD::SETLE:  Swap = true; // Fallthrough
4385     case ISD::SETOGE:
4386     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4387     case ISD::SETUGE: Swap = true; // Fallthrough
4388     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4389     case ISD::SETUGT: Swap = true; // Fallthrough
4390     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4391     case ISD::SETUEQ: Invert = true; // Fallthrough
4392     case ISD::SETONE:
4393       // Expand this to (OLT | OGT).
4394       TmpOp0 = Op0;
4395       TmpOp1 = Op1;
4396       Opc = ISD::OR;
4397       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4398       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4399       break;
4400     case ISD::SETUO: Invert = true; // Fallthrough
4401     case ISD::SETO:
4402       // Expand this to (OLT | OGE).
4403       TmpOp0 = Op0;
4404       TmpOp1 = Op1;
4405       Opc = ISD::OR;
4406       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4407       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4408       break;
4409     }
4410   } else {
4411     // Integer comparisons.
4412     switch (SetCCOpcode) {
4413     default: llvm_unreachable("Illegal integer comparison");
4414     case ISD::SETNE:  Invert = true;
4415     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4416     case ISD::SETLT:  Swap = true;
4417     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4418     case ISD::SETLE:  Swap = true;
4419     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4420     case ISD::SETULT: Swap = true;
4421     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4422     case ISD::SETULE: Swap = true;
4423     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4424     }
4425
4426     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4427     if (Opc == ARMISD::VCEQ) {
4428
4429       SDValue AndOp;
4430       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4431         AndOp = Op0;
4432       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4433         AndOp = Op1;
4434
4435       // Ignore bitconvert.
4436       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4437         AndOp = AndOp.getOperand(0);
4438
4439       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4440         Opc = ARMISD::VTST;
4441         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4442         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4443         Invert = !Invert;
4444       }
4445     }
4446   }
4447
4448   if (Swap)
4449     std::swap(Op0, Op1);
4450
4451   // If one of the operands is a constant vector zero, attempt to fold the
4452   // comparison to a specialized compare-against-zero form.
4453   SDValue SingleOp;
4454   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4455     SingleOp = Op0;
4456   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4457     if (Opc == ARMISD::VCGE)
4458       Opc = ARMISD::VCLEZ;
4459     else if (Opc == ARMISD::VCGT)
4460       Opc = ARMISD::VCLTZ;
4461     SingleOp = Op1;
4462   }
4463
4464   SDValue Result;
4465   if (SingleOp.getNode()) {
4466     switch (Opc) {
4467     case ARMISD::VCEQ:
4468       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4469     case ARMISD::VCGE:
4470       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4471     case ARMISD::VCLEZ:
4472       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4473     case ARMISD::VCGT:
4474       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4475     case ARMISD::VCLTZ:
4476       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4477     default:
4478       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4479     }
4480   } else {
4481      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4482   }
4483
4484   if (Invert)
4485     Result = DAG.getNOT(dl, Result, VT);
4486
4487   return Result;
4488 }
4489
4490 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4491 /// valid vector constant for a NEON instruction with a "modified immediate"
4492 /// operand (e.g., VMOV).  If so, return the encoded value.
4493 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4494                                  unsigned SplatBitSize, SelectionDAG &DAG,
4495                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4496   unsigned OpCmode, Imm;
4497
4498   // SplatBitSize is set to the smallest size that splats the vector, so a
4499   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4500   // immediate instructions others than VMOV do not support the 8-bit encoding
4501   // of a zero vector, and the default encoding of zero is supposed to be the
4502   // 32-bit version.
4503   if (SplatBits == 0)
4504     SplatBitSize = 32;
4505
4506   switch (SplatBitSize) {
4507   case 8:
4508     if (type != VMOVModImm)
4509       return SDValue();
4510     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4511     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4512     OpCmode = 0xe;
4513     Imm = SplatBits;
4514     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4515     break;
4516
4517   case 16:
4518     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4519     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4520     if ((SplatBits & ~0xff) == 0) {
4521       // Value = 0x00nn: Op=x, Cmode=100x.
4522       OpCmode = 0x8;
4523       Imm = SplatBits;
4524       break;
4525     }
4526     if ((SplatBits & ~0xff00) == 0) {
4527       // Value = 0xnn00: Op=x, Cmode=101x.
4528       OpCmode = 0xa;
4529       Imm = SplatBits >> 8;
4530       break;
4531     }
4532     return SDValue();
4533
4534   case 32:
4535     // NEON's 32-bit VMOV supports splat values where:
4536     // * only one byte is nonzero, or
4537     // * the least significant byte is 0xff and the second byte is nonzero, or
4538     // * the least significant 2 bytes are 0xff and the third is nonzero.
4539     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4540     if ((SplatBits & ~0xff) == 0) {
4541       // Value = 0x000000nn: Op=x, Cmode=000x.
4542       OpCmode = 0;
4543       Imm = SplatBits;
4544       break;
4545     }
4546     if ((SplatBits & ~0xff00) == 0) {
4547       // Value = 0x0000nn00: Op=x, Cmode=001x.
4548       OpCmode = 0x2;
4549       Imm = SplatBits >> 8;
4550       break;
4551     }
4552     if ((SplatBits & ~0xff0000) == 0) {
4553       // Value = 0x00nn0000: Op=x, Cmode=010x.
4554       OpCmode = 0x4;
4555       Imm = SplatBits >> 16;
4556       break;
4557     }
4558     if ((SplatBits & ~0xff000000) == 0) {
4559       // Value = 0xnn000000: Op=x, Cmode=011x.
4560       OpCmode = 0x6;
4561       Imm = SplatBits >> 24;
4562       break;
4563     }
4564
4565     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4566     if (type == OtherModImm) return SDValue();
4567
4568     if ((SplatBits & ~0xffff) == 0 &&
4569         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4570       // Value = 0x0000nnff: Op=x, Cmode=1100.
4571       OpCmode = 0xc;
4572       Imm = SplatBits >> 8;
4573       break;
4574     }
4575
4576     if ((SplatBits & ~0xffffff) == 0 &&
4577         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4578       // Value = 0x00nnffff: Op=x, Cmode=1101.
4579       OpCmode = 0xd;
4580       Imm = SplatBits >> 16;
4581       break;
4582     }
4583
4584     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4585     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4586     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4587     // and fall through here to test for a valid 64-bit splat.  But, then the
4588     // caller would also need to check and handle the change in size.
4589     return SDValue();
4590
4591   case 64: {
4592     if (type != VMOVModImm)
4593       return SDValue();
4594     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4595     uint64_t BitMask = 0xff;
4596     uint64_t Val = 0;
4597     unsigned ImmMask = 1;
4598     Imm = 0;
4599     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4600       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4601         Val |= BitMask;
4602         Imm |= ImmMask;
4603       } else if ((SplatBits & BitMask) != 0) {
4604         return SDValue();
4605       }
4606       BitMask <<= 8;
4607       ImmMask <<= 1;
4608     }
4609
4610     if (DAG.getTargetLoweringInfo().isBigEndian())
4611       // swap higher and lower 32 bit word
4612       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4613
4614     // Op=1, Cmode=1110.
4615     OpCmode = 0x1e;
4616     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4617     break;
4618   }
4619
4620   default:
4621     llvm_unreachable("unexpected size for isNEONModifiedImm");
4622   }
4623
4624   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4625   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4626 }
4627
4628 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4629                                            const ARMSubtarget *ST) const {
4630   if (!ST->hasVFP3())
4631     return SDValue();
4632
4633   bool IsDouble = Op.getValueType() == MVT::f64;
4634   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4635
4636   // Try splatting with a VMOV.f32...
4637   APFloat FPVal = CFP->getValueAPF();
4638   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4639
4640   if (ImmVal != -1) {
4641     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4642       // We have code in place to select a valid ConstantFP already, no need to
4643       // do any mangling.
4644       return Op;
4645     }
4646
4647     // It's a float and we are trying to use NEON operations where
4648     // possible. Lower it to a splat followed by an extract.
4649     SDLoc DL(Op);
4650     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4651     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4652                                       NewVal);
4653     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4654                        DAG.getConstant(0, MVT::i32));
4655   }
4656
4657   // The rest of our options are NEON only, make sure that's allowed before
4658   // proceeding..
4659   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4660     return SDValue();
4661
4662   EVT VMovVT;
4663   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4664
4665   // It wouldn't really be worth bothering for doubles except for one very
4666   // important value, which does happen to match: 0.0. So make sure we don't do
4667   // anything stupid.
4668   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4669     return SDValue();
4670
4671   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4672   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4673                                      false, VMOVModImm);
4674   if (NewVal != SDValue()) {
4675     SDLoc DL(Op);
4676     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4677                                       NewVal);
4678     if (IsDouble)
4679       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4680
4681     // It's a float: cast and extract a vector element.
4682     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4683                                        VecConstant);
4684     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4685                        DAG.getConstant(0, MVT::i32));
4686   }
4687
4688   // Finally, try a VMVN.i32
4689   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4690                              false, VMVNModImm);
4691   if (NewVal != SDValue()) {
4692     SDLoc DL(Op);
4693     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4694
4695     if (IsDouble)
4696       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4697
4698     // It's a float: cast and extract a vector element.
4699     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4700                                        VecConstant);
4701     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4702                        DAG.getConstant(0, MVT::i32));
4703   }
4704
4705   return SDValue();
4706 }
4707
4708 // check if an VEXT instruction can handle the shuffle mask when the
4709 // vector sources of the shuffle are the same.
4710 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4711   unsigned NumElts = VT.getVectorNumElements();
4712
4713   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4714   if (M[0] < 0)
4715     return false;
4716
4717   Imm = M[0];
4718
4719   // If this is a VEXT shuffle, the immediate value is the index of the first
4720   // element.  The other shuffle indices must be the successive elements after
4721   // the first one.
4722   unsigned ExpectedElt = Imm;
4723   for (unsigned i = 1; i < NumElts; ++i) {
4724     // Increment the expected index.  If it wraps around, just follow it
4725     // back to index zero and keep going.
4726     ++ExpectedElt;
4727     if (ExpectedElt == NumElts)
4728       ExpectedElt = 0;
4729
4730     if (M[i] < 0) continue; // ignore UNDEF indices
4731     if (ExpectedElt != static_cast<unsigned>(M[i]))
4732       return false;
4733   }
4734
4735   return true;
4736 }
4737
4738
4739 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4740                        bool &ReverseVEXT, unsigned &Imm) {
4741   unsigned NumElts = VT.getVectorNumElements();
4742   ReverseVEXT = false;
4743
4744   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4745   if (M[0] < 0)
4746     return false;
4747
4748   Imm = M[0];
4749
4750   // If this is a VEXT shuffle, the immediate value is the index of the first
4751   // element.  The other shuffle indices must be the successive elements after
4752   // the first one.
4753   unsigned ExpectedElt = Imm;
4754   for (unsigned i = 1; i < NumElts; ++i) {
4755     // Increment the expected index.  If it wraps around, it may still be
4756     // a VEXT but the source vectors must be swapped.
4757     ExpectedElt += 1;
4758     if (ExpectedElt == NumElts * 2) {
4759       ExpectedElt = 0;
4760       ReverseVEXT = true;
4761     }
4762
4763     if (M[i] < 0) continue; // ignore UNDEF indices
4764     if (ExpectedElt != static_cast<unsigned>(M[i]))
4765       return false;
4766   }
4767
4768   // Adjust the index value if the source operands will be swapped.
4769   if (ReverseVEXT)
4770     Imm -= NumElts;
4771
4772   return true;
4773 }
4774
4775 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4776 /// instruction with the specified blocksize.  (The order of the elements
4777 /// within each block of the vector is reversed.)
4778 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4779   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4780          "Only possible block sizes for VREV are: 16, 32, 64");
4781
4782   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4783   if (EltSz == 64)
4784     return false;
4785
4786   unsigned NumElts = VT.getVectorNumElements();
4787   unsigned BlockElts = M[0] + 1;
4788   // If the first shuffle index is UNDEF, be optimistic.
4789   if (M[0] < 0)
4790     BlockElts = BlockSize / EltSz;
4791
4792   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4793     return false;
4794
4795   for (unsigned i = 0; i < NumElts; ++i) {
4796     if (M[i] < 0) continue; // ignore UNDEF indices
4797     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4798       return false;
4799   }
4800
4801   return true;
4802 }
4803
4804 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4805   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4806   // range, then 0 is placed into the resulting vector. So pretty much any mask
4807   // of 8 elements can work here.
4808   return VT == MVT::v8i8 && M.size() == 8;
4809 }
4810
4811 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4812   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4813   if (EltSz == 64)
4814     return false;
4815
4816   unsigned NumElts = VT.getVectorNumElements();
4817   WhichResult = (M[0] == 0 ? 0 : 1);
4818   for (unsigned i = 0; i < NumElts; i += 2) {
4819     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4820         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4821       return false;
4822   }
4823   return true;
4824 }
4825
4826 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4827 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4828 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4829 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4830   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4831   if (EltSz == 64)
4832     return false;
4833
4834   unsigned NumElts = VT.getVectorNumElements();
4835   WhichResult = (M[0] == 0 ? 0 : 1);
4836   for (unsigned i = 0; i < NumElts; i += 2) {
4837     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4838         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4839       return false;
4840   }
4841   return true;
4842 }
4843
4844 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4845   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4846   if (EltSz == 64)
4847     return false;
4848
4849   unsigned NumElts = VT.getVectorNumElements();
4850   WhichResult = (M[0] == 0 ? 0 : 1);
4851   for (unsigned i = 0; i != NumElts; ++i) {
4852     if (M[i] < 0) continue; // ignore UNDEF indices
4853     if ((unsigned) M[i] != 2 * i + WhichResult)
4854       return false;
4855   }
4856
4857   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4858   if (VT.is64BitVector() && EltSz == 32)
4859     return false;
4860
4861   return true;
4862 }
4863
4864 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4865 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4866 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4867 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4868   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4869   if (EltSz == 64)
4870     return false;
4871
4872   unsigned Half = VT.getVectorNumElements() / 2;
4873   WhichResult = (M[0] == 0 ? 0 : 1);
4874   for (unsigned j = 0; j != 2; ++j) {
4875     unsigned Idx = WhichResult;
4876     for (unsigned i = 0; i != Half; ++i) {
4877       int MIdx = M[i + j * Half];
4878       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4879         return false;
4880       Idx += 2;
4881     }
4882   }
4883
4884   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4885   if (VT.is64BitVector() && EltSz == 32)
4886     return false;
4887
4888   return true;
4889 }
4890
4891 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4892   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4893   if (EltSz == 64)
4894     return false;
4895
4896   unsigned NumElts = VT.getVectorNumElements();
4897   WhichResult = (M[0] == 0 ? 0 : 1);
4898   unsigned Idx = WhichResult * NumElts / 2;
4899   for (unsigned i = 0; i != NumElts; i += 2) {
4900     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4901         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4902       return false;
4903     Idx += 1;
4904   }
4905
4906   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4907   if (VT.is64BitVector() && EltSz == 32)
4908     return false;
4909
4910   return true;
4911 }
4912
4913 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4914 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4915 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4916 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4917   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4918   if (EltSz == 64)
4919     return false;
4920
4921   unsigned NumElts = VT.getVectorNumElements();
4922   WhichResult = (M[0] == 0 ? 0 : 1);
4923   unsigned Idx = WhichResult * NumElts / 2;
4924   for (unsigned i = 0; i != NumElts; i += 2) {
4925     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4926         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4927       return false;
4928     Idx += 1;
4929   }
4930
4931   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4932   if (VT.is64BitVector() && EltSz == 32)
4933     return false;
4934
4935   return true;
4936 }
4937
4938 /// \return true if this is a reverse operation on an vector.
4939 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4940   unsigned NumElts = VT.getVectorNumElements();
4941   // Make sure the mask has the right size.
4942   if (NumElts != M.size())
4943       return false;
4944
4945   // Look for <15, ..., 3, -1, 1, 0>.
4946   for (unsigned i = 0; i != NumElts; ++i)
4947     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4948       return false;
4949
4950   return true;
4951 }
4952
4953 // If N is an integer constant that can be moved into a register in one
4954 // instruction, return an SDValue of such a constant (will become a MOV
4955 // instruction).  Otherwise return null.
4956 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4957                                      const ARMSubtarget *ST, SDLoc dl) {
4958   uint64_t Val;
4959   if (!isa<ConstantSDNode>(N))
4960     return SDValue();
4961   Val = cast<ConstantSDNode>(N)->getZExtValue();
4962
4963   if (ST->isThumb1Only()) {
4964     if (Val <= 255 || ~Val <= 255)
4965       return DAG.getConstant(Val, MVT::i32);
4966   } else {
4967     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4968       return DAG.getConstant(Val, MVT::i32);
4969   }
4970   return SDValue();
4971 }
4972
4973 // If this is a case we can't handle, return null and let the default
4974 // expansion code take care of it.
4975 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4976                                              const ARMSubtarget *ST) const {
4977   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4978   SDLoc dl(Op);
4979   EVT VT = Op.getValueType();
4980
4981   APInt SplatBits, SplatUndef;
4982   unsigned SplatBitSize;
4983   bool HasAnyUndefs;
4984   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4985     if (SplatBitSize <= 64) {
4986       // Check if an immediate VMOV works.
4987       EVT VmovVT;
4988       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4989                                       SplatUndef.getZExtValue(), SplatBitSize,
4990                                       DAG, VmovVT, VT.is128BitVector(),
4991                                       VMOVModImm);
4992       if (Val.getNode()) {
4993         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4994         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4995       }
4996
4997       // Try an immediate VMVN.
4998       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4999       Val = isNEONModifiedImm(NegatedImm,
5000                                       SplatUndef.getZExtValue(), SplatBitSize,
5001                                       DAG, VmovVT, VT.is128BitVector(),
5002                                       VMVNModImm);
5003       if (Val.getNode()) {
5004         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5005         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5006       }
5007
5008       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5009       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5010         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5011         if (ImmVal != -1) {
5012           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5013           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5014         }
5015       }
5016     }
5017   }
5018
5019   // Scan through the operands to see if only one value is used.
5020   //
5021   // As an optimisation, even if more than one value is used it may be more
5022   // profitable to splat with one value then change some lanes.
5023   //
5024   // Heuristically we decide to do this if the vector has a "dominant" value,
5025   // defined as splatted to more than half of the lanes.
5026   unsigned NumElts = VT.getVectorNumElements();
5027   bool isOnlyLowElement = true;
5028   bool usesOnlyOneValue = true;
5029   bool hasDominantValue = false;
5030   bool isConstant = true;
5031
5032   // Map of the number of times a particular SDValue appears in the
5033   // element list.
5034   DenseMap<SDValue, unsigned> ValueCounts;
5035   SDValue Value;
5036   for (unsigned i = 0; i < NumElts; ++i) {
5037     SDValue V = Op.getOperand(i);
5038     if (V.getOpcode() == ISD::UNDEF)
5039       continue;
5040     if (i > 0)
5041       isOnlyLowElement = false;
5042     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5043       isConstant = false;
5044
5045     ValueCounts.insert(std::make_pair(V, 0));
5046     unsigned &Count = ValueCounts[V];
5047
5048     // Is this value dominant? (takes up more than half of the lanes)
5049     if (++Count > (NumElts / 2)) {
5050       hasDominantValue = true;
5051       Value = V;
5052     }
5053   }
5054   if (ValueCounts.size() != 1)
5055     usesOnlyOneValue = false;
5056   if (!Value.getNode() && ValueCounts.size() > 0)
5057     Value = ValueCounts.begin()->first;
5058
5059   if (ValueCounts.size() == 0)
5060     return DAG.getUNDEF(VT);
5061
5062   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5063   // Keep going if we are hitting this case.
5064   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5065     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5066
5067   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5068
5069   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5070   // i32 and try again.
5071   if (hasDominantValue && EltSize <= 32) {
5072     if (!isConstant) {
5073       SDValue N;
5074
5075       // If we are VDUPing a value that comes directly from a vector, that will
5076       // cause an unnecessary move to and from a GPR, where instead we could
5077       // just use VDUPLANE. We can only do this if the lane being extracted
5078       // is at a constant index, as the VDUP from lane instructions only have
5079       // constant-index forms.
5080       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5081           isa<ConstantSDNode>(Value->getOperand(1))) {
5082         // We need to create a new undef vector to use for the VDUPLANE if the
5083         // size of the vector from which we get the value is different than the
5084         // size of the vector that we need to create. We will insert the element
5085         // such that the register coalescer will remove unnecessary copies.
5086         if (VT != Value->getOperand(0).getValueType()) {
5087           ConstantSDNode *constIndex;
5088           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5089           assert(constIndex && "The index is not a constant!");
5090           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5091                              VT.getVectorNumElements();
5092           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5093                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5094                         Value, DAG.getConstant(index, MVT::i32)),
5095                            DAG.getConstant(index, MVT::i32));
5096         } else
5097           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5098                         Value->getOperand(0), Value->getOperand(1));
5099       } else
5100         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5101
5102       if (!usesOnlyOneValue) {
5103         // The dominant value was splatted as 'N', but we now have to insert
5104         // all differing elements.
5105         for (unsigned I = 0; I < NumElts; ++I) {
5106           if (Op.getOperand(I) == Value)
5107             continue;
5108           SmallVector<SDValue, 3> Ops;
5109           Ops.push_back(N);
5110           Ops.push_back(Op.getOperand(I));
5111           Ops.push_back(DAG.getConstant(I, MVT::i32));
5112           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5113         }
5114       }
5115       return N;
5116     }
5117     if (VT.getVectorElementType().isFloatingPoint()) {
5118       SmallVector<SDValue, 8> Ops;
5119       for (unsigned i = 0; i < NumElts; ++i)
5120         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5121                                   Op.getOperand(i)));
5122       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5123       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5124       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5125       if (Val.getNode())
5126         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5127     }
5128     if (usesOnlyOneValue) {
5129       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5130       if (isConstant && Val.getNode())
5131         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5132     }
5133   }
5134
5135   // If all elements are constants and the case above didn't get hit, fall back
5136   // to the default expansion, which will generate a load from the constant
5137   // pool.
5138   if (isConstant)
5139     return SDValue();
5140
5141   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5142   if (NumElts >= 4) {
5143     SDValue shuffle = ReconstructShuffle(Op, DAG);
5144     if (shuffle != SDValue())
5145       return shuffle;
5146   }
5147
5148   // Vectors with 32- or 64-bit elements can be built by directly assigning
5149   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5150   // will be legalized.
5151   if (EltSize >= 32) {
5152     // Do the expansion with floating-point types, since that is what the VFP
5153     // registers are defined to use, and since i64 is not legal.
5154     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5155     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5156     SmallVector<SDValue, 8> Ops;
5157     for (unsigned i = 0; i < NumElts; ++i)
5158       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5159     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5160     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5161   }
5162
5163   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5164   // know the default expansion would otherwise fall back on something even
5165   // worse. For a vector with one or two non-undef values, that's
5166   // scalar_to_vector for the elements followed by a shuffle (provided the
5167   // shuffle is valid for the target) and materialization element by element
5168   // on the stack followed by a load for everything else.
5169   if (!isConstant && !usesOnlyOneValue) {
5170     SDValue Vec = DAG.getUNDEF(VT);
5171     for (unsigned i = 0 ; i < NumElts; ++i) {
5172       SDValue V = Op.getOperand(i);
5173       if (V.getOpcode() == ISD::UNDEF)
5174         continue;
5175       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5176       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5177     }
5178     return Vec;
5179   }
5180
5181   return SDValue();
5182 }
5183
5184 // Gather data to see if the operation can be modelled as a
5185 // shuffle in combination with VEXTs.
5186 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5187                                               SelectionDAG &DAG) const {
5188   SDLoc dl(Op);
5189   EVT VT = Op.getValueType();
5190   unsigned NumElts = VT.getVectorNumElements();
5191
5192   SmallVector<SDValue, 2> SourceVecs;
5193   SmallVector<unsigned, 2> MinElts;
5194   SmallVector<unsigned, 2> MaxElts;
5195
5196   for (unsigned i = 0; i < NumElts; ++i) {
5197     SDValue V = Op.getOperand(i);
5198     if (V.getOpcode() == ISD::UNDEF)
5199       continue;
5200     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5201       // A shuffle can only come from building a vector from various
5202       // elements of other vectors.
5203       return SDValue();
5204     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5205                VT.getVectorElementType()) {
5206       // This code doesn't know how to handle shuffles where the vector
5207       // element types do not match (this happens because type legalization
5208       // promotes the return type of EXTRACT_VECTOR_ELT).
5209       // FIXME: It might be appropriate to extend this code to handle
5210       // mismatched types.
5211       return SDValue();
5212     }
5213
5214     // Record this extraction against the appropriate vector if possible...
5215     SDValue SourceVec = V.getOperand(0);
5216     // If the element number isn't a constant, we can't effectively
5217     // analyze what's going on.
5218     if (!isa<ConstantSDNode>(V.getOperand(1)))
5219       return SDValue();
5220     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5221     bool FoundSource = false;
5222     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5223       if (SourceVecs[j] == SourceVec) {
5224         if (MinElts[j] > EltNo)
5225           MinElts[j] = EltNo;
5226         if (MaxElts[j] < EltNo)
5227           MaxElts[j] = EltNo;
5228         FoundSource = true;
5229         break;
5230       }
5231     }
5232
5233     // Or record a new source if not...
5234     if (!FoundSource) {
5235       SourceVecs.push_back(SourceVec);
5236       MinElts.push_back(EltNo);
5237       MaxElts.push_back(EltNo);
5238     }
5239   }
5240
5241   // Currently only do something sane when at most two source vectors
5242   // involved.
5243   if (SourceVecs.size() > 2)
5244     return SDValue();
5245
5246   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5247   int VEXTOffsets[2] = {0, 0};
5248
5249   // This loop extracts the usage patterns of the source vectors
5250   // and prepares appropriate SDValues for a shuffle if possible.
5251   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5252     if (SourceVecs[i].getValueType() == VT) {
5253       // No VEXT necessary
5254       ShuffleSrcs[i] = SourceVecs[i];
5255       VEXTOffsets[i] = 0;
5256       continue;
5257     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5258       // It probably isn't worth padding out a smaller vector just to
5259       // break it down again in a shuffle.
5260       return SDValue();
5261     }
5262
5263     // Since only 64-bit and 128-bit vectors are legal on ARM and
5264     // we've eliminated the other cases...
5265     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5266            "unexpected vector sizes in ReconstructShuffle");
5267
5268     if (MaxElts[i] - MinElts[i] >= NumElts) {
5269       // Span too large for a VEXT to cope
5270       return SDValue();
5271     }
5272
5273     if (MinElts[i] >= NumElts) {
5274       // The extraction can just take the second half
5275       VEXTOffsets[i] = NumElts;
5276       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5277                                    SourceVecs[i],
5278                                    DAG.getIntPtrConstant(NumElts));
5279     } else if (MaxElts[i] < NumElts) {
5280       // The extraction can just take the first half
5281       VEXTOffsets[i] = 0;
5282       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5283                                    SourceVecs[i],
5284                                    DAG.getIntPtrConstant(0));
5285     } else {
5286       // An actual VEXT is needed
5287       VEXTOffsets[i] = MinElts[i];
5288       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5289                                      SourceVecs[i],
5290                                      DAG.getIntPtrConstant(0));
5291       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5292                                      SourceVecs[i],
5293                                      DAG.getIntPtrConstant(NumElts));
5294       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5295                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5296     }
5297   }
5298
5299   SmallVector<int, 8> Mask;
5300
5301   for (unsigned i = 0; i < NumElts; ++i) {
5302     SDValue Entry = Op.getOperand(i);
5303     if (Entry.getOpcode() == ISD::UNDEF) {
5304       Mask.push_back(-1);
5305       continue;
5306     }
5307
5308     SDValue ExtractVec = Entry.getOperand(0);
5309     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5310                                           .getOperand(1))->getSExtValue();
5311     if (ExtractVec == SourceVecs[0]) {
5312       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5313     } else {
5314       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5315     }
5316   }
5317
5318   // Final check before we try to produce nonsense...
5319   if (isShuffleMaskLegal(Mask, VT))
5320     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5321                                 &Mask[0]);
5322
5323   return SDValue();
5324 }
5325
5326 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5327 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5328 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5329 /// are assumed to be legal.
5330 bool
5331 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5332                                       EVT VT) const {
5333   if (VT.getVectorNumElements() == 4 &&
5334       (VT.is128BitVector() || VT.is64BitVector())) {
5335     unsigned PFIndexes[4];
5336     for (unsigned i = 0; i != 4; ++i) {
5337       if (M[i] < 0)
5338         PFIndexes[i] = 8;
5339       else
5340         PFIndexes[i] = M[i];
5341     }
5342
5343     // Compute the index in the perfect shuffle table.
5344     unsigned PFTableIndex =
5345       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5346     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5347     unsigned Cost = (PFEntry >> 30);
5348
5349     if (Cost <= 4)
5350       return true;
5351   }
5352
5353   bool ReverseVEXT;
5354   unsigned Imm, WhichResult;
5355
5356   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5357   return (EltSize >= 32 ||
5358           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5359           isVREVMask(M, VT, 64) ||
5360           isVREVMask(M, VT, 32) ||
5361           isVREVMask(M, VT, 16) ||
5362           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5363           isVTBLMask(M, VT) ||
5364           isVTRNMask(M, VT, WhichResult) ||
5365           isVUZPMask(M, VT, WhichResult) ||
5366           isVZIPMask(M, VT, WhichResult) ||
5367           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5368           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5369           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5370           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5371 }
5372
5373 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5374 /// the specified operations to build the shuffle.
5375 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5376                                       SDValue RHS, SelectionDAG &DAG,
5377                                       SDLoc dl) {
5378   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5379   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5380   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5381
5382   enum {
5383     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5384     OP_VREV,
5385     OP_VDUP0,
5386     OP_VDUP1,
5387     OP_VDUP2,
5388     OP_VDUP3,
5389     OP_VEXT1,
5390     OP_VEXT2,
5391     OP_VEXT3,
5392     OP_VUZPL, // VUZP, left result
5393     OP_VUZPR, // VUZP, right result
5394     OP_VZIPL, // VZIP, left result
5395     OP_VZIPR, // VZIP, right result
5396     OP_VTRNL, // VTRN, left result
5397     OP_VTRNR  // VTRN, right result
5398   };
5399
5400   if (OpNum == OP_COPY) {
5401     if (LHSID == (1*9+2)*9+3) return LHS;
5402     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5403     return RHS;
5404   }
5405
5406   SDValue OpLHS, OpRHS;
5407   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5408   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5409   EVT VT = OpLHS.getValueType();
5410
5411   switch (OpNum) {
5412   default: llvm_unreachable("Unknown shuffle opcode!");
5413   case OP_VREV:
5414     // VREV divides the vector in half and swaps within the half.
5415     if (VT.getVectorElementType() == MVT::i32 ||
5416         VT.getVectorElementType() == MVT::f32)
5417       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5418     // vrev <4 x i16> -> VREV32
5419     if (VT.getVectorElementType() == MVT::i16)
5420       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5421     // vrev <4 x i8> -> VREV16
5422     assert(VT.getVectorElementType() == MVT::i8);
5423     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5424   case OP_VDUP0:
5425   case OP_VDUP1:
5426   case OP_VDUP2:
5427   case OP_VDUP3:
5428     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5429                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5430   case OP_VEXT1:
5431   case OP_VEXT2:
5432   case OP_VEXT3:
5433     return DAG.getNode(ARMISD::VEXT, dl, VT,
5434                        OpLHS, OpRHS,
5435                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5436   case OP_VUZPL:
5437   case OP_VUZPR:
5438     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5439                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5440   case OP_VZIPL:
5441   case OP_VZIPR:
5442     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5443                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5444   case OP_VTRNL:
5445   case OP_VTRNR:
5446     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5447                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5448   }
5449 }
5450
5451 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5452                                        ArrayRef<int> ShuffleMask,
5453                                        SelectionDAG &DAG) {
5454   // Check to see if we can use the VTBL instruction.
5455   SDValue V1 = Op.getOperand(0);
5456   SDValue V2 = Op.getOperand(1);
5457   SDLoc DL(Op);
5458
5459   SmallVector<SDValue, 8> VTBLMask;
5460   for (ArrayRef<int>::iterator
5461          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5462     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5463
5464   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5465     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5466                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5467
5468   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5469                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5470 }
5471
5472 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5473                                                       SelectionDAG &DAG) {
5474   SDLoc DL(Op);
5475   SDValue OpLHS = Op.getOperand(0);
5476   EVT VT = OpLHS.getValueType();
5477
5478   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5479          "Expect an v8i16/v16i8 type");
5480   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5481   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5482   // extract the first 8 bytes into the top double word and the last 8 bytes
5483   // into the bottom double word. The v8i16 case is similar.
5484   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5485   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5486                      DAG.getConstant(ExtractNum, MVT::i32));
5487 }
5488
5489 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5490   SDValue V1 = Op.getOperand(0);
5491   SDValue V2 = Op.getOperand(1);
5492   SDLoc dl(Op);
5493   EVT VT = Op.getValueType();
5494   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5495
5496   // Convert shuffles that are directly supported on NEON to target-specific
5497   // DAG nodes, instead of keeping them as shuffles and matching them again
5498   // during code selection.  This is more efficient and avoids the possibility
5499   // of inconsistencies between legalization and selection.
5500   // FIXME: floating-point vectors should be canonicalized to integer vectors
5501   // of the same time so that they get CSEd properly.
5502   ArrayRef<int> ShuffleMask = SVN->getMask();
5503
5504   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5505   if (EltSize <= 32) {
5506     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5507       int Lane = SVN->getSplatIndex();
5508       // If this is undef splat, generate it via "just" vdup, if possible.
5509       if (Lane == -1) Lane = 0;
5510
5511       // Test if V1 is a SCALAR_TO_VECTOR.
5512       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5513         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5514       }
5515       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5516       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5517       // reaches it).
5518       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5519           !isa<ConstantSDNode>(V1.getOperand(0))) {
5520         bool IsScalarToVector = true;
5521         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5522           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5523             IsScalarToVector = false;
5524             break;
5525           }
5526         if (IsScalarToVector)
5527           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5528       }
5529       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5530                          DAG.getConstant(Lane, MVT::i32));
5531     }
5532
5533     bool ReverseVEXT;
5534     unsigned Imm;
5535     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5536       if (ReverseVEXT)
5537         std::swap(V1, V2);
5538       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5539                          DAG.getConstant(Imm, MVT::i32));
5540     }
5541
5542     if (isVREVMask(ShuffleMask, VT, 64))
5543       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5544     if (isVREVMask(ShuffleMask, VT, 32))
5545       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5546     if (isVREVMask(ShuffleMask, VT, 16))
5547       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5548
5549     if (V2->getOpcode() == ISD::UNDEF &&
5550         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5551       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5552                          DAG.getConstant(Imm, MVT::i32));
5553     }
5554
5555     // Check for Neon shuffles that modify both input vectors in place.
5556     // If both results are used, i.e., if there are two shuffles with the same
5557     // source operands and with masks corresponding to both results of one of
5558     // these operations, DAG memoization will ensure that a single node is
5559     // used for both shuffles.
5560     unsigned WhichResult;
5561     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5562       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5563                          V1, V2).getValue(WhichResult);
5564     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5565       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5566                          V1, V2).getValue(WhichResult);
5567     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5568       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5569                          V1, V2).getValue(WhichResult);
5570
5571     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5572       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5573                          V1, V1).getValue(WhichResult);
5574     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5575       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5576                          V1, V1).getValue(WhichResult);
5577     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5578       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5579                          V1, V1).getValue(WhichResult);
5580   }
5581
5582   // If the shuffle is not directly supported and it has 4 elements, use
5583   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5584   unsigned NumElts = VT.getVectorNumElements();
5585   if (NumElts == 4) {
5586     unsigned PFIndexes[4];
5587     for (unsigned i = 0; i != 4; ++i) {
5588       if (ShuffleMask[i] < 0)
5589         PFIndexes[i] = 8;
5590       else
5591         PFIndexes[i] = ShuffleMask[i];
5592     }
5593
5594     // Compute the index in the perfect shuffle table.
5595     unsigned PFTableIndex =
5596       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5597     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5598     unsigned Cost = (PFEntry >> 30);
5599
5600     if (Cost <= 4)
5601       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5602   }
5603
5604   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5605   if (EltSize >= 32) {
5606     // Do the expansion with floating-point types, since that is what the VFP
5607     // registers are defined to use, and since i64 is not legal.
5608     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5609     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5610     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5611     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5612     SmallVector<SDValue, 8> Ops;
5613     for (unsigned i = 0; i < NumElts; ++i) {
5614       if (ShuffleMask[i] < 0)
5615         Ops.push_back(DAG.getUNDEF(EltVT));
5616       else
5617         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5618                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5619                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5620                                                   MVT::i32)));
5621     }
5622     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5623     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5624   }
5625
5626   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5627     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5628
5629   if (VT == MVT::v8i8) {
5630     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5631     if (NewOp.getNode())
5632       return NewOp;
5633   }
5634
5635   return SDValue();
5636 }
5637
5638 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5639   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5640   SDValue Lane = Op.getOperand(2);
5641   if (!isa<ConstantSDNode>(Lane))
5642     return SDValue();
5643
5644   return Op;
5645 }
5646
5647 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5648   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5649   SDValue Lane = Op.getOperand(1);
5650   if (!isa<ConstantSDNode>(Lane))
5651     return SDValue();
5652
5653   SDValue Vec = Op.getOperand(0);
5654   if (Op.getValueType() == MVT::i32 &&
5655       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5656     SDLoc dl(Op);
5657     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5658   }
5659
5660   return Op;
5661 }
5662
5663 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5664   // The only time a CONCAT_VECTORS operation can have legal types is when
5665   // two 64-bit vectors are concatenated to a 128-bit vector.
5666   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5667          "unexpected CONCAT_VECTORS");
5668   SDLoc dl(Op);
5669   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5670   SDValue Op0 = Op.getOperand(0);
5671   SDValue Op1 = Op.getOperand(1);
5672   if (Op0.getOpcode() != ISD::UNDEF)
5673     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5674                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5675                       DAG.getIntPtrConstant(0));
5676   if (Op1.getOpcode() != ISD::UNDEF)
5677     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5678                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5679                       DAG.getIntPtrConstant(1));
5680   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5681 }
5682
5683 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5684 /// element has been zero/sign-extended, depending on the isSigned parameter,
5685 /// from an integer type half its size.
5686 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5687                                    bool isSigned) {
5688   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5689   EVT VT = N->getValueType(0);
5690   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5691     SDNode *BVN = N->getOperand(0).getNode();
5692     if (BVN->getValueType(0) != MVT::v4i32 ||
5693         BVN->getOpcode() != ISD::BUILD_VECTOR)
5694       return false;
5695     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5696     unsigned HiElt = 1 - LoElt;
5697     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5698     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5699     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5700     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5701     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5702       return false;
5703     if (isSigned) {
5704       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5705           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5706         return true;
5707     } else {
5708       if (Hi0->isNullValue() && Hi1->isNullValue())
5709         return true;
5710     }
5711     return false;
5712   }
5713
5714   if (N->getOpcode() != ISD::BUILD_VECTOR)
5715     return false;
5716
5717   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5718     SDNode *Elt = N->getOperand(i).getNode();
5719     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5720       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5721       unsigned HalfSize = EltSize / 2;
5722       if (isSigned) {
5723         if (!isIntN(HalfSize, C->getSExtValue()))
5724           return false;
5725       } else {
5726         if (!isUIntN(HalfSize, C->getZExtValue()))
5727           return false;
5728       }
5729       continue;
5730     }
5731     return false;
5732   }
5733
5734   return true;
5735 }
5736
5737 /// isSignExtended - Check if a node is a vector value that is sign-extended
5738 /// or a constant BUILD_VECTOR with sign-extended elements.
5739 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5740   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5741     return true;
5742   if (isExtendedBUILD_VECTOR(N, DAG, true))
5743     return true;
5744   return false;
5745 }
5746
5747 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5748 /// or a constant BUILD_VECTOR with zero-extended elements.
5749 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5750   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5751     return true;
5752   if (isExtendedBUILD_VECTOR(N, DAG, false))
5753     return true;
5754   return false;
5755 }
5756
5757 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5758   if (OrigVT.getSizeInBits() >= 64)
5759     return OrigVT;
5760
5761   assert(OrigVT.isSimple() && "Expecting a simple value type");
5762
5763   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5764   switch (OrigSimpleTy) {
5765   default: llvm_unreachable("Unexpected Vector Type");
5766   case MVT::v2i8:
5767   case MVT::v2i16:
5768      return MVT::v2i32;
5769   case MVT::v4i8:
5770     return  MVT::v4i16;
5771   }
5772 }
5773
5774 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5775 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5776 /// We insert the required extension here to get the vector to fill a D register.
5777 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5778                                             const EVT &OrigTy,
5779                                             const EVT &ExtTy,
5780                                             unsigned ExtOpcode) {
5781   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5782   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5783   // 64-bits we need to insert a new extension so that it will be 64-bits.
5784   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5785   if (OrigTy.getSizeInBits() >= 64)
5786     return N;
5787
5788   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5789   EVT NewVT = getExtensionTo64Bits(OrigTy);
5790
5791   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5792 }
5793
5794 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5795 /// does not do any sign/zero extension. If the original vector is less
5796 /// than 64 bits, an appropriate extension will be added after the load to
5797 /// reach a total size of 64 bits. We have to add the extension separately
5798 /// because ARM does not have a sign/zero extending load for vectors.
5799 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5800   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5801
5802   // The load already has the right type.
5803   if (ExtendedTy == LD->getMemoryVT())
5804     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5805                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5806                 LD->isNonTemporal(), LD->isInvariant(),
5807                 LD->getAlignment());
5808
5809   // We need to create a zextload/sextload. We cannot just create a load
5810   // followed by a zext/zext node because LowerMUL is also run during normal
5811   // operation legalization where we can't create illegal types.
5812   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5813                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5814                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5815                         LD->isNonTemporal(), LD->getAlignment());
5816 }
5817
5818 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5819 /// extending load, or BUILD_VECTOR with extended elements, return the
5820 /// unextended value. The unextended vector should be 64 bits so that it can
5821 /// be used as an operand to a VMULL instruction. If the original vector size
5822 /// before extension is less than 64 bits we add a an extension to resize
5823 /// the vector to 64 bits.
5824 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5825   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5826     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5827                                         N->getOperand(0)->getValueType(0),
5828                                         N->getValueType(0),
5829                                         N->getOpcode());
5830
5831   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5832     return SkipLoadExtensionForVMULL(LD, DAG);
5833
5834   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5835   // have been legalized as a BITCAST from v4i32.
5836   if (N->getOpcode() == ISD::BITCAST) {
5837     SDNode *BVN = N->getOperand(0).getNode();
5838     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5839            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5840     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5841     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5842                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5843   }
5844   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5845   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5846   EVT VT = N->getValueType(0);
5847   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5848   unsigned NumElts = VT.getVectorNumElements();
5849   MVT TruncVT = MVT::getIntegerVT(EltSize);
5850   SmallVector<SDValue, 8> Ops;
5851   for (unsigned i = 0; i != NumElts; ++i) {
5852     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5853     const APInt &CInt = C->getAPIntValue();
5854     // Element types smaller than 32 bits are not legal, so use i32 elements.
5855     // The values are implicitly truncated so sext vs. zext doesn't matter.
5856     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5857   }
5858   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5859                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5860 }
5861
5862 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5863   unsigned Opcode = N->getOpcode();
5864   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5865     SDNode *N0 = N->getOperand(0).getNode();
5866     SDNode *N1 = N->getOperand(1).getNode();
5867     return N0->hasOneUse() && N1->hasOneUse() &&
5868       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5869   }
5870   return false;
5871 }
5872
5873 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5874   unsigned Opcode = N->getOpcode();
5875   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5876     SDNode *N0 = N->getOperand(0).getNode();
5877     SDNode *N1 = N->getOperand(1).getNode();
5878     return N0->hasOneUse() && N1->hasOneUse() &&
5879       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5880   }
5881   return false;
5882 }
5883
5884 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5885   // Multiplications are only custom-lowered for 128-bit vectors so that
5886   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5887   EVT VT = Op.getValueType();
5888   assert(VT.is128BitVector() && VT.isInteger() &&
5889          "unexpected type for custom-lowering ISD::MUL");
5890   SDNode *N0 = Op.getOperand(0).getNode();
5891   SDNode *N1 = Op.getOperand(1).getNode();
5892   unsigned NewOpc = 0;
5893   bool isMLA = false;
5894   bool isN0SExt = isSignExtended(N0, DAG);
5895   bool isN1SExt = isSignExtended(N1, DAG);
5896   if (isN0SExt && isN1SExt)
5897     NewOpc = ARMISD::VMULLs;
5898   else {
5899     bool isN0ZExt = isZeroExtended(N0, DAG);
5900     bool isN1ZExt = isZeroExtended(N1, DAG);
5901     if (isN0ZExt && isN1ZExt)
5902       NewOpc = ARMISD::VMULLu;
5903     else if (isN1SExt || isN1ZExt) {
5904       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5905       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5906       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5907         NewOpc = ARMISD::VMULLs;
5908         isMLA = true;
5909       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5910         NewOpc = ARMISD::VMULLu;
5911         isMLA = true;
5912       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5913         std::swap(N0, N1);
5914         NewOpc = ARMISD::VMULLu;
5915         isMLA = true;
5916       }
5917     }
5918
5919     if (!NewOpc) {
5920       if (VT == MVT::v2i64)
5921         // Fall through to expand this.  It is not legal.
5922         return SDValue();
5923       else
5924         // Other vector multiplications are legal.
5925         return Op;
5926     }
5927   }
5928
5929   // Legalize to a VMULL instruction.
5930   SDLoc DL(Op);
5931   SDValue Op0;
5932   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5933   if (!isMLA) {
5934     Op0 = SkipExtensionForVMULL(N0, DAG);
5935     assert(Op0.getValueType().is64BitVector() &&
5936            Op1.getValueType().is64BitVector() &&
5937            "unexpected types for extended operands to VMULL");
5938     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5939   }
5940
5941   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5942   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5943   //   vmull q0, d4, d6
5944   //   vmlal q0, d5, d6
5945   // is faster than
5946   //   vaddl q0, d4, d5
5947   //   vmovl q1, d6
5948   //   vmul  q0, q0, q1
5949   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5950   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5951   EVT Op1VT = Op1.getValueType();
5952   return DAG.getNode(N0->getOpcode(), DL, VT,
5953                      DAG.getNode(NewOpc, DL, VT,
5954                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5955                      DAG.getNode(NewOpc, DL, VT,
5956                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5957 }
5958
5959 static SDValue
5960 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5961   // Convert to float
5962   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5963   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5964   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5965   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5966   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5967   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5968   // Get reciprocal estimate.
5969   // float4 recip = vrecpeq_f32(yf);
5970   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5971                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5972   // Because char has a smaller range than uchar, we can actually get away
5973   // without any newton steps.  This requires that we use a weird bias
5974   // of 0xb000, however (again, this has been exhaustively tested).
5975   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5976   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5977   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5978   Y = DAG.getConstant(0xb000, MVT::i32);
5979   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5980   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5981   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5982   // Convert back to short.
5983   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5984   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5985   return X;
5986 }
5987
5988 static SDValue
5989 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5990   SDValue N2;
5991   // Convert to float.
5992   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5993   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5994   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5995   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5996   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5997   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5998
5999   // Use reciprocal estimate and one refinement step.
6000   // float4 recip = vrecpeq_f32(yf);
6001   // recip *= vrecpsq_f32(yf, recip);
6002   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6003                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6004   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6005                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6006                    N1, N2);
6007   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6008   // Because short has a smaller range than ushort, we can actually get away
6009   // with only a single newton step.  This requires that we use a weird bias
6010   // of 89, however (again, this has been exhaustively tested).
6011   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6012   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6013   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6014   N1 = DAG.getConstant(0x89, MVT::i32);
6015   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6016   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6017   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6018   // Convert back to integer and return.
6019   // return vmovn_s32(vcvt_s32_f32(result));
6020   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6021   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6022   return N0;
6023 }
6024
6025 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6026   EVT VT = Op.getValueType();
6027   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6028          "unexpected type for custom-lowering ISD::SDIV");
6029
6030   SDLoc dl(Op);
6031   SDValue N0 = Op.getOperand(0);
6032   SDValue N1 = Op.getOperand(1);
6033   SDValue N2, N3;
6034
6035   if (VT == MVT::v8i8) {
6036     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6037     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6038
6039     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6040                      DAG.getIntPtrConstant(4));
6041     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6042                      DAG.getIntPtrConstant(4));
6043     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6044                      DAG.getIntPtrConstant(0));
6045     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6046                      DAG.getIntPtrConstant(0));
6047
6048     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6049     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6050
6051     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6052     N0 = LowerCONCAT_VECTORS(N0, DAG);
6053
6054     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6055     return N0;
6056   }
6057   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6058 }
6059
6060 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6061   EVT VT = Op.getValueType();
6062   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6063          "unexpected type for custom-lowering ISD::UDIV");
6064
6065   SDLoc dl(Op);
6066   SDValue N0 = Op.getOperand(0);
6067   SDValue N1 = Op.getOperand(1);
6068   SDValue N2, N3;
6069
6070   if (VT == MVT::v8i8) {
6071     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6072     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6073
6074     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6075                      DAG.getIntPtrConstant(4));
6076     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6077                      DAG.getIntPtrConstant(4));
6078     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6079                      DAG.getIntPtrConstant(0));
6080     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6081                      DAG.getIntPtrConstant(0));
6082
6083     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6084     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6085
6086     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6087     N0 = LowerCONCAT_VECTORS(N0, DAG);
6088
6089     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6090                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6091                      N0);
6092     return N0;
6093   }
6094
6095   // v4i16 sdiv ... Convert to float.
6096   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6097   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6098   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6099   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6100   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6101   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6102
6103   // Use reciprocal estimate and two refinement steps.
6104   // float4 recip = vrecpeq_f32(yf);
6105   // recip *= vrecpsq_f32(yf, recip);
6106   // recip *= vrecpsq_f32(yf, recip);
6107   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6108                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6109   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6110                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6111                    BN1, N2);
6112   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6113   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6114                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6115                    BN1, N2);
6116   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6117   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6118   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6119   // and that it will never cause us to return an answer too large).
6120   // float4 result = as_float4(as_int4(xf*recip) + 2);
6121   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6122   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6123   N1 = DAG.getConstant(2, MVT::i32);
6124   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6125   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6126   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6127   // Convert back to integer and return.
6128   // return vmovn_u32(vcvt_s32_f32(result));
6129   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6130   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6131   return N0;
6132 }
6133
6134 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6135   EVT VT = Op.getNode()->getValueType(0);
6136   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6137
6138   unsigned Opc;
6139   bool ExtraOp = false;
6140   switch (Op.getOpcode()) {
6141   default: llvm_unreachable("Invalid code");
6142   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6143   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6144   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6145   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6146   }
6147
6148   if (!ExtraOp)
6149     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6150                        Op.getOperand(1));
6151   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6152                      Op.getOperand(1), Op.getOperand(2));
6153 }
6154
6155 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6156   assert(Subtarget->isTargetDarwin());
6157
6158   // For iOS, we want to call an alternative entry point: __sincos_stret,
6159   // return values are passed via sret.
6160   SDLoc dl(Op);
6161   SDValue Arg = Op.getOperand(0);
6162   EVT ArgVT = Arg.getValueType();
6163   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6164
6165   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6167
6168   // Pair of floats / doubles used to pass the result.
6169   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6170
6171   // Create stack object for sret.
6172   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6173   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6174   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6175   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6176
6177   ArgListTy Args;
6178   ArgListEntry Entry;
6179
6180   Entry.Node = SRet;
6181   Entry.Ty = RetTy->getPointerTo();
6182   Entry.isSExt = false;
6183   Entry.isZExt = false;
6184   Entry.isSRet = true;
6185   Args.push_back(Entry);
6186
6187   Entry.Node = Arg;
6188   Entry.Ty = ArgTy;
6189   Entry.isSExt = false;
6190   Entry.isZExt = false;
6191   Args.push_back(Entry);
6192
6193   const char *LibcallName  = (ArgVT == MVT::f64)
6194   ? "__sincos_stret" : "__sincosf_stret";
6195   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6196
6197   TargetLowering::CallLoweringInfo CLI(DAG);
6198   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6199     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6200                std::move(Args), 0)
6201     .setDiscardResult();
6202
6203   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6204
6205   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6206                                 MachinePointerInfo(), false, false, false, 0);
6207
6208   // Address of cos field.
6209   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6210                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6211   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6212                                 MachinePointerInfo(), false, false, false, 0);
6213
6214   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6215   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6216                      LoadSin.getValue(0), LoadCos.getValue(0));
6217 }
6218
6219 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6220   // Monotonic load/store is legal for all targets
6221   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6222     return Op;
6223
6224   // Acquire/Release load/store is not legal for targets without a
6225   // dmb or equivalent available.
6226   return SDValue();
6227 }
6228
6229 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6230                                     SmallVectorImpl<SDValue> &Results,
6231                                     SelectionDAG &DAG,
6232                                     const ARMSubtarget *Subtarget) {
6233   SDLoc DL(N);
6234   SDValue Cycles32, OutChain;
6235
6236   if (Subtarget->hasPerfMon()) {
6237     // Under Power Management extensions, the cycle-count is:
6238     //    mrc p15, #0, <Rt>, c9, c13, #0
6239     SDValue Ops[] = { N->getOperand(0), // Chain
6240                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6241                       DAG.getConstant(15, MVT::i32),
6242                       DAG.getConstant(0, MVT::i32),
6243                       DAG.getConstant(9, MVT::i32),
6244                       DAG.getConstant(13, MVT::i32),
6245                       DAG.getConstant(0, MVT::i32)
6246     };
6247
6248     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6249                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6250     OutChain = Cycles32.getValue(1);
6251   } else {
6252     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6253     // there are older ARM CPUs that have implementation-specific ways of
6254     // obtaining this information (FIXME!).
6255     Cycles32 = DAG.getConstant(0, MVT::i32);
6256     OutChain = DAG.getEntryNode();
6257   }
6258
6259
6260   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6261                                  Cycles32, DAG.getConstant(0, MVT::i32));
6262   Results.push_back(Cycles64);
6263   Results.push_back(OutChain);
6264 }
6265
6266 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6267   switch (Op.getOpcode()) {
6268   default: llvm_unreachable("Don't know how to custom lower this!");
6269   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6270   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6271   case ISD::GlobalAddress:
6272     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6273     default: llvm_unreachable("unknown object format");
6274     case Triple::COFF:
6275       return LowerGlobalAddressWindows(Op, DAG);
6276     case Triple::ELF:
6277       return LowerGlobalAddressELF(Op, DAG);
6278     case Triple::MachO:
6279       return LowerGlobalAddressDarwin(Op, DAG);
6280     }
6281   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6282   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6283   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6284   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6285   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6286   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6287   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6288   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6289   case ISD::SINT_TO_FP:
6290   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6291   case ISD::FP_TO_SINT:
6292   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6293   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6294   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6295   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6296   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6297   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6298   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6299   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6300                                                                Subtarget);
6301   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6302   case ISD::SHL:
6303   case ISD::SRL:
6304   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6305   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6306   case ISD::SRL_PARTS:
6307   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6308   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6309   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6310   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6311   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6312   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6313   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6314   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6315   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6316   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6317   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6318   case ISD::MUL:           return LowerMUL(Op, DAG);
6319   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6320   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6321   case ISD::ADDC:
6322   case ISD::ADDE:
6323   case ISD::SUBC:
6324   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6325   case ISD::SADDO:
6326   case ISD::UADDO:
6327   case ISD::SSUBO:
6328   case ISD::USUBO:
6329     return LowerXALUO(Op, DAG);
6330   case ISD::ATOMIC_LOAD:
6331   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6332   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6333   case ISD::SDIVREM:
6334   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6335   case ISD::DYNAMIC_STACKALLOC:
6336     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6337       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6338     llvm_unreachable("Don't know how to custom lower this!");
6339   }
6340 }
6341
6342 /// ReplaceNodeResults - Replace the results of node with an illegal result
6343 /// type with new values built out of custom code.
6344 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6345                                            SmallVectorImpl<SDValue>&Results,
6346                                            SelectionDAG &DAG) const {
6347   SDValue Res;
6348   switch (N->getOpcode()) {
6349   default:
6350     llvm_unreachable("Don't know how to custom expand this!");
6351   case ISD::BITCAST:
6352     Res = ExpandBITCAST(N, DAG);
6353     break;
6354   case ISD::SRL:
6355   case ISD::SRA:
6356     Res = Expand64BitShift(N, DAG, Subtarget);
6357     break;
6358   case ISD::READCYCLECOUNTER:
6359     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6360     return;
6361   }
6362   if (Res.getNode())
6363     Results.push_back(Res);
6364 }
6365
6366 //===----------------------------------------------------------------------===//
6367 //                           ARM Scheduler Hooks
6368 //===----------------------------------------------------------------------===//
6369
6370 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6371 /// registers the function context.
6372 void ARMTargetLowering::
6373 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6374                        MachineBasicBlock *DispatchBB, int FI) const {
6375   const TargetInstrInfo *TII =
6376       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6377   DebugLoc dl = MI->getDebugLoc();
6378   MachineFunction *MF = MBB->getParent();
6379   MachineRegisterInfo *MRI = &MF->getRegInfo();
6380   MachineConstantPool *MCP = MF->getConstantPool();
6381   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6382   const Function *F = MF->getFunction();
6383
6384   bool isThumb = Subtarget->isThumb();
6385   bool isThumb2 = Subtarget->isThumb2();
6386
6387   unsigned PCLabelId = AFI->createPICLabelUId();
6388   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6389   ARMConstantPoolValue *CPV =
6390     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6391   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6392
6393   const TargetRegisterClass *TRC = isThumb ?
6394     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6395     (const TargetRegisterClass*)&ARM::GPRRegClass;
6396
6397   // Grab constant pool and fixed stack memory operands.
6398   MachineMemOperand *CPMMO =
6399     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6400                              MachineMemOperand::MOLoad, 4, 4);
6401
6402   MachineMemOperand *FIMMOSt =
6403     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6404                              MachineMemOperand::MOStore, 4, 4);
6405
6406   // Load the address of the dispatch MBB into the jump buffer.
6407   if (isThumb2) {
6408     // Incoming value: jbuf
6409     //   ldr.n  r5, LCPI1_1
6410     //   orr    r5, r5, #1
6411     //   add    r5, pc
6412     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6413     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6414     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6415                    .addConstantPoolIndex(CPI)
6416                    .addMemOperand(CPMMO));
6417     // Set the low bit because of thumb mode.
6418     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6419     AddDefaultCC(
6420       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6421                      .addReg(NewVReg1, RegState::Kill)
6422                      .addImm(0x01)));
6423     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6424     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6425       .addReg(NewVReg2, RegState::Kill)
6426       .addImm(PCLabelId);
6427     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6428                    .addReg(NewVReg3, RegState::Kill)
6429                    .addFrameIndex(FI)
6430                    .addImm(36)  // &jbuf[1] :: pc
6431                    .addMemOperand(FIMMOSt));
6432   } else if (isThumb) {
6433     // Incoming value: jbuf
6434     //   ldr.n  r1, LCPI1_4
6435     //   add    r1, pc
6436     //   mov    r2, #1
6437     //   orrs   r1, r2
6438     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6439     //   str    r1, [r2]
6440     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6441     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6442                    .addConstantPoolIndex(CPI)
6443                    .addMemOperand(CPMMO));
6444     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6445     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6446       .addReg(NewVReg1, RegState::Kill)
6447       .addImm(PCLabelId);
6448     // Set the low bit because of thumb mode.
6449     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6450     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6451                    .addReg(ARM::CPSR, RegState::Define)
6452                    .addImm(1));
6453     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6454     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6455                    .addReg(ARM::CPSR, RegState::Define)
6456                    .addReg(NewVReg2, RegState::Kill)
6457                    .addReg(NewVReg3, RegState::Kill));
6458     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6459     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6460                    .addFrameIndex(FI)
6461                    .addImm(36)); // &jbuf[1] :: pc
6462     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6463                    .addReg(NewVReg4, RegState::Kill)
6464                    .addReg(NewVReg5, RegState::Kill)
6465                    .addImm(0)
6466                    .addMemOperand(FIMMOSt));
6467   } else {
6468     // Incoming value: jbuf
6469     //   ldr  r1, LCPI1_1
6470     //   add  r1, pc, r1
6471     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6472     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6473     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6474                    .addConstantPoolIndex(CPI)
6475                    .addImm(0)
6476                    .addMemOperand(CPMMO));
6477     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6478     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6479                    .addReg(NewVReg1, RegState::Kill)
6480                    .addImm(PCLabelId));
6481     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6482                    .addReg(NewVReg2, RegState::Kill)
6483                    .addFrameIndex(FI)
6484                    .addImm(36)  // &jbuf[1] :: pc
6485                    .addMemOperand(FIMMOSt));
6486   }
6487 }
6488
6489 MachineBasicBlock *ARMTargetLowering::
6490 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6491   const TargetInstrInfo *TII =
6492       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6493   DebugLoc dl = MI->getDebugLoc();
6494   MachineFunction *MF = MBB->getParent();
6495   MachineRegisterInfo *MRI = &MF->getRegInfo();
6496   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6497   MachineFrameInfo *MFI = MF->getFrameInfo();
6498   int FI = MFI->getFunctionContextIndex();
6499
6500   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6501     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6502     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6503
6504   // Get a mapping of the call site numbers to all of the landing pads they're
6505   // associated with.
6506   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6507   unsigned MaxCSNum = 0;
6508   MachineModuleInfo &MMI = MF->getMMI();
6509   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6510        ++BB) {
6511     if (!BB->isLandingPad()) continue;
6512
6513     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6514     // pad.
6515     for (MachineBasicBlock::iterator
6516            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6517       if (!II->isEHLabel()) continue;
6518
6519       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6520       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6521
6522       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6523       for (SmallVectorImpl<unsigned>::iterator
6524              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6525            CSI != CSE; ++CSI) {
6526         CallSiteNumToLPad[*CSI].push_back(BB);
6527         MaxCSNum = std::max(MaxCSNum, *CSI);
6528       }
6529       break;
6530     }
6531   }
6532
6533   // Get an ordered list of the machine basic blocks for the jump table.
6534   std::vector<MachineBasicBlock*> LPadList;
6535   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6536   LPadList.reserve(CallSiteNumToLPad.size());
6537   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6538     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6539     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6540            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6541       LPadList.push_back(*II);
6542       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6543     }
6544   }
6545
6546   assert(!LPadList.empty() &&
6547          "No landing pad destinations for the dispatch jump table!");
6548
6549   // Create the jump table and associated information.
6550   MachineJumpTableInfo *JTI =
6551     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6552   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6553   unsigned UId = AFI->createJumpTableUId();
6554   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6555
6556   // Create the MBBs for the dispatch code.
6557
6558   // Shove the dispatch's address into the return slot in the function context.
6559   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6560   DispatchBB->setIsLandingPad();
6561
6562   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6563   unsigned trap_opcode;
6564   if (Subtarget->isThumb())
6565     trap_opcode = ARM::tTRAP;
6566   else
6567     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6568
6569   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6570   DispatchBB->addSuccessor(TrapBB);
6571
6572   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6573   DispatchBB->addSuccessor(DispContBB);
6574
6575   // Insert and MBBs.
6576   MF->insert(MF->end(), DispatchBB);
6577   MF->insert(MF->end(), DispContBB);
6578   MF->insert(MF->end(), TrapBB);
6579
6580   // Insert code into the entry block that creates and registers the function
6581   // context.
6582   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6583
6584   MachineMemOperand *FIMMOLd =
6585     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6586                              MachineMemOperand::MOLoad |
6587                              MachineMemOperand::MOVolatile, 4, 4);
6588
6589   MachineInstrBuilder MIB;
6590   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6591
6592   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6593   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6594
6595   // Add a register mask with no preserved registers.  This results in all
6596   // registers being marked as clobbered.
6597   MIB.addRegMask(RI.getNoPreservedMask());
6598
6599   unsigned NumLPads = LPadList.size();
6600   if (Subtarget->isThumb2()) {
6601     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6602     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6603                    .addFrameIndex(FI)
6604                    .addImm(4)
6605                    .addMemOperand(FIMMOLd));
6606
6607     if (NumLPads < 256) {
6608       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6609                      .addReg(NewVReg1)
6610                      .addImm(LPadList.size()));
6611     } else {
6612       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6613       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6614                      .addImm(NumLPads & 0xFFFF));
6615
6616       unsigned VReg2 = VReg1;
6617       if ((NumLPads & 0xFFFF0000) != 0) {
6618         VReg2 = MRI->createVirtualRegister(TRC);
6619         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6620                        .addReg(VReg1)
6621                        .addImm(NumLPads >> 16));
6622       }
6623
6624       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6625                      .addReg(NewVReg1)
6626                      .addReg(VReg2));
6627     }
6628
6629     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6630       .addMBB(TrapBB)
6631       .addImm(ARMCC::HI)
6632       .addReg(ARM::CPSR);
6633
6634     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6635     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6636                    .addJumpTableIndex(MJTI)
6637                    .addImm(UId));
6638
6639     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6640     AddDefaultCC(
6641       AddDefaultPred(
6642         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6643         .addReg(NewVReg3, RegState::Kill)
6644         .addReg(NewVReg1)
6645         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6646
6647     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6648       .addReg(NewVReg4, RegState::Kill)
6649       .addReg(NewVReg1)
6650       .addJumpTableIndex(MJTI)
6651       .addImm(UId);
6652   } else if (Subtarget->isThumb()) {
6653     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6654     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6655                    .addFrameIndex(FI)
6656                    .addImm(1)
6657                    .addMemOperand(FIMMOLd));
6658
6659     if (NumLPads < 256) {
6660       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6661                      .addReg(NewVReg1)
6662                      .addImm(NumLPads));
6663     } else {
6664       MachineConstantPool *ConstantPool = MF->getConstantPool();
6665       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6666       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6667
6668       // MachineConstantPool wants an explicit alignment.
6669       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6670       if (Align == 0)
6671         Align = getDataLayout()->getTypeAllocSize(C->getType());
6672       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6673
6674       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6675       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6676                      .addReg(VReg1, RegState::Define)
6677                      .addConstantPoolIndex(Idx));
6678       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6679                      .addReg(NewVReg1)
6680                      .addReg(VReg1));
6681     }
6682
6683     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6684       .addMBB(TrapBB)
6685       .addImm(ARMCC::HI)
6686       .addReg(ARM::CPSR);
6687
6688     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6689     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6690                    .addReg(ARM::CPSR, RegState::Define)
6691                    .addReg(NewVReg1)
6692                    .addImm(2));
6693
6694     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6695     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6696                    .addJumpTableIndex(MJTI)
6697                    .addImm(UId));
6698
6699     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6700     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6701                    .addReg(ARM::CPSR, RegState::Define)
6702                    .addReg(NewVReg2, RegState::Kill)
6703                    .addReg(NewVReg3));
6704
6705     MachineMemOperand *JTMMOLd =
6706       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6707                                MachineMemOperand::MOLoad, 4, 4);
6708
6709     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6710     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6711                    .addReg(NewVReg4, RegState::Kill)
6712                    .addImm(0)
6713                    .addMemOperand(JTMMOLd));
6714
6715     unsigned NewVReg6 = NewVReg5;
6716     if (RelocM == Reloc::PIC_) {
6717       NewVReg6 = MRI->createVirtualRegister(TRC);
6718       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6719                      .addReg(ARM::CPSR, RegState::Define)
6720                      .addReg(NewVReg5, RegState::Kill)
6721                      .addReg(NewVReg3));
6722     }
6723
6724     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6725       .addReg(NewVReg6, RegState::Kill)
6726       .addJumpTableIndex(MJTI)
6727       .addImm(UId);
6728   } else {
6729     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6730     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6731                    .addFrameIndex(FI)
6732                    .addImm(4)
6733                    .addMemOperand(FIMMOLd));
6734
6735     if (NumLPads < 256) {
6736       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6737                      .addReg(NewVReg1)
6738                      .addImm(NumLPads));
6739     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6740       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6741       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6742                      .addImm(NumLPads & 0xFFFF));
6743
6744       unsigned VReg2 = VReg1;
6745       if ((NumLPads & 0xFFFF0000) != 0) {
6746         VReg2 = MRI->createVirtualRegister(TRC);
6747         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6748                        .addReg(VReg1)
6749                        .addImm(NumLPads >> 16));
6750       }
6751
6752       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6753                      .addReg(NewVReg1)
6754                      .addReg(VReg2));
6755     } else {
6756       MachineConstantPool *ConstantPool = MF->getConstantPool();
6757       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6758       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6759
6760       // MachineConstantPool wants an explicit alignment.
6761       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6762       if (Align == 0)
6763         Align = getDataLayout()->getTypeAllocSize(C->getType());
6764       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6765
6766       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6767       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6768                      .addReg(VReg1, RegState::Define)
6769                      .addConstantPoolIndex(Idx)
6770                      .addImm(0));
6771       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6772                      .addReg(NewVReg1)
6773                      .addReg(VReg1, RegState::Kill));
6774     }
6775
6776     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6777       .addMBB(TrapBB)
6778       .addImm(ARMCC::HI)
6779       .addReg(ARM::CPSR);
6780
6781     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6782     AddDefaultCC(
6783       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6784                      .addReg(NewVReg1)
6785                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6786     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6787     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6788                    .addJumpTableIndex(MJTI)
6789                    .addImm(UId));
6790
6791     MachineMemOperand *JTMMOLd =
6792       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6793                                MachineMemOperand::MOLoad, 4, 4);
6794     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6795     AddDefaultPred(
6796       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6797       .addReg(NewVReg3, RegState::Kill)
6798       .addReg(NewVReg4)
6799       .addImm(0)
6800       .addMemOperand(JTMMOLd));
6801
6802     if (RelocM == Reloc::PIC_) {
6803       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6804         .addReg(NewVReg5, RegState::Kill)
6805         .addReg(NewVReg4)
6806         .addJumpTableIndex(MJTI)
6807         .addImm(UId);
6808     } else {
6809       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6810         .addReg(NewVReg5, RegState::Kill)
6811         .addJumpTableIndex(MJTI)
6812         .addImm(UId);
6813     }
6814   }
6815
6816   // Add the jump table entries as successors to the MBB.
6817   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6818   for (std::vector<MachineBasicBlock*>::iterator
6819          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6820     MachineBasicBlock *CurMBB = *I;
6821     if (SeenMBBs.insert(CurMBB))
6822       DispContBB->addSuccessor(CurMBB);
6823   }
6824
6825   // N.B. the order the invoke BBs are processed in doesn't matter here.
6826   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6827   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6828   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6829          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6830     MachineBasicBlock *BB = *I;
6831
6832     // Remove the landing pad successor from the invoke block and replace it
6833     // with the new dispatch block.
6834     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6835                                                   BB->succ_end());
6836     while (!Successors.empty()) {
6837       MachineBasicBlock *SMBB = Successors.pop_back_val();
6838       if (SMBB->isLandingPad()) {
6839         BB->removeSuccessor(SMBB);
6840         MBBLPads.push_back(SMBB);
6841       }
6842     }
6843
6844     BB->addSuccessor(DispatchBB);
6845
6846     // Find the invoke call and mark all of the callee-saved registers as
6847     // 'implicit defined' so that they're spilled. This prevents code from
6848     // moving instructions to before the EH block, where they will never be
6849     // executed.
6850     for (MachineBasicBlock::reverse_iterator
6851            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6852       if (!II->isCall()) continue;
6853
6854       DenseMap<unsigned, bool> DefRegs;
6855       for (MachineInstr::mop_iterator
6856              OI = II->operands_begin(), OE = II->operands_end();
6857            OI != OE; ++OI) {
6858         if (!OI->isReg()) continue;
6859         DefRegs[OI->getReg()] = true;
6860       }
6861
6862       MachineInstrBuilder MIB(*MF, &*II);
6863
6864       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6865         unsigned Reg = SavedRegs[i];
6866         if (Subtarget->isThumb2() &&
6867             !ARM::tGPRRegClass.contains(Reg) &&
6868             !ARM::hGPRRegClass.contains(Reg))
6869           continue;
6870         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6871           continue;
6872         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6873           continue;
6874         if (!DefRegs[Reg])
6875           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6876       }
6877
6878       break;
6879     }
6880   }
6881
6882   // Mark all former landing pads as non-landing pads. The dispatch is the only
6883   // landing pad now.
6884   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6885          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6886     (*I)->setIsLandingPad(false);
6887
6888   // The instruction is gone now.
6889   MI->eraseFromParent();
6890
6891   return MBB;
6892 }
6893
6894 static
6895 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6896   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6897        E = MBB->succ_end(); I != E; ++I)
6898     if (*I != Succ)
6899       return *I;
6900   llvm_unreachable("Expecting a BB with two successors!");
6901 }
6902
6903 /// Return the load opcode for a given load size. If load size >= 8,
6904 /// neon opcode will be returned.
6905 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6906   if (LdSize >= 8)
6907     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6908                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6909   if (IsThumb1)
6910     return LdSize == 4 ? ARM::tLDRi
6911                        : LdSize == 2 ? ARM::tLDRHi
6912                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6913   if (IsThumb2)
6914     return LdSize == 4 ? ARM::t2LDR_POST
6915                        : LdSize == 2 ? ARM::t2LDRH_POST
6916                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6917   return LdSize == 4 ? ARM::LDR_POST_IMM
6918                      : LdSize == 2 ? ARM::LDRH_POST
6919                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6920 }
6921
6922 /// Return the store opcode for a given store size. If store size >= 8,
6923 /// neon opcode will be returned.
6924 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6925   if (StSize >= 8)
6926     return StSize == 16 ? ARM::VST1q32wb_fixed
6927                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6928   if (IsThumb1)
6929     return StSize == 4 ? ARM::tSTRi
6930                        : StSize == 2 ? ARM::tSTRHi
6931                                      : StSize == 1 ? ARM::tSTRBi : 0;
6932   if (IsThumb2)
6933     return StSize == 4 ? ARM::t2STR_POST
6934                        : StSize == 2 ? ARM::t2STRH_POST
6935                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6936   return StSize == 4 ? ARM::STR_POST_IMM
6937                      : StSize == 2 ? ARM::STRH_POST
6938                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6939 }
6940
6941 /// Emit a post-increment load operation with given size. The instructions
6942 /// will be added to BB at Pos.
6943 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6944                        const TargetInstrInfo *TII, DebugLoc dl,
6945                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6946                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6947   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6948   assert(LdOpc != 0 && "Should have a load opcode");
6949   if (LdSize >= 8) {
6950     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6951                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6952                        .addImm(0));
6953   } else if (IsThumb1) {
6954     // load + update AddrIn
6955     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6956                        .addReg(AddrIn).addImm(0));
6957     MachineInstrBuilder MIB =
6958         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6959     MIB = AddDefaultT1CC(MIB);
6960     MIB.addReg(AddrIn).addImm(LdSize);
6961     AddDefaultPred(MIB);
6962   } else if (IsThumb2) {
6963     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6964                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6965                        .addImm(LdSize));
6966   } else { // arm
6967     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6968                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6969                        .addReg(0).addImm(LdSize));
6970   }
6971 }
6972
6973 /// Emit a post-increment store operation with given size. The instructions
6974 /// will be added to BB at Pos.
6975 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6976                        const TargetInstrInfo *TII, DebugLoc dl,
6977                        unsigned StSize, unsigned Data, unsigned AddrIn,
6978                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6979   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6980   assert(StOpc != 0 && "Should have a store opcode");
6981   if (StSize >= 8) {
6982     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6983                        .addReg(AddrIn).addImm(0).addReg(Data));
6984   } else if (IsThumb1) {
6985     // store + update AddrIn
6986     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6987                        .addReg(AddrIn).addImm(0));
6988     MachineInstrBuilder MIB =
6989         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6990     MIB = AddDefaultT1CC(MIB);
6991     MIB.addReg(AddrIn).addImm(StSize);
6992     AddDefaultPred(MIB);
6993   } else if (IsThumb2) {
6994     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6995                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6996   } else { // arm
6997     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6998                        .addReg(Data).addReg(AddrIn).addReg(0)
6999                        .addImm(StSize));
7000   }
7001 }
7002
7003 MachineBasicBlock *
7004 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7005                                    MachineBasicBlock *BB) const {
7006   // This pseudo instruction has 3 operands: dst, src, size
7007   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7008   // Otherwise, we will generate unrolled scalar copies.
7009   const TargetInstrInfo *TII =
7010       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7011   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7012   MachineFunction::iterator It = BB;
7013   ++It;
7014
7015   unsigned dest = MI->getOperand(0).getReg();
7016   unsigned src = MI->getOperand(1).getReg();
7017   unsigned SizeVal = MI->getOperand(2).getImm();
7018   unsigned Align = MI->getOperand(3).getImm();
7019   DebugLoc dl = MI->getDebugLoc();
7020
7021   MachineFunction *MF = BB->getParent();
7022   MachineRegisterInfo &MRI = MF->getRegInfo();
7023   unsigned UnitSize = 0;
7024   const TargetRegisterClass *TRC = nullptr;
7025   const TargetRegisterClass *VecTRC = nullptr;
7026
7027   bool IsThumb1 = Subtarget->isThumb1Only();
7028   bool IsThumb2 = Subtarget->isThumb2();
7029
7030   if (Align & 1) {
7031     UnitSize = 1;
7032   } else if (Align & 2) {
7033     UnitSize = 2;
7034   } else {
7035     // Check whether we can use NEON instructions.
7036     if (!MF->getFunction()->getAttributes().
7037           hasAttribute(AttributeSet::FunctionIndex,
7038                        Attribute::NoImplicitFloat) &&
7039         Subtarget->hasNEON()) {
7040       if ((Align % 16 == 0) && SizeVal >= 16)
7041         UnitSize = 16;
7042       else if ((Align % 8 == 0) && SizeVal >= 8)
7043         UnitSize = 8;
7044     }
7045     // Can't use NEON instructions.
7046     if (UnitSize == 0)
7047       UnitSize = 4;
7048   }
7049
7050   // Select the correct opcode and register class for unit size load/store
7051   bool IsNeon = UnitSize >= 8;
7052   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7053                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7054   if (IsNeon)
7055     VecTRC = UnitSize == 16
7056                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7057                  : UnitSize == 8
7058                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7059                        : nullptr;
7060
7061   unsigned BytesLeft = SizeVal % UnitSize;
7062   unsigned LoopSize = SizeVal - BytesLeft;
7063
7064   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7065     // Use LDR and STR to copy.
7066     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7067     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7068     unsigned srcIn = src;
7069     unsigned destIn = dest;
7070     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7071       unsigned srcOut = MRI.createVirtualRegister(TRC);
7072       unsigned destOut = MRI.createVirtualRegister(TRC);
7073       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7074       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7075                  IsThumb1, IsThumb2);
7076       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7077                  IsThumb1, IsThumb2);
7078       srcIn = srcOut;
7079       destIn = destOut;
7080     }
7081
7082     // Handle the leftover bytes with LDRB and STRB.
7083     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7084     // [destOut] = STRB_POST(scratch, destIn, 1)
7085     for (unsigned i = 0; i < BytesLeft; i++) {
7086       unsigned srcOut = MRI.createVirtualRegister(TRC);
7087       unsigned destOut = MRI.createVirtualRegister(TRC);
7088       unsigned scratch = MRI.createVirtualRegister(TRC);
7089       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7090                  IsThumb1, IsThumb2);
7091       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7092                  IsThumb1, IsThumb2);
7093       srcIn = srcOut;
7094       destIn = destOut;
7095     }
7096     MI->eraseFromParent();   // The instruction is gone now.
7097     return BB;
7098   }
7099
7100   // Expand the pseudo op to a loop.
7101   // thisMBB:
7102   //   ...
7103   //   movw varEnd, # --> with thumb2
7104   //   movt varEnd, #
7105   //   ldrcp varEnd, idx --> without thumb2
7106   //   fallthrough --> loopMBB
7107   // loopMBB:
7108   //   PHI varPhi, varEnd, varLoop
7109   //   PHI srcPhi, src, srcLoop
7110   //   PHI destPhi, dst, destLoop
7111   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7112   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7113   //   subs varLoop, varPhi, #UnitSize
7114   //   bne loopMBB
7115   //   fallthrough --> exitMBB
7116   // exitMBB:
7117   //   epilogue to handle left-over bytes
7118   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7119   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7120   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7121   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7122   MF->insert(It, loopMBB);
7123   MF->insert(It, exitMBB);
7124
7125   // Transfer the remainder of BB and its successor edges to exitMBB.
7126   exitMBB->splice(exitMBB->begin(), BB,
7127                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7128   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7129
7130   // Load an immediate to varEnd.
7131   unsigned varEnd = MRI.createVirtualRegister(TRC);
7132   if (IsThumb2) {
7133     unsigned Vtmp = varEnd;
7134     if ((LoopSize & 0xFFFF0000) != 0)
7135       Vtmp = MRI.createVirtualRegister(TRC);
7136     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7137                        .addImm(LoopSize & 0xFFFF));
7138
7139     if ((LoopSize & 0xFFFF0000) != 0)
7140       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7141                          .addReg(Vtmp).addImm(LoopSize >> 16));
7142   } else {
7143     MachineConstantPool *ConstantPool = MF->getConstantPool();
7144     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7145     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7146
7147     // MachineConstantPool wants an explicit alignment.
7148     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7149     if (Align == 0)
7150       Align = getDataLayout()->getTypeAllocSize(C->getType());
7151     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7152
7153     if (IsThumb1)
7154       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7155           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7156     else
7157       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7158           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7159   }
7160   BB->addSuccessor(loopMBB);
7161
7162   // Generate the loop body:
7163   //   varPhi = PHI(varLoop, varEnd)
7164   //   srcPhi = PHI(srcLoop, src)
7165   //   destPhi = PHI(destLoop, dst)
7166   MachineBasicBlock *entryBB = BB;
7167   BB = loopMBB;
7168   unsigned varLoop = MRI.createVirtualRegister(TRC);
7169   unsigned varPhi = MRI.createVirtualRegister(TRC);
7170   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7171   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7172   unsigned destLoop = MRI.createVirtualRegister(TRC);
7173   unsigned destPhi = MRI.createVirtualRegister(TRC);
7174
7175   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7176     .addReg(varLoop).addMBB(loopMBB)
7177     .addReg(varEnd).addMBB(entryBB);
7178   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7179     .addReg(srcLoop).addMBB(loopMBB)
7180     .addReg(src).addMBB(entryBB);
7181   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7182     .addReg(destLoop).addMBB(loopMBB)
7183     .addReg(dest).addMBB(entryBB);
7184
7185   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7186   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7187   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7188   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7189              IsThumb1, IsThumb2);
7190   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7191              IsThumb1, IsThumb2);
7192
7193   // Decrement loop variable by UnitSize.
7194   if (IsThumb1) {
7195     MachineInstrBuilder MIB =
7196         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7197     MIB = AddDefaultT1CC(MIB);
7198     MIB.addReg(varPhi).addImm(UnitSize);
7199     AddDefaultPred(MIB);
7200   } else {
7201     MachineInstrBuilder MIB =
7202         BuildMI(*BB, BB->end(), dl,
7203                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7204     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7205     MIB->getOperand(5).setReg(ARM::CPSR);
7206     MIB->getOperand(5).setIsDef(true);
7207   }
7208   BuildMI(*BB, BB->end(), dl,
7209           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7210       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7211
7212   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7213   BB->addSuccessor(loopMBB);
7214   BB->addSuccessor(exitMBB);
7215
7216   // Add epilogue to handle BytesLeft.
7217   BB = exitMBB;
7218   MachineInstr *StartOfExit = exitMBB->begin();
7219
7220   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7221   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7222   unsigned srcIn = srcLoop;
7223   unsigned destIn = destLoop;
7224   for (unsigned i = 0; i < BytesLeft; i++) {
7225     unsigned srcOut = MRI.createVirtualRegister(TRC);
7226     unsigned destOut = MRI.createVirtualRegister(TRC);
7227     unsigned scratch = MRI.createVirtualRegister(TRC);
7228     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7229                IsThumb1, IsThumb2);
7230     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7231                IsThumb1, IsThumb2);
7232     srcIn = srcOut;
7233     destIn = destOut;
7234   }
7235
7236   MI->eraseFromParent();   // The instruction is gone now.
7237   return BB;
7238 }
7239
7240 MachineBasicBlock *
7241 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7242                                        MachineBasicBlock *MBB) const {
7243   const TargetMachine &TM = getTargetMachine();
7244   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7245   DebugLoc DL = MI->getDebugLoc();
7246
7247   assert(Subtarget->isTargetWindows() &&
7248          "__chkstk is only supported on Windows");
7249   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7250
7251   // __chkstk takes the number of words to allocate on the stack in R4, and
7252   // returns the stack adjustment in number of bytes in R4.  This will not
7253   // clober any other registers (other than the obvious lr).
7254   //
7255   // Although, technically, IP should be considered a register which may be
7256   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7257   // thumb-2 environment, so there is no interworking required.  As a result, we
7258   // do not expect a veneer to be emitted by the linker, clobbering IP.
7259   //
7260   // Each module receives its own copy of __chkstk, so no import thunk is
7261   // required, again, ensuring that IP is not clobbered.
7262   //
7263   // Finally, although some linkers may theoretically provide a trampoline for
7264   // out of range calls (which is quite common due to a 32M range limitation of
7265   // branches for Thumb), we can generate the long-call version via
7266   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7267   // IP.
7268
7269   switch (TM.getCodeModel()) {
7270   case CodeModel::Small:
7271   case CodeModel::Medium:
7272   case CodeModel::Default:
7273   case CodeModel::Kernel:
7274     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7275       .addImm((unsigned)ARMCC::AL).addReg(0)
7276       .addExternalSymbol("__chkstk")
7277       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7278       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7279       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7280     break;
7281   case CodeModel::Large:
7282   case CodeModel::JITDefault: {
7283     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7284     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7285
7286     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7287       .addExternalSymbol("__chkstk");
7288     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7289       .addImm((unsigned)ARMCC::AL).addReg(0)
7290       .addReg(Reg, RegState::Kill)
7291       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7292       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7293       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7294     break;
7295   }
7296   }
7297
7298   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7299                                       ARM::SP)
7300                               .addReg(ARM::SP).addReg(ARM::R4)));
7301
7302   MI->eraseFromParent();
7303   return MBB;
7304 }
7305
7306 MachineBasicBlock *
7307 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7308                                                MachineBasicBlock *BB) const {
7309   const TargetInstrInfo *TII =
7310       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7311   DebugLoc dl = MI->getDebugLoc();
7312   bool isThumb2 = Subtarget->isThumb2();
7313   switch (MI->getOpcode()) {
7314   default: {
7315     MI->dump();
7316     llvm_unreachable("Unexpected instr type to insert");
7317   }
7318   // The Thumb2 pre-indexed stores have the same MI operands, they just
7319   // define them differently in the .td files from the isel patterns, so
7320   // they need pseudos.
7321   case ARM::t2STR_preidx:
7322     MI->setDesc(TII->get(ARM::t2STR_PRE));
7323     return BB;
7324   case ARM::t2STRB_preidx:
7325     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7326     return BB;
7327   case ARM::t2STRH_preidx:
7328     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7329     return BB;
7330
7331   case ARM::STRi_preidx:
7332   case ARM::STRBi_preidx: {
7333     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7334       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7335     // Decode the offset.
7336     unsigned Offset = MI->getOperand(4).getImm();
7337     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7338     Offset = ARM_AM::getAM2Offset(Offset);
7339     if (isSub)
7340       Offset = -Offset;
7341
7342     MachineMemOperand *MMO = *MI->memoperands_begin();
7343     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7344       .addOperand(MI->getOperand(0))  // Rn_wb
7345       .addOperand(MI->getOperand(1))  // Rt
7346       .addOperand(MI->getOperand(2))  // Rn
7347       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7348       .addOperand(MI->getOperand(5))  // pred
7349       .addOperand(MI->getOperand(6))
7350       .addMemOperand(MMO);
7351     MI->eraseFromParent();
7352     return BB;
7353   }
7354   case ARM::STRr_preidx:
7355   case ARM::STRBr_preidx:
7356   case ARM::STRH_preidx: {
7357     unsigned NewOpc;
7358     switch (MI->getOpcode()) {
7359     default: llvm_unreachable("unexpected opcode!");
7360     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7361     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7362     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7363     }
7364     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7365     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7366       MIB.addOperand(MI->getOperand(i));
7367     MI->eraseFromParent();
7368     return BB;
7369   }
7370
7371   case ARM::tMOVCCr_pseudo: {
7372     // To "insert" a SELECT_CC instruction, we actually have to insert the
7373     // diamond control-flow pattern.  The incoming instruction knows the
7374     // destination vreg to set, the condition code register to branch on, the
7375     // true/false values to select between, and a branch opcode to use.
7376     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7377     MachineFunction::iterator It = BB;
7378     ++It;
7379
7380     //  thisMBB:
7381     //  ...
7382     //   TrueVal = ...
7383     //   cmpTY ccX, r1, r2
7384     //   bCC copy1MBB
7385     //   fallthrough --> copy0MBB
7386     MachineBasicBlock *thisMBB  = BB;
7387     MachineFunction *F = BB->getParent();
7388     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7389     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7390     F->insert(It, copy0MBB);
7391     F->insert(It, sinkMBB);
7392
7393     // Transfer the remainder of BB and its successor edges to sinkMBB.
7394     sinkMBB->splice(sinkMBB->begin(), BB,
7395                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7396     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7397
7398     BB->addSuccessor(copy0MBB);
7399     BB->addSuccessor(sinkMBB);
7400
7401     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7402       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7403
7404     //  copy0MBB:
7405     //   %FalseValue = ...
7406     //   # fallthrough to sinkMBB
7407     BB = copy0MBB;
7408
7409     // Update machine-CFG edges
7410     BB->addSuccessor(sinkMBB);
7411
7412     //  sinkMBB:
7413     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7414     //  ...
7415     BB = sinkMBB;
7416     BuildMI(*BB, BB->begin(), dl,
7417             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7418       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7419       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7420
7421     MI->eraseFromParent();   // The pseudo instruction is gone now.
7422     return BB;
7423   }
7424
7425   case ARM::BCCi64:
7426   case ARM::BCCZi64: {
7427     // If there is an unconditional branch to the other successor, remove it.
7428     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7429
7430     // Compare both parts that make up the double comparison separately for
7431     // equality.
7432     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7433
7434     unsigned LHS1 = MI->getOperand(1).getReg();
7435     unsigned LHS2 = MI->getOperand(2).getReg();
7436     if (RHSisZero) {
7437       AddDefaultPred(BuildMI(BB, dl,
7438                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7439                      .addReg(LHS1).addImm(0));
7440       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7441         .addReg(LHS2).addImm(0)
7442         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7443     } else {
7444       unsigned RHS1 = MI->getOperand(3).getReg();
7445       unsigned RHS2 = MI->getOperand(4).getReg();
7446       AddDefaultPred(BuildMI(BB, dl,
7447                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7448                      .addReg(LHS1).addReg(RHS1));
7449       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7450         .addReg(LHS2).addReg(RHS2)
7451         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7452     }
7453
7454     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7455     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7456     if (MI->getOperand(0).getImm() == ARMCC::NE)
7457       std::swap(destMBB, exitMBB);
7458
7459     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7460       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7461     if (isThumb2)
7462       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7463     else
7464       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7465
7466     MI->eraseFromParent();   // The pseudo instruction is gone now.
7467     return BB;
7468   }
7469
7470   case ARM::Int_eh_sjlj_setjmp:
7471   case ARM::Int_eh_sjlj_setjmp_nofp:
7472   case ARM::tInt_eh_sjlj_setjmp:
7473   case ARM::t2Int_eh_sjlj_setjmp:
7474   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7475     EmitSjLjDispatchBlock(MI, BB);
7476     return BB;
7477
7478   case ARM::ABS:
7479   case ARM::t2ABS: {
7480     // To insert an ABS instruction, we have to insert the
7481     // diamond control-flow pattern.  The incoming instruction knows the
7482     // source vreg to test against 0, the destination vreg to set,
7483     // the condition code register to branch on, the
7484     // true/false values to select between, and a branch opcode to use.
7485     // It transforms
7486     //     V1 = ABS V0
7487     // into
7488     //     V2 = MOVS V0
7489     //     BCC                      (branch to SinkBB if V0 >= 0)
7490     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7491     //     SinkBB: V1 = PHI(V2, V3)
7492     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7493     MachineFunction::iterator BBI = BB;
7494     ++BBI;
7495     MachineFunction *Fn = BB->getParent();
7496     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7497     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7498     Fn->insert(BBI, RSBBB);
7499     Fn->insert(BBI, SinkBB);
7500
7501     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7502     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7503     bool isThumb2 = Subtarget->isThumb2();
7504     MachineRegisterInfo &MRI = Fn->getRegInfo();
7505     // In Thumb mode S must not be specified if source register is the SP or
7506     // PC and if destination register is the SP, so restrict register class
7507     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7508       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7509       (const TargetRegisterClass*)&ARM::GPRRegClass);
7510
7511     // Transfer the remainder of BB and its successor edges to sinkMBB.
7512     SinkBB->splice(SinkBB->begin(), BB,
7513                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7514     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7515
7516     BB->addSuccessor(RSBBB);
7517     BB->addSuccessor(SinkBB);
7518
7519     // fall through to SinkMBB
7520     RSBBB->addSuccessor(SinkBB);
7521
7522     // insert a cmp at the end of BB
7523     AddDefaultPred(BuildMI(BB, dl,
7524                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7525                    .addReg(ABSSrcReg).addImm(0));
7526
7527     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7528     BuildMI(BB, dl,
7529       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7530       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7531
7532     // insert rsbri in RSBBB
7533     // Note: BCC and rsbri will be converted into predicated rsbmi
7534     // by if-conversion pass
7535     BuildMI(*RSBBB, RSBBB->begin(), dl,
7536       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7537       .addReg(ABSSrcReg, RegState::Kill)
7538       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7539
7540     // insert PHI in SinkBB,
7541     // reuse ABSDstReg to not change uses of ABS instruction
7542     BuildMI(*SinkBB, SinkBB->begin(), dl,
7543       TII->get(ARM::PHI), ABSDstReg)
7544       .addReg(NewRsbDstReg).addMBB(RSBBB)
7545       .addReg(ABSSrcReg).addMBB(BB);
7546
7547     // remove ABS instruction
7548     MI->eraseFromParent();
7549
7550     // return last added BB
7551     return SinkBB;
7552   }
7553   case ARM::COPY_STRUCT_BYVAL_I32:
7554     ++NumLoopByVals;
7555     return EmitStructByval(MI, BB);
7556   case ARM::WIN__CHKSTK:
7557     return EmitLowered__chkstk(MI, BB);
7558   }
7559 }
7560
7561 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7562                                                       SDNode *Node) const {
7563   if (!MI->hasPostISelHook()) {
7564     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7565            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7566     return;
7567   }
7568
7569   const MCInstrDesc *MCID = &MI->getDesc();
7570   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7571   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7572   // operand is still set to noreg. If needed, set the optional operand's
7573   // register to CPSR, and remove the redundant implicit def.
7574   //
7575   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7576
7577   // Rename pseudo opcodes.
7578   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7579   if (NewOpc) {
7580     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7581         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7582     MCID = &TII->get(NewOpc);
7583
7584     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7585            "converted opcode should be the same except for cc_out");
7586
7587     MI->setDesc(*MCID);
7588
7589     // Add the optional cc_out operand
7590     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7591   }
7592   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7593
7594   // Any ARM instruction that sets the 's' bit should specify an optional
7595   // "cc_out" operand in the last operand position.
7596   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7597     assert(!NewOpc && "Optional cc_out operand required");
7598     return;
7599   }
7600   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7601   // since we already have an optional CPSR def.
7602   bool definesCPSR = false;
7603   bool deadCPSR = false;
7604   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7605        i != e; ++i) {
7606     const MachineOperand &MO = MI->getOperand(i);
7607     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7608       definesCPSR = true;
7609       if (MO.isDead())
7610         deadCPSR = true;
7611       MI->RemoveOperand(i);
7612       break;
7613     }
7614   }
7615   if (!definesCPSR) {
7616     assert(!NewOpc && "Optional cc_out operand required");
7617     return;
7618   }
7619   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7620   if (deadCPSR) {
7621     assert(!MI->getOperand(ccOutIdx).getReg() &&
7622            "expect uninitialized optional cc_out operand");
7623     return;
7624   }
7625
7626   // If this instruction was defined with an optional CPSR def and its dag node
7627   // had a live implicit CPSR def, then activate the optional CPSR def.
7628   MachineOperand &MO = MI->getOperand(ccOutIdx);
7629   MO.setReg(ARM::CPSR);
7630   MO.setIsDef(true);
7631 }
7632
7633 //===----------------------------------------------------------------------===//
7634 //                           ARM Optimization Hooks
7635 //===----------------------------------------------------------------------===//
7636
7637 // Helper function that checks if N is a null or all ones constant.
7638 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7639   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7640   if (!C)
7641     return false;
7642   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7643 }
7644
7645 // Return true if N is conditionally 0 or all ones.
7646 // Detects these expressions where cc is an i1 value:
7647 //
7648 //   (select cc 0, y)   [AllOnes=0]
7649 //   (select cc y, 0)   [AllOnes=0]
7650 //   (zext cc)          [AllOnes=0]
7651 //   (sext cc)          [AllOnes=0/1]
7652 //   (select cc -1, y)  [AllOnes=1]
7653 //   (select cc y, -1)  [AllOnes=1]
7654 //
7655 // Invert is set when N is the null/all ones constant when CC is false.
7656 // OtherOp is set to the alternative value of N.
7657 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7658                                        SDValue &CC, bool &Invert,
7659                                        SDValue &OtherOp,
7660                                        SelectionDAG &DAG) {
7661   switch (N->getOpcode()) {
7662   default: return false;
7663   case ISD::SELECT: {
7664     CC = N->getOperand(0);
7665     SDValue N1 = N->getOperand(1);
7666     SDValue N2 = N->getOperand(2);
7667     if (isZeroOrAllOnes(N1, AllOnes)) {
7668       Invert = false;
7669       OtherOp = N2;
7670       return true;
7671     }
7672     if (isZeroOrAllOnes(N2, AllOnes)) {
7673       Invert = true;
7674       OtherOp = N1;
7675       return true;
7676     }
7677     return false;
7678   }
7679   case ISD::ZERO_EXTEND:
7680     // (zext cc) can never be the all ones value.
7681     if (AllOnes)
7682       return false;
7683     // Fall through.
7684   case ISD::SIGN_EXTEND: {
7685     EVT VT = N->getValueType(0);
7686     CC = N->getOperand(0);
7687     if (CC.getValueType() != MVT::i1)
7688       return false;
7689     Invert = !AllOnes;
7690     if (AllOnes)
7691       // When looking for an AllOnes constant, N is an sext, and the 'other'
7692       // value is 0.
7693       OtherOp = DAG.getConstant(0, VT);
7694     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7695       // When looking for a 0 constant, N can be zext or sext.
7696       OtherOp = DAG.getConstant(1, VT);
7697     else
7698       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7699     return true;
7700   }
7701   }
7702 }
7703
7704 // Combine a constant select operand into its use:
7705 //
7706 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7707 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7708 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7709 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7710 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7711 //
7712 // The transform is rejected if the select doesn't have a constant operand that
7713 // is null, or all ones when AllOnes is set.
7714 //
7715 // Also recognize sext/zext from i1:
7716 //
7717 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7718 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7719 //
7720 // These transformations eventually create predicated instructions.
7721 //
7722 // @param N       The node to transform.
7723 // @param Slct    The N operand that is a select.
7724 // @param OtherOp The other N operand (x above).
7725 // @param DCI     Context.
7726 // @param AllOnes Require the select constant to be all ones instead of null.
7727 // @returns The new node, or SDValue() on failure.
7728 static
7729 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7730                             TargetLowering::DAGCombinerInfo &DCI,
7731                             bool AllOnes = false) {
7732   SelectionDAG &DAG = DCI.DAG;
7733   EVT VT = N->getValueType(0);
7734   SDValue NonConstantVal;
7735   SDValue CCOp;
7736   bool SwapSelectOps;
7737   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7738                                   NonConstantVal, DAG))
7739     return SDValue();
7740
7741   // Slct is now know to be the desired identity constant when CC is true.
7742   SDValue TrueVal = OtherOp;
7743   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7744                                  OtherOp, NonConstantVal);
7745   // Unless SwapSelectOps says CC should be false.
7746   if (SwapSelectOps)
7747     std::swap(TrueVal, FalseVal);
7748
7749   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7750                      CCOp, TrueVal, FalseVal);
7751 }
7752
7753 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7754 static
7755 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7756                                        TargetLowering::DAGCombinerInfo &DCI) {
7757   SDValue N0 = N->getOperand(0);
7758   SDValue N1 = N->getOperand(1);
7759   if (N0.getNode()->hasOneUse()) {
7760     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7761     if (Result.getNode())
7762       return Result;
7763   }
7764   if (N1.getNode()->hasOneUse()) {
7765     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7766     if (Result.getNode())
7767       return Result;
7768   }
7769   return SDValue();
7770 }
7771
7772 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7773 // (only after legalization).
7774 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7775                                  TargetLowering::DAGCombinerInfo &DCI,
7776                                  const ARMSubtarget *Subtarget) {
7777
7778   // Only perform optimization if after legalize, and if NEON is available. We
7779   // also expected both operands to be BUILD_VECTORs.
7780   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7781       || N0.getOpcode() != ISD::BUILD_VECTOR
7782       || N1.getOpcode() != ISD::BUILD_VECTOR)
7783     return SDValue();
7784
7785   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7786   EVT VT = N->getValueType(0);
7787   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7788     return SDValue();
7789
7790   // Check that the vector operands are of the right form.
7791   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7792   // operands, where N is the size of the formed vector.
7793   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7794   // index such that we have a pair wise add pattern.
7795
7796   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7797   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7798     return SDValue();
7799   SDValue Vec = N0->getOperand(0)->getOperand(0);
7800   SDNode *V = Vec.getNode();
7801   unsigned nextIndex = 0;
7802
7803   // For each operands to the ADD which are BUILD_VECTORs,
7804   // check to see if each of their operands are an EXTRACT_VECTOR with
7805   // the same vector and appropriate index.
7806   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7807     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7808         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7809
7810       SDValue ExtVec0 = N0->getOperand(i);
7811       SDValue ExtVec1 = N1->getOperand(i);
7812
7813       // First operand is the vector, verify its the same.
7814       if (V != ExtVec0->getOperand(0).getNode() ||
7815           V != ExtVec1->getOperand(0).getNode())
7816         return SDValue();
7817
7818       // Second is the constant, verify its correct.
7819       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7820       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7821
7822       // For the constant, we want to see all the even or all the odd.
7823       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7824           || C1->getZExtValue() != nextIndex+1)
7825         return SDValue();
7826
7827       // Increment index.
7828       nextIndex+=2;
7829     } else
7830       return SDValue();
7831   }
7832
7833   // Create VPADDL node.
7834   SelectionDAG &DAG = DCI.DAG;
7835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7836
7837   // Build operand list.
7838   SmallVector<SDValue, 8> Ops;
7839   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7840                                 TLI.getPointerTy()));
7841
7842   // Input is the vector.
7843   Ops.push_back(Vec);
7844
7845   // Get widened type and narrowed type.
7846   MVT widenType;
7847   unsigned numElem = VT.getVectorNumElements();
7848   
7849   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7850   switch (inputLaneType.getSimpleVT().SimpleTy) {
7851     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7852     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7853     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7854     default:
7855       llvm_unreachable("Invalid vector element type for padd optimization.");
7856   }
7857
7858   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7859   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7860   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7861 }
7862
7863 static SDValue findMUL_LOHI(SDValue V) {
7864   if (V->getOpcode() == ISD::UMUL_LOHI ||
7865       V->getOpcode() == ISD::SMUL_LOHI)
7866     return V;
7867   return SDValue();
7868 }
7869
7870 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7871                                      TargetLowering::DAGCombinerInfo &DCI,
7872                                      const ARMSubtarget *Subtarget) {
7873
7874   if (Subtarget->isThumb1Only()) return SDValue();
7875
7876   // Only perform the checks after legalize when the pattern is available.
7877   if (DCI.isBeforeLegalize()) return SDValue();
7878
7879   // Look for multiply add opportunities.
7880   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7881   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7882   // a glue link from the first add to the second add.
7883   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7884   // a S/UMLAL instruction.
7885   //          loAdd   UMUL_LOHI
7886   //            \    / :lo    \ :hi
7887   //             \  /          \          [no multiline comment]
7888   //              ADDC         |  hiAdd
7889   //                 \ :glue  /  /
7890   //                  \      /  /
7891   //                    ADDE
7892   //
7893   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7894   SDValue AddcOp0 = AddcNode->getOperand(0);
7895   SDValue AddcOp1 = AddcNode->getOperand(1);
7896
7897   // Check if the two operands are from the same mul_lohi node.
7898   if (AddcOp0.getNode() == AddcOp1.getNode())
7899     return SDValue();
7900
7901   assert(AddcNode->getNumValues() == 2 &&
7902          AddcNode->getValueType(0) == MVT::i32 &&
7903          "Expect ADDC with two result values. First: i32");
7904
7905   // Check that we have a glued ADDC node.
7906   if (AddcNode->getValueType(1) != MVT::Glue)
7907     return SDValue();
7908
7909   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7910   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7911       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7912       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7913       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7914     return SDValue();
7915
7916   // Look for the glued ADDE.
7917   SDNode* AddeNode = AddcNode->getGluedUser();
7918   if (!AddeNode)
7919     return SDValue();
7920
7921   // Make sure it is really an ADDE.
7922   if (AddeNode->getOpcode() != ISD::ADDE)
7923     return SDValue();
7924
7925   assert(AddeNode->getNumOperands() == 3 &&
7926          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7927          "ADDE node has the wrong inputs");
7928
7929   // Check for the triangle shape.
7930   SDValue AddeOp0 = AddeNode->getOperand(0);
7931   SDValue AddeOp1 = AddeNode->getOperand(1);
7932
7933   // Make sure that the ADDE operands are not coming from the same node.
7934   if (AddeOp0.getNode() == AddeOp1.getNode())
7935     return SDValue();
7936
7937   // Find the MUL_LOHI node walking up ADDE's operands.
7938   bool IsLeftOperandMUL = false;
7939   SDValue MULOp = findMUL_LOHI(AddeOp0);
7940   if (MULOp == SDValue())
7941    MULOp = findMUL_LOHI(AddeOp1);
7942   else
7943     IsLeftOperandMUL = true;
7944   if (MULOp == SDValue())
7945      return SDValue();
7946
7947   // Figure out the right opcode.
7948   unsigned Opc = MULOp->getOpcode();
7949   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7950
7951   // Figure out the high and low input values to the MLAL node.
7952   SDValue* HiMul = &MULOp;
7953   SDValue* HiAdd = nullptr;
7954   SDValue* LoMul = nullptr;
7955   SDValue* LowAdd = nullptr;
7956
7957   if (IsLeftOperandMUL)
7958     HiAdd = &AddeOp1;
7959   else
7960     HiAdd = &AddeOp0;
7961
7962
7963   if (AddcOp0->getOpcode() == Opc) {
7964     LoMul = &AddcOp0;
7965     LowAdd = &AddcOp1;
7966   }
7967   if (AddcOp1->getOpcode() == Opc) {
7968     LoMul = &AddcOp1;
7969     LowAdd = &AddcOp0;
7970   }
7971
7972   if (!LoMul)
7973     return SDValue();
7974
7975   if (LoMul->getNode() != HiMul->getNode())
7976     return SDValue();
7977
7978   // Create the merged node.
7979   SelectionDAG &DAG = DCI.DAG;
7980
7981   // Build operand list.
7982   SmallVector<SDValue, 8> Ops;
7983   Ops.push_back(LoMul->getOperand(0));
7984   Ops.push_back(LoMul->getOperand(1));
7985   Ops.push_back(*LowAdd);
7986   Ops.push_back(*HiAdd);
7987
7988   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7989                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7990
7991   // Replace the ADDs' nodes uses by the MLA node's values.
7992   SDValue HiMLALResult(MLALNode.getNode(), 1);
7993   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7994
7995   SDValue LoMLALResult(MLALNode.getNode(), 0);
7996   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7997
7998   // Return original node to notify the driver to stop replacing.
7999   SDValue resNode(AddcNode, 0);
8000   return resNode;
8001 }
8002
8003 /// PerformADDCCombine - Target-specific dag combine transform from
8004 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8005 static SDValue PerformADDCCombine(SDNode *N,
8006                                  TargetLowering::DAGCombinerInfo &DCI,
8007                                  const ARMSubtarget *Subtarget) {
8008
8009   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8010
8011 }
8012
8013 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8014 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8015 /// called with the default operands, and if that fails, with commuted
8016 /// operands.
8017 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8018                                           TargetLowering::DAGCombinerInfo &DCI,
8019                                           const ARMSubtarget *Subtarget){
8020
8021   // Attempt to create vpaddl for this add.
8022   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8023   if (Result.getNode())
8024     return Result;
8025
8026   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8027   if (N0.getNode()->hasOneUse()) {
8028     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8029     if (Result.getNode()) return Result;
8030   }
8031   return SDValue();
8032 }
8033
8034 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8035 ///
8036 static SDValue PerformADDCombine(SDNode *N,
8037                                  TargetLowering::DAGCombinerInfo &DCI,
8038                                  const ARMSubtarget *Subtarget) {
8039   SDValue N0 = N->getOperand(0);
8040   SDValue N1 = N->getOperand(1);
8041
8042   // First try with the default operand order.
8043   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8044   if (Result.getNode())
8045     return Result;
8046
8047   // If that didn't work, try again with the operands commuted.
8048   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8049 }
8050
8051 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8052 ///
8053 static SDValue PerformSUBCombine(SDNode *N,
8054                                  TargetLowering::DAGCombinerInfo &DCI) {
8055   SDValue N0 = N->getOperand(0);
8056   SDValue N1 = N->getOperand(1);
8057
8058   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8059   if (N1.getNode()->hasOneUse()) {
8060     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8061     if (Result.getNode()) return Result;
8062   }
8063
8064   return SDValue();
8065 }
8066
8067 /// PerformVMULCombine
8068 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8069 /// special multiplier accumulator forwarding.
8070 ///   vmul d3, d0, d2
8071 ///   vmla d3, d1, d2
8072 /// is faster than
8073 ///   vadd d3, d0, d1
8074 ///   vmul d3, d3, d2
8075 //  However, for (A + B) * (A + B),
8076 //    vadd d2, d0, d1
8077 //    vmul d3, d0, d2
8078 //    vmla d3, d1, d2
8079 //  is slower than
8080 //    vadd d2, d0, d1
8081 //    vmul d3, d2, d2
8082 static SDValue PerformVMULCombine(SDNode *N,
8083                                   TargetLowering::DAGCombinerInfo &DCI,
8084                                   const ARMSubtarget *Subtarget) {
8085   if (!Subtarget->hasVMLxForwarding())
8086     return SDValue();
8087
8088   SelectionDAG &DAG = DCI.DAG;
8089   SDValue N0 = N->getOperand(0);
8090   SDValue N1 = N->getOperand(1);
8091   unsigned Opcode = N0.getOpcode();
8092   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8093       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8094     Opcode = N1.getOpcode();
8095     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8096         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8097       return SDValue();
8098     std::swap(N0, N1);
8099   }
8100
8101   if (N0 == N1)
8102     return SDValue();
8103
8104   EVT VT = N->getValueType(0);
8105   SDLoc DL(N);
8106   SDValue N00 = N0->getOperand(0);
8107   SDValue N01 = N0->getOperand(1);
8108   return DAG.getNode(Opcode, DL, VT,
8109                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8110                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8111 }
8112
8113 static SDValue PerformMULCombine(SDNode *N,
8114                                  TargetLowering::DAGCombinerInfo &DCI,
8115                                  const ARMSubtarget *Subtarget) {
8116   SelectionDAG &DAG = DCI.DAG;
8117
8118   if (Subtarget->isThumb1Only())
8119     return SDValue();
8120
8121   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8122     return SDValue();
8123
8124   EVT VT = N->getValueType(0);
8125   if (VT.is64BitVector() || VT.is128BitVector())
8126     return PerformVMULCombine(N, DCI, Subtarget);
8127   if (VT != MVT::i32)
8128     return SDValue();
8129
8130   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8131   if (!C)
8132     return SDValue();
8133
8134   int64_t MulAmt = C->getSExtValue();
8135   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8136
8137   ShiftAmt = ShiftAmt & (32 - 1);
8138   SDValue V = N->getOperand(0);
8139   SDLoc DL(N);
8140
8141   SDValue Res;
8142   MulAmt >>= ShiftAmt;
8143
8144   if (MulAmt >= 0) {
8145     if (isPowerOf2_32(MulAmt - 1)) {
8146       // (mul x, 2^N + 1) => (add (shl x, N), x)
8147       Res = DAG.getNode(ISD::ADD, DL, VT,
8148                         V,
8149                         DAG.getNode(ISD::SHL, DL, VT,
8150                                     V,
8151                                     DAG.getConstant(Log2_32(MulAmt - 1),
8152                                                     MVT::i32)));
8153     } else if (isPowerOf2_32(MulAmt + 1)) {
8154       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8155       Res = DAG.getNode(ISD::SUB, DL, VT,
8156                         DAG.getNode(ISD::SHL, DL, VT,
8157                                     V,
8158                                     DAG.getConstant(Log2_32(MulAmt + 1),
8159                                                     MVT::i32)),
8160                         V);
8161     } else
8162       return SDValue();
8163   } else {
8164     uint64_t MulAmtAbs = -MulAmt;
8165     if (isPowerOf2_32(MulAmtAbs + 1)) {
8166       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8167       Res = DAG.getNode(ISD::SUB, DL, VT,
8168                         V,
8169                         DAG.getNode(ISD::SHL, DL, VT,
8170                                     V,
8171                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8172                                                     MVT::i32)));
8173     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8174       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8175       Res = DAG.getNode(ISD::ADD, DL, VT,
8176                         V,
8177                         DAG.getNode(ISD::SHL, DL, VT,
8178                                     V,
8179                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8180                                                     MVT::i32)));
8181       Res = DAG.getNode(ISD::SUB, DL, VT,
8182                         DAG.getConstant(0, MVT::i32),Res);
8183
8184     } else
8185       return SDValue();
8186   }
8187
8188   if (ShiftAmt != 0)
8189     Res = DAG.getNode(ISD::SHL, DL, VT,
8190                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8191
8192   // Do not add new nodes to DAG combiner worklist.
8193   DCI.CombineTo(N, Res, false);
8194   return SDValue();
8195 }
8196
8197 static SDValue PerformANDCombine(SDNode *N,
8198                                  TargetLowering::DAGCombinerInfo &DCI,
8199                                  const ARMSubtarget *Subtarget) {
8200
8201   // Attempt to use immediate-form VBIC
8202   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8203   SDLoc dl(N);
8204   EVT VT = N->getValueType(0);
8205   SelectionDAG &DAG = DCI.DAG;
8206
8207   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8208     return SDValue();
8209
8210   APInt SplatBits, SplatUndef;
8211   unsigned SplatBitSize;
8212   bool HasAnyUndefs;
8213   if (BVN &&
8214       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8215     if (SplatBitSize <= 64) {
8216       EVT VbicVT;
8217       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8218                                       SplatUndef.getZExtValue(), SplatBitSize,
8219                                       DAG, VbicVT, VT.is128BitVector(),
8220                                       OtherModImm);
8221       if (Val.getNode()) {
8222         SDValue Input =
8223           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8224         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8225         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8226       }
8227     }
8228   }
8229
8230   if (!Subtarget->isThumb1Only()) {
8231     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8232     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8233     if (Result.getNode())
8234       return Result;
8235   }
8236
8237   return SDValue();
8238 }
8239
8240 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8241 static SDValue PerformORCombine(SDNode *N,
8242                                 TargetLowering::DAGCombinerInfo &DCI,
8243                                 const ARMSubtarget *Subtarget) {
8244   // Attempt to use immediate-form VORR
8245   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8246   SDLoc dl(N);
8247   EVT VT = N->getValueType(0);
8248   SelectionDAG &DAG = DCI.DAG;
8249
8250   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8251     return SDValue();
8252
8253   APInt SplatBits, SplatUndef;
8254   unsigned SplatBitSize;
8255   bool HasAnyUndefs;
8256   if (BVN && Subtarget->hasNEON() &&
8257       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8258     if (SplatBitSize <= 64) {
8259       EVT VorrVT;
8260       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8261                                       SplatUndef.getZExtValue(), SplatBitSize,
8262                                       DAG, VorrVT, VT.is128BitVector(),
8263                                       OtherModImm);
8264       if (Val.getNode()) {
8265         SDValue Input =
8266           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8267         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8268         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8269       }
8270     }
8271   }
8272
8273   if (!Subtarget->isThumb1Only()) {
8274     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8275     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8276     if (Result.getNode())
8277       return Result;
8278   }
8279
8280   // The code below optimizes (or (and X, Y), Z).
8281   // The AND operand needs to have a single user to make these optimizations
8282   // profitable.
8283   SDValue N0 = N->getOperand(0);
8284   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8285     return SDValue();
8286   SDValue N1 = N->getOperand(1);
8287
8288   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8289   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8290       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8291     APInt SplatUndef;
8292     unsigned SplatBitSize;
8293     bool HasAnyUndefs;
8294
8295     APInt SplatBits0, SplatBits1;
8296     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8297     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8298     // Ensure that the second operand of both ands are constants
8299     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8300                                       HasAnyUndefs) && !HasAnyUndefs) {
8301         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8302                                           HasAnyUndefs) && !HasAnyUndefs) {
8303             // Ensure that the bit width of the constants are the same and that
8304             // the splat arguments are logical inverses as per the pattern we
8305             // are trying to simplify.
8306             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8307                 SplatBits0 == ~SplatBits1) {
8308                 // Canonicalize the vector type to make instruction selection
8309                 // simpler.
8310                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8311                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8312                                              N0->getOperand(1),
8313                                              N0->getOperand(0),
8314                                              N1->getOperand(0));
8315                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8316             }
8317         }
8318     }
8319   }
8320
8321   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8322   // reasonable.
8323
8324   // BFI is only available on V6T2+
8325   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8326     return SDValue();
8327
8328   SDLoc DL(N);
8329   // 1) or (and A, mask), val => ARMbfi A, val, mask
8330   //      iff (val & mask) == val
8331   //
8332   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8333   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8334   //          && mask == ~mask2
8335   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8336   //          && ~mask == mask2
8337   //  (i.e., copy a bitfield value into another bitfield of the same width)
8338
8339   if (VT != MVT::i32)
8340     return SDValue();
8341
8342   SDValue N00 = N0.getOperand(0);
8343
8344   // The value and the mask need to be constants so we can verify this is
8345   // actually a bitfield set. If the mask is 0xffff, we can do better
8346   // via a movt instruction, so don't use BFI in that case.
8347   SDValue MaskOp = N0.getOperand(1);
8348   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8349   if (!MaskC)
8350     return SDValue();
8351   unsigned Mask = MaskC->getZExtValue();
8352   if (Mask == 0xffff)
8353     return SDValue();
8354   SDValue Res;
8355   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8356   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8357   if (N1C) {
8358     unsigned Val = N1C->getZExtValue();
8359     if ((Val & ~Mask) != Val)
8360       return SDValue();
8361
8362     if (ARM::isBitFieldInvertedMask(Mask)) {
8363       Val >>= countTrailingZeros(~Mask);
8364
8365       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8366                         DAG.getConstant(Val, MVT::i32),
8367                         DAG.getConstant(Mask, MVT::i32));
8368
8369       // Do not add new nodes to DAG combiner worklist.
8370       DCI.CombineTo(N, Res, false);
8371       return SDValue();
8372     }
8373   } else if (N1.getOpcode() == ISD::AND) {
8374     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8375     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8376     if (!N11C)
8377       return SDValue();
8378     unsigned Mask2 = N11C->getZExtValue();
8379
8380     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8381     // as is to match.
8382     if (ARM::isBitFieldInvertedMask(Mask) &&
8383         (Mask == ~Mask2)) {
8384       // The pack halfword instruction works better for masks that fit it,
8385       // so use that when it's available.
8386       if (Subtarget->hasT2ExtractPack() &&
8387           (Mask == 0xffff || Mask == 0xffff0000))
8388         return SDValue();
8389       // 2a
8390       unsigned amt = countTrailingZeros(Mask2);
8391       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8392                         DAG.getConstant(amt, MVT::i32));
8393       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8394                         DAG.getConstant(Mask, MVT::i32));
8395       // Do not add new nodes to DAG combiner worklist.
8396       DCI.CombineTo(N, Res, false);
8397       return SDValue();
8398     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8399                (~Mask == Mask2)) {
8400       // The pack halfword instruction works better for masks that fit it,
8401       // so use that when it's available.
8402       if (Subtarget->hasT2ExtractPack() &&
8403           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8404         return SDValue();
8405       // 2b
8406       unsigned lsb = countTrailingZeros(Mask);
8407       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8408                         DAG.getConstant(lsb, MVT::i32));
8409       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8410                         DAG.getConstant(Mask2, MVT::i32));
8411       // Do not add new nodes to DAG combiner worklist.
8412       DCI.CombineTo(N, Res, false);
8413       return SDValue();
8414     }
8415   }
8416
8417   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8418       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8419       ARM::isBitFieldInvertedMask(~Mask)) {
8420     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8421     // where lsb(mask) == #shamt and masked bits of B are known zero.
8422     SDValue ShAmt = N00.getOperand(1);
8423     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8424     unsigned LSB = countTrailingZeros(Mask);
8425     if (ShAmtC != LSB)
8426       return SDValue();
8427
8428     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8429                       DAG.getConstant(~Mask, MVT::i32));
8430
8431     // Do not add new nodes to DAG combiner worklist.
8432     DCI.CombineTo(N, Res, false);
8433   }
8434
8435   return SDValue();
8436 }
8437
8438 static SDValue PerformXORCombine(SDNode *N,
8439                                  TargetLowering::DAGCombinerInfo &DCI,
8440                                  const ARMSubtarget *Subtarget) {
8441   EVT VT = N->getValueType(0);
8442   SelectionDAG &DAG = DCI.DAG;
8443
8444   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8445     return SDValue();
8446
8447   if (!Subtarget->isThumb1Only()) {
8448     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8449     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8450     if (Result.getNode())
8451       return Result;
8452   }
8453
8454   return SDValue();
8455 }
8456
8457 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8458 /// the bits being cleared by the AND are not demanded by the BFI.
8459 static SDValue PerformBFICombine(SDNode *N,
8460                                  TargetLowering::DAGCombinerInfo &DCI) {
8461   SDValue N1 = N->getOperand(1);
8462   if (N1.getOpcode() == ISD::AND) {
8463     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8464     if (!N11C)
8465       return SDValue();
8466     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8467     unsigned LSB = countTrailingZeros(~InvMask);
8468     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8469     unsigned Mask = (1 << Width)-1;
8470     unsigned Mask2 = N11C->getZExtValue();
8471     if ((Mask & (~Mask2)) == 0)
8472       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8473                              N->getOperand(0), N1.getOperand(0),
8474                              N->getOperand(2));
8475   }
8476   return SDValue();
8477 }
8478
8479 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8480 /// ARMISD::VMOVRRD.
8481 static SDValue PerformVMOVRRDCombine(SDNode *N,
8482                                      TargetLowering::DAGCombinerInfo &DCI) {
8483   // vmovrrd(vmovdrr x, y) -> x,y
8484   SDValue InDouble = N->getOperand(0);
8485   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8486     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8487
8488   // vmovrrd(load f64) -> (load i32), (load i32)
8489   SDNode *InNode = InDouble.getNode();
8490   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8491       InNode->getValueType(0) == MVT::f64 &&
8492       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8493       !cast<LoadSDNode>(InNode)->isVolatile()) {
8494     // TODO: Should this be done for non-FrameIndex operands?
8495     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8496
8497     SelectionDAG &DAG = DCI.DAG;
8498     SDLoc DL(LD);
8499     SDValue BasePtr = LD->getBasePtr();
8500     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8501                                  LD->getPointerInfo(), LD->isVolatile(),
8502                                  LD->isNonTemporal(), LD->isInvariant(),
8503                                  LD->getAlignment());
8504
8505     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8506                                     DAG.getConstant(4, MVT::i32));
8507     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8508                                  LD->getPointerInfo(), LD->isVolatile(),
8509                                  LD->isNonTemporal(), LD->isInvariant(),
8510                                  std::min(4U, LD->getAlignment() / 2));
8511
8512     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8513     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8514       std::swap (NewLD1, NewLD2);
8515     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8516     return Result;
8517   }
8518
8519   return SDValue();
8520 }
8521
8522 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8523 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8524 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8525   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8526   SDValue Op0 = N->getOperand(0);
8527   SDValue Op1 = N->getOperand(1);
8528   if (Op0.getOpcode() == ISD::BITCAST)
8529     Op0 = Op0.getOperand(0);
8530   if (Op1.getOpcode() == ISD::BITCAST)
8531     Op1 = Op1.getOperand(0);
8532   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8533       Op0.getNode() == Op1.getNode() &&
8534       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8535     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8536                        N->getValueType(0), Op0.getOperand(0));
8537   return SDValue();
8538 }
8539
8540 /// PerformSTORECombine - Target-specific dag combine xforms for
8541 /// ISD::STORE.
8542 static SDValue PerformSTORECombine(SDNode *N,
8543                                    TargetLowering::DAGCombinerInfo &DCI) {
8544   StoreSDNode *St = cast<StoreSDNode>(N);
8545   if (St->isVolatile())
8546     return SDValue();
8547
8548   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8549   // pack all of the elements in one place.  Next, store to memory in fewer
8550   // chunks.
8551   SDValue StVal = St->getValue();
8552   EVT VT = StVal.getValueType();
8553   if (St->isTruncatingStore() && VT.isVector()) {
8554     SelectionDAG &DAG = DCI.DAG;
8555     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8556     EVT StVT = St->getMemoryVT();
8557     unsigned NumElems = VT.getVectorNumElements();
8558     assert(StVT != VT && "Cannot truncate to the same type");
8559     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8560     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8561
8562     // From, To sizes and ElemCount must be pow of two
8563     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8564
8565     // We are going to use the original vector elt for storing.
8566     // Accumulated smaller vector elements must be a multiple of the store size.
8567     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8568
8569     unsigned SizeRatio  = FromEltSz / ToEltSz;
8570     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8571
8572     // Create a type on which we perform the shuffle.
8573     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8574                                      NumElems*SizeRatio);
8575     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8576
8577     SDLoc DL(St);
8578     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8579     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8580     for (unsigned i = 0; i < NumElems; ++i)
8581       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8582
8583     // Can't shuffle using an illegal type.
8584     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8585
8586     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8587                                 DAG.getUNDEF(WideVec.getValueType()),
8588                                 ShuffleVec.data());
8589     // At this point all of the data is stored at the bottom of the
8590     // register. We now need to save it to mem.
8591
8592     // Find the largest store unit
8593     MVT StoreType = MVT::i8;
8594     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8595          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8596       MVT Tp = (MVT::SimpleValueType)tp;
8597       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8598         StoreType = Tp;
8599     }
8600     // Didn't find a legal store type.
8601     if (!TLI.isTypeLegal(StoreType))
8602       return SDValue();
8603
8604     // Bitcast the original vector into a vector of store-size units
8605     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8606             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8607     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8608     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8609     SmallVector<SDValue, 8> Chains;
8610     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8611                                         TLI.getPointerTy());
8612     SDValue BasePtr = St->getBasePtr();
8613
8614     // Perform one or more big stores into memory.
8615     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8616     for (unsigned I = 0; I < E; I++) {
8617       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8618                                    StoreType, ShuffWide,
8619                                    DAG.getIntPtrConstant(I));
8620       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8621                                 St->getPointerInfo(), St->isVolatile(),
8622                                 St->isNonTemporal(), St->getAlignment());
8623       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8624                             Increment);
8625       Chains.push_back(Ch);
8626     }
8627     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8628   }
8629
8630   if (!ISD::isNormalStore(St))
8631     return SDValue();
8632
8633   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8634   // ARM stores of arguments in the same cache line.
8635   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8636       StVal.getNode()->hasOneUse()) {
8637     SelectionDAG  &DAG = DCI.DAG;
8638     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8639     SDLoc DL(St);
8640     SDValue BasePtr = St->getBasePtr();
8641     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8642                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8643                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8644                                   St->isNonTemporal(), St->getAlignment());
8645
8646     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8647                                     DAG.getConstant(4, MVT::i32));
8648     return DAG.getStore(NewST1.getValue(0), DL,
8649                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8650                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8651                         St->isNonTemporal(),
8652                         std::min(4U, St->getAlignment() / 2));
8653   }
8654
8655   if (StVal.getValueType() != MVT::i64 ||
8656       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8657     return SDValue();
8658
8659   // Bitcast an i64 store extracted from a vector to f64.
8660   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8661   SelectionDAG &DAG = DCI.DAG;
8662   SDLoc dl(StVal);
8663   SDValue IntVec = StVal.getOperand(0);
8664   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8665                                  IntVec.getValueType().getVectorNumElements());
8666   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8667   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8668                                Vec, StVal.getOperand(1));
8669   dl = SDLoc(N);
8670   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8671   // Make the DAGCombiner fold the bitcasts.
8672   DCI.AddToWorklist(Vec.getNode());
8673   DCI.AddToWorklist(ExtElt.getNode());
8674   DCI.AddToWorklist(V.getNode());
8675   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8676                       St->getPointerInfo(), St->isVolatile(),
8677                       St->isNonTemporal(), St->getAlignment(),
8678                       St->getAAInfo());
8679 }
8680
8681 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8682 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8683 /// i64 vector to have f64 elements, since the value can then be loaded
8684 /// directly into a VFP register.
8685 static bool hasNormalLoadOperand(SDNode *N) {
8686   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8687   for (unsigned i = 0; i < NumElts; ++i) {
8688     SDNode *Elt = N->getOperand(i).getNode();
8689     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8690       return true;
8691   }
8692   return false;
8693 }
8694
8695 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8696 /// ISD::BUILD_VECTOR.
8697 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8698                                           TargetLowering::DAGCombinerInfo &DCI){
8699   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8700   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8701   // into a pair of GPRs, which is fine when the value is used as a scalar,
8702   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8703   SelectionDAG &DAG = DCI.DAG;
8704   if (N->getNumOperands() == 2) {
8705     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8706     if (RV.getNode())
8707       return RV;
8708   }
8709
8710   // Load i64 elements as f64 values so that type legalization does not split
8711   // them up into i32 values.
8712   EVT VT = N->getValueType(0);
8713   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8714     return SDValue();
8715   SDLoc dl(N);
8716   SmallVector<SDValue, 8> Ops;
8717   unsigned NumElts = VT.getVectorNumElements();
8718   for (unsigned i = 0; i < NumElts; ++i) {
8719     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8720     Ops.push_back(V);
8721     // Make the DAGCombiner fold the bitcast.
8722     DCI.AddToWorklist(V.getNode());
8723   }
8724   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8725   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8726   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8727 }
8728
8729 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8730 static SDValue
8731 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8732   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8733   // At that time, we may have inserted bitcasts from integer to float.
8734   // If these bitcasts have survived DAGCombine, change the lowering of this
8735   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8736   // force to use floating point types.
8737
8738   // Make sure we can change the type of the vector.
8739   // This is possible iff:
8740   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8741   //    1.1. Vector is used only once.
8742   //    1.2. Use is a bit convert to an integer type.
8743   // 2. The size of its operands are 32-bits (64-bits are not legal).
8744   EVT VT = N->getValueType(0);
8745   EVT EltVT = VT.getVectorElementType();
8746
8747   // Check 1.1. and 2.
8748   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8749     return SDValue();
8750
8751   // By construction, the input type must be float.
8752   assert(EltVT == MVT::f32 && "Unexpected type!");
8753
8754   // Check 1.2.
8755   SDNode *Use = *N->use_begin();
8756   if (Use->getOpcode() != ISD::BITCAST ||
8757       Use->getValueType(0).isFloatingPoint())
8758     return SDValue();
8759
8760   // Check profitability.
8761   // Model is, if more than half of the relevant operands are bitcast from
8762   // i32, turn the build_vector into a sequence of insert_vector_elt.
8763   // Relevant operands are everything that is not statically
8764   // (i.e., at compile time) bitcasted.
8765   unsigned NumOfBitCastedElts = 0;
8766   unsigned NumElts = VT.getVectorNumElements();
8767   unsigned NumOfRelevantElts = NumElts;
8768   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8769     SDValue Elt = N->getOperand(Idx);
8770     if (Elt->getOpcode() == ISD::BITCAST) {
8771       // Assume only bit cast to i32 will go away.
8772       if (Elt->getOperand(0).getValueType() == MVT::i32)
8773         ++NumOfBitCastedElts;
8774     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8775       // Constants are statically casted, thus do not count them as
8776       // relevant operands.
8777       --NumOfRelevantElts;
8778   }
8779
8780   // Check if more than half of the elements require a non-free bitcast.
8781   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8782     return SDValue();
8783
8784   SelectionDAG &DAG = DCI.DAG;
8785   // Create the new vector type.
8786   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8787   // Check if the type is legal.
8788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8789   if (!TLI.isTypeLegal(VecVT))
8790     return SDValue();
8791
8792   // Combine:
8793   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8794   // => BITCAST INSERT_VECTOR_ELT
8795   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8796   //                      (BITCAST EN), N.
8797   SDValue Vec = DAG.getUNDEF(VecVT);
8798   SDLoc dl(N);
8799   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8800     SDValue V = N->getOperand(Idx);
8801     if (V.getOpcode() == ISD::UNDEF)
8802       continue;
8803     if (V.getOpcode() == ISD::BITCAST &&
8804         V->getOperand(0).getValueType() == MVT::i32)
8805       // Fold obvious case.
8806       V = V.getOperand(0);
8807     else {
8808       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8809       // Make the DAGCombiner fold the bitcasts.
8810       DCI.AddToWorklist(V.getNode());
8811     }
8812     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8813     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8814   }
8815   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8816   // Make the DAGCombiner fold the bitcasts.
8817   DCI.AddToWorklist(Vec.getNode());
8818   return Vec;
8819 }
8820
8821 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8822 /// ISD::INSERT_VECTOR_ELT.
8823 static SDValue PerformInsertEltCombine(SDNode *N,
8824                                        TargetLowering::DAGCombinerInfo &DCI) {
8825   // Bitcast an i64 load inserted into a vector to f64.
8826   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8827   EVT VT = N->getValueType(0);
8828   SDNode *Elt = N->getOperand(1).getNode();
8829   if (VT.getVectorElementType() != MVT::i64 ||
8830       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8831     return SDValue();
8832
8833   SelectionDAG &DAG = DCI.DAG;
8834   SDLoc dl(N);
8835   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8836                                  VT.getVectorNumElements());
8837   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8838   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8839   // Make the DAGCombiner fold the bitcasts.
8840   DCI.AddToWorklist(Vec.getNode());
8841   DCI.AddToWorklist(V.getNode());
8842   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8843                                Vec, V, N->getOperand(2));
8844   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8845 }
8846
8847 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8848 /// ISD::VECTOR_SHUFFLE.
8849 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8850   // The LLVM shufflevector instruction does not require the shuffle mask
8851   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8852   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8853   // operands do not match the mask length, they are extended by concatenating
8854   // them with undef vectors.  That is probably the right thing for other
8855   // targets, but for NEON it is better to concatenate two double-register
8856   // size vector operands into a single quad-register size vector.  Do that
8857   // transformation here:
8858   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8859   //   shuffle(concat(v1, v2), undef)
8860   SDValue Op0 = N->getOperand(0);
8861   SDValue Op1 = N->getOperand(1);
8862   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8863       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8864       Op0.getNumOperands() != 2 ||
8865       Op1.getNumOperands() != 2)
8866     return SDValue();
8867   SDValue Concat0Op1 = Op0.getOperand(1);
8868   SDValue Concat1Op1 = Op1.getOperand(1);
8869   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8870       Concat1Op1.getOpcode() != ISD::UNDEF)
8871     return SDValue();
8872   // Skip the transformation if any of the types are illegal.
8873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8874   EVT VT = N->getValueType(0);
8875   if (!TLI.isTypeLegal(VT) ||
8876       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8877       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8878     return SDValue();
8879
8880   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8881                                   Op0.getOperand(0), Op1.getOperand(0));
8882   // Translate the shuffle mask.
8883   SmallVector<int, 16> NewMask;
8884   unsigned NumElts = VT.getVectorNumElements();
8885   unsigned HalfElts = NumElts/2;
8886   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8887   for (unsigned n = 0; n < NumElts; ++n) {
8888     int MaskElt = SVN->getMaskElt(n);
8889     int NewElt = -1;
8890     if (MaskElt < (int)HalfElts)
8891       NewElt = MaskElt;
8892     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8893       NewElt = HalfElts + MaskElt - NumElts;
8894     NewMask.push_back(NewElt);
8895   }
8896   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8897                               DAG.getUNDEF(VT), NewMask.data());
8898 }
8899
8900 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8901 /// NEON load/store intrinsics to merge base address updates.
8902 static SDValue CombineBaseUpdate(SDNode *N,
8903                                  TargetLowering::DAGCombinerInfo &DCI) {
8904   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8905     return SDValue();
8906
8907   SelectionDAG &DAG = DCI.DAG;
8908   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8909                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8910   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8911   SDValue Addr = N->getOperand(AddrOpIdx);
8912
8913   // Search for a use of the address operand that is an increment.
8914   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8915          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8916     SDNode *User = *UI;
8917     if (User->getOpcode() != ISD::ADD ||
8918         UI.getUse().getResNo() != Addr.getResNo())
8919       continue;
8920
8921     // Check that the add is independent of the load/store.  Otherwise, folding
8922     // it would create a cycle.
8923     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8924       continue;
8925
8926     // Find the new opcode for the updating load/store.
8927     bool isLoad = true;
8928     bool isLaneOp = false;
8929     unsigned NewOpc = 0;
8930     unsigned NumVecs = 0;
8931     if (isIntrinsic) {
8932       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8933       switch (IntNo) {
8934       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8935       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8936         NumVecs = 1; break;
8937       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8938         NumVecs = 2; break;
8939       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8940         NumVecs = 3; break;
8941       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8942         NumVecs = 4; break;
8943       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8944         NumVecs = 2; isLaneOp = true; break;
8945       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8946         NumVecs = 3; isLaneOp = true; break;
8947       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8948         NumVecs = 4; isLaneOp = true; break;
8949       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8950         NumVecs = 1; isLoad = false; break;
8951       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8952         NumVecs = 2; isLoad = false; break;
8953       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8954         NumVecs = 3; isLoad = false; break;
8955       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8956         NumVecs = 4; isLoad = false; break;
8957       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8958         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8959       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8960         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8961       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8962         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8963       }
8964     } else {
8965       isLaneOp = true;
8966       switch (N->getOpcode()) {
8967       default: llvm_unreachable("unexpected opcode for Neon base update");
8968       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8969       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8970       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8971       }
8972     }
8973
8974     // Find the size of memory referenced by the load/store.
8975     EVT VecTy;
8976     if (isLoad)
8977       VecTy = N->getValueType(0);
8978     else
8979       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8980     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8981     if (isLaneOp)
8982       NumBytes /= VecTy.getVectorNumElements();
8983
8984     // If the increment is a constant, it must match the memory ref size.
8985     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8986     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8987       uint64_t IncVal = CInc->getZExtValue();
8988       if (IncVal != NumBytes)
8989         continue;
8990     } else if (NumBytes >= 3 * 16) {
8991       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8992       // separate instructions that make it harder to use a non-constant update.
8993       continue;
8994     }
8995
8996     // Create the new updating load/store node.
8997     EVT Tys[6];
8998     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8999     unsigned n;
9000     for (n = 0; n < NumResultVecs; ++n)
9001       Tys[n] = VecTy;
9002     Tys[n++] = MVT::i32;
9003     Tys[n] = MVT::Other;
9004     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
9005     SmallVector<SDValue, 8> Ops;
9006     Ops.push_back(N->getOperand(0)); // incoming chain
9007     Ops.push_back(N->getOperand(AddrOpIdx));
9008     Ops.push_back(Inc);
9009     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9010       Ops.push_back(N->getOperand(i));
9011     }
9012     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9013     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9014                                            Ops, MemInt->getMemoryVT(),
9015                                            MemInt->getMemOperand());
9016
9017     // Update the uses.
9018     std::vector<SDValue> NewResults;
9019     for (unsigned i = 0; i < NumResultVecs; ++i) {
9020       NewResults.push_back(SDValue(UpdN.getNode(), i));
9021     }
9022     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9023     DCI.CombineTo(N, NewResults);
9024     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9025
9026     break;
9027   }
9028   return SDValue();
9029 }
9030
9031 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9032 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9033 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9034 /// return true.
9035 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9036   SelectionDAG &DAG = DCI.DAG;
9037   EVT VT = N->getValueType(0);
9038   // vldN-dup instructions only support 64-bit vectors for N > 1.
9039   if (!VT.is64BitVector())
9040     return false;
9041
9042   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9043   SDNode *VLD = N->getOperand(0).getNode();
9044   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9045     return false;
9046   unsigned NumVecs = 0;
9047   unsigned NewOpc = 0;
9048   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9049   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9050     NumVecs = 2;
9051     NewOpc = ARMISD::VLD2DUP;
9052   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9053     NumVecs = 3;
9054     NewOpc = ARMISD::VLD3DUP;
9055   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9056     NumVecs = 4;
9057     NewOpc = ARMISD::VLD4DUP;
9058   } else {
9059     return false;
9060   }
9061
9062   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9063   // numbers match the load.
9064   unsigned VLDLaneNo =
9065     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9066   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9067        UI != UE; ++UI) {
9068     // Ignore uses of the chain result.
9069     if (UI.getUse().getResNo() == NumVecs)
9070       continue;
9071     SDNode *User = *UI;
9072     if (User->getOpcode() != ARMISD::VDUPLANE ||
9073         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9074       return false;
9075   }
9076
9077   // Create the vldN-dup node.
9078   EVT Tys[5];
9079   unsigned n;
9080   for (n = 0; n < NumVecs; ++n)
9081     Tys[n] = VT;
9082   Tys[n] = MVT::Other;
9083   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9084   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9085   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9086   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9087                                            Ops, VLDMemInt->getMemoryVT(),
9088                                            VLDMemInt->getMemOperand());
9089
9090   // Update the uses.
9091   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9092        UI != UE; ++UI) {
9093     unsigned ResNo = UI.getUse().getResNo();
9094     // Ignore uses of the chain result.
9095     if (ResNo == NumVecs)
9096       continue;
9097     SDNode *User = *UI;
9098     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9099   }
9100
9101   // Now the vldN-lane intrinsic is dead except for its chain result.
9102   // Update uses of the chain.
9103   std::vector<SDValue> VLDDupResults;
9104   for (unsigned n = 0; n < NumVecs; ++n)
9105     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9106   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9107   DCI.CombineTo(VLD, VLDDupResults);
9108
9109   return true;
9110 }
9111
9112 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9113 /// ARMISD::VDUPLANE.
9114 static SDValue PerformVDUPLANECombine(SDNode *N,
9115                                       TargetLowering::DAGCombinerInfo &DCI) {
9116   SDValue Op = N->getOperand(0);
9117
9118   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9119   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9120   if (CombineVLDDUP(N, DCI))
9121     return SDValue(N, 0);
9122
9123   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9124   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9125   while (Op.getOpcode() == ISD::BITCAST)
9126     Op = Op.getOperand(0);
9127   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9128     return SDValue();
9129
9130   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9131   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9132   // The canonical VMOV for a zero vector uses a 32-bit element size.
9133   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9134   unsigned EltBits;
9135   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9136     EltSize = 8;
9137   EVT VT = N->getValueType(0);
9138   if (EltSize > VT.getVectorElementType().getSizeInBits())
9139     return SDValue();
9140
9141   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9142 }
9143
9144 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9145 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9146 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9147 {
9148   integerPart cN;
9149   integerPart c0 = 0;
9150   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9151        I != E; I++) {
9152     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9153     if (!C)
9154       return false;
9155
9156     bool isExact;
9157     APFloat APF = C->getValueAPF();
9158     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9159         != APFloat::opOK || !isExact)
9160       return false;
9161
9162     c0 = (I == 0) ? cN : c0;
9163     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9164       return false;
9165   }
9166   C = c0;
9167   return true;
9168 }
9169
9170 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9171 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9172 /// when the VMUL has a constant operand that is a power of 2.
9173 ///
9174 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9175 ///  vmul.f32        d16, d17, d16
9176 ///  vcvt.s32.f32    d16, d16
9177 /// becomes:
9178 ///  vcvt.s32.f32    d16, d16, #3
9179 static SDValue PerformVCVTCombine(SDNode *N,
9180                                   TargetLowering::DAGCombinerInfo &DCI,
9181                                   const ARMSubtarget *Subtarget) {
9182   SelectionDAG &DAG = DCI.DAG;
9183   SDValue Op = N->getOperand(0);
9184
9185   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9186       Op.getOpcode() != ISD::FMUL)
9187     return SDValue();
9188
9189   uint64_t C;
9190   SDValue N0 = Op->getOperand(0);
9191   SDValue ConstVec = Op->getOperand(1);
9192   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9193
9194   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9195       !isConstVecPow2(ConstVec, isSigned, C))
9196     return SDValue();
9197
9198   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9199   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9200   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9201     // These instructions only exist converting from f32 to i32. We can handle
9202     // smaller integers by generating an extra truncate, but larger ones would
9203     // be lossy.
9204     return SDValue();
9205   }
9206
9207   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9208     Intrinsic::arm_neon_vcvtfp2fxu;
9209   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9210   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9211                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9212                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9213                                  DAG.getConstant(Log2_64(C), MVT::i32));
9214
9215   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9216     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9217
9218   return FixConv;
9219 }
9220
9221 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9222 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9223 /// when the VDIV has a constant operand that is a power of 2.
9224 ///
9225 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9226 ///  vcvt.f32.s32    d16, d16
9227 ///  vdiv.f32        d16, d17, d16
9228 /// becomes:
9229 ///  vcvt.f32.s32    d16, d16, #3
9230 static SDValue PerformVDIVCombine(SDNode *N,
9231                                   TargetLowering::DAGCombinerInfo &DCI,
9232                                   const ARMSubtarget *Subtarget) {
9233   SelectionDAG &DAG = DCI.DAG;
9234   SDValue Op = N->getOperand(0);
9235   unsigned OpOpcode = Op.getNode()->getOpcode();
9236
9237   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9238       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9239     return SDValue();
9240
9241   uint64_t C;
9242   SDValue ConstVec = N->getOperand(1);
9243   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9244
9245   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9246       !isConstVecPow2(ConstVec, isSigned, C))
9247     return SDValue();
9248
9249   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9250   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9251   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9252     // These instructions only exist converting from i32 to f32. We can handle
9253     // smaller integers by generating an extra extend, but larger ones would
9254     // be lossy.
9255     return SDValue();
9256   }
9257
9258   SDValue ConvInput = Op.getOperand(0);
9259   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9260   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9261     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9262                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9263                             ConvInput);
9264
9265   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9266     Intrinsic::arm_neon_vcvtfxu2fp;
9267   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9268                      Op.getValueType(),
9269                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9270                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9271 }
9272
9273 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9274 /// operand of a vector shift operation, where all the elements of the
9275 /// build_vector must have the same constant integer value.
9276 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9277   // Ignore bit_converts.
9278   while (Op.getOpcode() == ISD::BITCAST)
9279     Op = Op.getOperand(0);
9280   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9281   APInt SplatBits, SplatUndef;
9282   unsigned SplatBitSize;
9283   bool HasAnyUndefs;
9284   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9285                                       HasAnyUndefs, ElementBits) ||
9286       SplatBitSize > ElementBits)
9287     return false;
9288   Cnt = SplatBits.getSExtValue();
9289   return true;
9290 }
9291
9292 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9293 /// operand of a vector shift left operation.  That value must be in the range:
9294 ///   0 <= Value < ElementBits for a left shift; or
9295 ///   0 <= Value <= ElementBits for a long left shift.
9296 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9297   assert(VT.isVector() && "vector shift count is not a vector type");
9298   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9299   if (! getVShiftImm(Op, ElementBits, Cnt))
9300     return false;
9301   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9302 }
9303
9304 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9305 /// operand of a vector shift right operation.  For a shift opcode, the value
9306 /// is positive, but for an intrinsic the value count must be negative. The
9307 /// absolute value must be in the range:
9308 ///   1 <= |Value| <= ElementBits for a right shift; or
9309 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9310 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9311                          int64_t &Cnt) {
9312   assert(VT.isVector() && "vector shift count is not a vector type");
9313   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9314   if (! getVShiftImm(Op, ElementBits, Cnt))
9315     return false;
9316   if (isIntrinsic)
9317     Cnt = -Cnt;
9318   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9319 }
9320
9321 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9322 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9323   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9324   switch (IntNo) {
9325   default:
9326     // Don't do anything for most intrinsics.
9327     break;
9328
9329   // Vector shifts: check for immediate versions and lower them.
9330   // Note: This is done during DAG combining instead of DAG legalizing because
9331   // the build_vectors for 64-bit vector element shift counts are generally
9332   // not legal, and it is hard to see their values after they get legalized to
9333   // loads from a constant pool.
9334   case Intrinsic::arm_neon_vshifts:
9335   case Intrinsic::arm_neon_vshiftu:
9336   case Intrinsic::arm_neon_vrshifts:
9337   case Intrinsic::arm_neon_vrshiftu:
9338   case Intrinsic::arm_neon_vrshiftn:
9339   case Intrinsic::arm_neon_vqshifts:
9340   case Intrinsic::arm_neon_vqshiftu:
9341   case Intrinsic::arm_neon_vqshiftsu:
9342   case Intrinsic::arm_neon_vqshiftns:
9343   case Intrinsic::arm_neon_vqshiftnu:
9344   case Intrinsic::arm_neon_vqshiftnsu:
9345   case Intrinsic::arm_neon_vqrshiftns:
9346   case Intrinsic::arm_neon_vqrshiftnu:
9347   case Intrinsic::arm_neon_vqrshiftnsu: {
9348     EVT VT = N->getOperand(1).getValueType();
9349     int64_t Cnt;
9350     unsigned VShiftOpc = 0;
9351
9352     switch (IntNo) {
9353     case Intrinsic::arm_neon_vshifts:
9354     case Intrinsic::arm_neon_vshiftu:
9355       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9356         VShiftOpc = ARMISD::VSHL;
9357         break;
9358       }
9359       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9360         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9361                      ARMISD::VSHRs : ARMISD::VSHRu);
9362         break;
9363       }
9364       return SDValue();
9365
9366     case Intrinsic::arm_neon_vrshifts:
9367     case Intrinsic::arm_neon_vrshiftu:
9368       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9369         break;
9370       return SDValue();
9371
9372     case Intrinsic::arm_neon_vqshifts:
9373     case Intrinsic::arm_neon_vqshiftu:
9374       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9375         break;
9376       return SDValue();
9377
9378     case Intrinsic::arm_neon_vqshiftsu:
9379       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9380         break;
9381       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9382
9383     case Intrinsic::arm_neon_vrshiftn:
9384     case Intrinsic::arm_neon_vqshiftns:
9385     case Intrinsic::arm_neon_vqshiftnu:
9386     case Intrinsic::arm_neon_vqshiftnsu:
9387     case Intrinsic::arm_neon_vqrshiftns:
9388     case Intrinsic::arm_neon_vqrshiftnu:
9389     case Intrinsic::arm_neon_vqrshiftnsu:
9390       // Narrowing shifts require an immediate right shift.
9391       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9392         break;
9393       llvm_unreachable("invalid shift count for narrowing vector shift "
9394                        "intrinsic");
9395
9396     default:
9397       llvm_unreachable("unhandled vector shift");
9398     }
9399
9400     switch (IntNo) {
9401     case Intrinsic::arm_neon_vshifts:
9402     case Intrinsic::arm_neon_vshiftu:
9403       // Opcode already set above.
9404       break;
9405     case Intrinsic::arm_neon_vrshifts:
9406       VShiftOpc = ARMISD::VRSHRs; break;
9407     case Intrinsic::arm_neon_vrshiftu:
9408       VShiftOpc = ARMISD::VRSHRu; break;
9409     case Intrinsic::arm_neon_vrshiftn:
9410       VShiftOpc = ARMISD::VRSHRN; break;
9411     case Intrinsic::arm_neon_vqshifts:
9412       VShiftOpc = ARMISD::VQSHLs; break;
9413     case Intrinsic::arm_neon_vqshiftu:
9414       VShiftOpc = ARMISD::VQSHLu; break;
9415     case Intrinsic::arm_neon_vqshiftsu:
9416       VShiftOpc = ARMISD::VQSHLsu; break;
9417     case Intrinsic::arm_neon_vqshiftns:
9418       VShiftOpc = ARMISD::VQSHRNs; break;
9419     case Intrinsic::arm_neon_vqshiftnu:
9420       VShiftOpc = ARMISD::VQSHRNu; break;
9421     case Intrinsic::arm_neon_vqshiftnsu:
9422       VShiftOpc = ARMISD::VQSHRNsu; break;
9423     case Intrinsic::arm_neon_vqrshiftns:
9424       VShiftOpc = ARMISD::VQRSHRNs; break;
9425     case Intrinsic::arm_neon_vqrshiftnu:
9426       VShiftOpc = ARMISD::VQRSHRNu; break;
9427     case Intrinsic::arm_neon_vqrshiftnsu:
9428       VShiftOpc = ARMISD::VQRSHRNsu; break;
9429     }
9430
9431     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9432                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9433   }
9434
9435   case Intrinsic::arm_neon_vshiftins: {
9436     EVT VT = N->getOperand(1).getValueType();
9437     int64_t Cnt;
9438     unsigned VShiftOpc = 0;
9439
9440     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9441       VShiftOpc = ARMISD::VSLI;
9442     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9443       VShiftOpc = ARMISD::VSRI;
9444     else {
9445       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9446     }
9447
9448     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9449                        N->getOperand(1), N->getOperand(2),
9450                        DAG.getConstant(Cnt, MVT::i32));
9451   }
9452
9453   case Intrinsic::arm_neon_vqrshifts:
9454   case Intrinsic::arm_neon_vqrshiftu:
9455     // No immediate versions of these to check for.
9456     break;
9457   }
9458
9459   return SDValue();
9460 }
9461
9462 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9463 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9464 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9465 /// vector element shift counts are generally not legal, and it is hard to see
9466 /// their values after they get legalized to loads from a constant pool.
9467 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9468                                    const ARMSubtarget *ST) {
9469   EVT VT = N->getValueType(0);
9470   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9471     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9472     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9473     SDValue N1 = N->getOperand(1);
9474     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9475       SDValue N0 = N->getOperand(0);
9476       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9477           DAG.MaskedValueIsZero(N0.getOperand(0),
9478                                 APInt::getHighBitsSet(32, 16)))
9479         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9480     }
9481   }
9482
9483   // Nothing to be done for scalar shifts.
9484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9485   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9486     return SDValue();
9487
9488   assert(ST->hasNEON() && "unexpected vector shift");
9489   int64_t Cnt;
9490
9491   switch (N->getOpcode()) {
9492   default: llvm_unreachable("unexpected shift opcode");
9493
9494   case ISD::SHL:
9495     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9496       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9497                          DAG.getConstant(Cnt, MVT::i32));
9498     break;
9499
9500   case ISD::SRA:
9501   case ISD::SRL:
9502     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9503       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9504                             ARMISD::VSHRs : ARMISD::VSHRu);
9505       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9506                          DAG.getConstant(Cnt, MVT::i32));
9507     }
9508   }
9509   return SDValue();
9510 }
9511
9512 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9513 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9514 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9515                                     const ARMSubtarget *ST) {
9516   SDValue N0 = N->getOperand(0);
9517
9518   // Check for sign- and zero-extensions of vector extract operations of 8-
9519   // and 16-bit vector elements.  NEON supports these directly.  They are
9520   // handled during DAG combining because type legalization will promote them
9521   // to 32-bit types and it is messy to recognize the operations after that.
9522   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9523     SDValue Vec = N0.getOperand(0);
9524     SDValue Lane = N0.getOperand(1);
9525     EVT VT = N->getValueType(0);
9526     EVT EltVT = N0.getValueType();
9527     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9528
9529     if (VT == MVT::i32 &&
9530         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9531         TLI.isTypeLegal(Vec.getValueType()) &&
9532         isa<ConstantSDNode>(Lane)) {
9533
9534       unsigned Opc = 0;
9535       switch (N->getOpcode()) {
9536       default: llvm_unreachable("unexpected opcode");
9537       case ISD::SIGN_EXTEND:
9538         Opc = ARMISD::VGETLANEs;
9539         break;
9540       case ISD::ZERO_EXTEND:
9541       case ISD::ANY_EXTEND:
9542         Opc = ARMISD::VGETLANEu;
9543         break;
9544       }
9545       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9546     }
9547   }
9548
9549   return SDValue();
9550 }
9551
9552 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9553 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9554 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9555                                        const ARMSubtarget *ST) {
9556   // If the target supports NEON, try to use vmax/vmin instructions for f32
9557   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9558   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9559   // a NaN; only do the transformation when it matches that behavior.
9560
9561   // For now only do this when using NEON for FP operations; if using VFP, it
9562   // is not obvious that the benefit outweighs the cost of switching to the
9563   // NEON pipeline.
9564   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9565       N->getValueType(0) != MVT::f32)
9566     return SDValue();
9567
9568   SDValue CondLHS = N->getOperand(0);
9569   SDValue CondRHS = N->getOperand(1);
9570   SDValue LHS = N->getOperand(2);
9571   SDValue RHS = N->getOperand(3);
9572   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9573
9574   unsigned Opcode = 0;
9575   bool IsReversed;
9576   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9577     IsReversed = false; // x CC y ? x : y
9578   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9579     IsReversed = true ; // x CC y ? y : x
9580   } else {
9581     return SDValue();
9582   }
9583
9584   bool IsUnordered;
9585   switch (CC) {
9586   default: break;
9587   case ISD::SETOLT:
9588   case ISD::SETOLE:
9589   case ISD::SETLT:
9590   case ISD::SETLE:
9591   case ISD::SETULT:
9592   case ISD::SETULE:
9593     // If LHS is NaN, an ordered comparison will be false and the result will
9594     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9595     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9596     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9597     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9598       break;
9599     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9600     // will return -0, so vmin can only be used for unsafe math or if one of
9601     // the operands is known to be nonzero.
9602     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9603         !DAG.getTarget().Options.UnsafeFPMath &&
9604         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9605       break;
9606     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9607     break;
9608
9609   case ISD::SETOGT:
9610   case ISD::SETOGE:
9611   case ISD::SETGT:
9612   case ISD::SETGE:
9613   case ISD::SETUGT:
9614   case ISD::SETUGE:
9615     // If LHS is NaN, an ordered comparison will be false and the result will
9616     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9617     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9618     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9619     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9620       break;
9621     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9622     // will return +0, so vmax can only be used for unsafe math or if one of
9623     // the operands is known to be nonzero.
9624     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9625         !DAG.getTarget().Options.UnsafeFPMath &&
9626         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9627       break;
9628     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9629     break;
9630   }
9631
9632   if (!Opcode)
9633     return SDValue();
9634   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9635 }
9636
9637 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9638 SDValue
9639 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9640   SDValue Cmp = N->getOperand(4);
9641   if (Cmp.getOpcode() != ARMISD::CMPZ)
9642     // Only looking at EQ and NE cases.
9643     return SDValue();
9644
9645   EVT VT = N->getValueType(0);
9646   SDLoc dl(N);
9647   SDValue LHS = Cmp.getOperand(0);
9648   SDValue RHS = Cmp.getOperand(1);
9649   SDValue FalseVal = N->getOperand(0);
9650   SDValue TrueVal = N->getOperand(1);
9651   SDValue ARMcc = N->getOperand(2);
9652   ARMCC::CondCodes CC =
9653     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9654
9655   // Simplify
9656   //   mov     r1, r0
9657   //   cmp     r1, x
9658   //   mov     r0, y
9659   //   moveq   r0, x
9660   // to
9661   //   cmp     r0, x
9662   //   movne   r0, y
9663   //
9664   //   mov     r1, r0
9665   //   cmp     r1, x
9666   //   mov     r0, x
9667   //   movne   r0, y
9668   // to
9669   //   cmp     r0, x
9670   //   movne   r0, y
9671   /// FIXME: Turn this into a target neutral optimization?
9672   SDValue Res;
9673   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9674     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9675                       N->getOperand(3), Cmp);
9676   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9677     SDValue ARMcc;
9678     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9679     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9680                       N->getOperand(3), NewCmp);
9681   }
9682
9683   if (Res.getNode()) {
9684     APInt KnownZero, KnownOne;
9685     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9686     // Capture demanded bits information that would be otherwise lost.
9687     if (KnownZero == 0xfffffffe)
9688       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9689                         DAG.getValueType(MVT::i1));
9690     else if (KnownZero == 0xffffff00)
9691       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9692                         DAG.getValueType(MVT::i8));
9693     else if (KnownZero == 0xffff0000)
9694       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9695                         DAG.getValueType(MVT::i16));
9696   }
9697
9698   return Res;
9699 }
9700
9701 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9702                                              DAGCombinerInfo &DCI) const {
9703   switch (N->getOpcode()) {
9704   default: break;
9705   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9706   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9707   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9708   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9709   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9710   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9711   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9712   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9713   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9714   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9715   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9716   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9717   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9718   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9719   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9720   case ISD::FP_TO_SINT:
9721   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9722   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9723   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9724   case ISD::SHL:
9725   case ISD::SRA:
9726   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9727   case ISD::SIGN_EXTEND:
9728   case ISD::ZERO_EXTEND:
9729   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9730   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9731   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9732   case ARMISD::VLD2DUP:
9733   case ARMISD::VLD3DUP:
9734   case ARMISD::VLD4DUP:
9735     return CombineBaseUpdate(N, DCI);
9736   case ARMISD::BUILD_VECTOR:
9737     return PerformARMBUILD_VECTORCombine(N, DCI);
9738   case ISD::INTRINSIC_VOID:
9739   case ISD::INTRINSIC_W_CHAIN:
9740     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9741     case Intrinsic::arm_neon_vld1:
9742     case Intrinsic::arm_neon_vld2:
9743     case Intrinsic::arm_neon_vld3:
9744     case Intrinsic::arm_neon_vld4:
9745     case Intrinsic::arm_neon_vld2lane:
9746     case Intrinsic::arm_neon_vld3lane:
9747     case Intrinsic::arm_neon_vld4lane:
9748     case Intrinsic::arm_neon_vst1:
9749     case Intrinsic::arm_neon_vst2:
9750     case Intrinsic::arm_neon_vst3:
9751     case Intrinsic::arm_neon_vst4:
9752     case Intrinsic::arm_neon_vst2lane:
9753     case Intrinsic::arm_neon_vst3lane:
9754     case Intrinsic::arm_neon_vst4lane:
9755       return CombineBaseUpdate(N, DCI);
9756     default: break;
9757     }
9758     break;
9759   }
9760   return SDValue();
9761 }
9762
9763 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9764                                                           EVT VT) const {
9765   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9766 }
9767
9768 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9769                                                        unsigned,
9770                                                        unsigned,
9771                                                        bool *Fast) const {
9772   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9773   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9774
9775   switch (VT.getSimpleVT().SimpleTy) {
9776   default:
9777     return false;
9778   case MVT::i8:
9779   case MVT::i16:
9780   case MVT::i32: {
9781     // Unaligned access can use (for example) LRDB, LRDH, LDR
9782     if (AllowsUnaligned) {
9783       if (Fast)
9784         *Fast = Subtarget->hasV7Ops();
9785       return true;
9786     }
9787     return false;
9788   }
9789   case MVT::f64:
9790   case MVT::v2f64: {
9791     // For any little-endian targets with neon, we can support unaligned ld/st
9792     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9793     // A big-endian target may also explicitly support unaligned accesses
9794     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9795       if (Fast)
9796         *Fast = true;
9797       return true;
9798     }
9799     return false;
9800   }
9801   }
9802 }
9803
9804 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9805                        unsigned AlignCheck) {
9806   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9807           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9808 }
9809
9810 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9811                                            unsigned DstAlign, unsigned SrcAlign,
9812                                            bool IsMemset, bool ZeroMemset,
9813                                            bool MemcpyStrSrc,
9814                                            MachineFunction &MF) const {
9815   const Function *F = MF.getFunction();
9816
9817   // See if we can use NEON instructions for this...
9818   if ((!IsMemset || ZeroMemset) &&
9819       Subtarget->hasNEON() &&
9820       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9821                                        Attribute::NoImplicitFloat)) {
9822     bool Fast;
9823     if (Size >= 16 &&
9824         (memOpAlign(SrcAlign, DstAlign, 16) ||
9825          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9826       return MVT::v2f64;
9827     } else if (Size >= 8 &&
9828                (memOpAlign(SrcAlign, DstAlign, 8) ||
9829                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9830                  Fast))) {
9831       return MVT::f64;
9832     }
9833   }
9834
9835   // Lowering to i32/i16 if the size permits.
9836   if (Size >= 4)
9837     return MVT::i32;
9838   else if (Size >= 2)
9839     return MVT::i16;
9840
9841   // Let the target-independent logic figure it out.
9842   return MVT::Other;
9843 }
9844
9845 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9846   if (Val.getOpcode() != ISD::LOAD)
9847     return false;
9848
9849   EVT VT1 = Val.getValueType();
9850   if (!VT1.isSimple() || !VT1.isInteger() ||
9851       !VT2.isSimple() || !VT2.isInteger())
9852     return false;
9853
9854   switch (VT1.getSimpleVT().SimpleTy) {
9855   default: break;
9856   case MVT::i1:
9857   case MVT::i8:
9858   case MVT::i16:
9859     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9860     return true;
9861   }
9862
9863   return false;
9864 }
9865
9866 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9867   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9868     return false;
9869
9870   if (!isTypeLegal(EVT::getEVT(Ty1)))
9871     return false;
9872
9873   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9874
9875   // Assuming the caller doesn't have a zeroext or signext return parameter,
9876   // truncation all the way down to i1 is valid.
9877   return true;
9878 }
9879
9880
9881 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9882   if (V < 0)
9883     return false;
9884
9885   unsigned Scale = 1;
9886   switch (VT.getSimpleVT().SimpleTy) {
9887   default: return false;
9888   case MVT::i1:
9889   case MVT::i8:
9890     // Scale == 1;
9891     break;
9892   case MVT::i16:
9893     // Scale == 2;
9894     Scale = 2;
9895     break;
9896   case MVT::i32:
9897     // Scale == 4;
9898     Scale = 4;
9899     break;
9900   }
9901
9902   if ((V & (Scale - 1)) != 0)
9903     return false;
9904   V /= Scale;
9905   return V == (V & ((1LL << 5) - 1));
9906 }
9907
9908 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9909                                       const ARMSubtarget *Subtarget) {
9910   bool isNeg = false;
9911   if (V < 0) {
9912     isNeg = true;
9913     V = - V;
9914   }
9915
9916   switch (VT.getSimpleVT().SimpleTy) {
9917   default: return false;
9918   case MVT::i1:
9919   case MVT::i8:
9920   case MVT::i16:
9921   case MVT::i32:
9922     // + imm12 or - imm8
9923     if (isNeg)
9924       return V == (V & ((1LL << 8) - 1));
9925     return V == (V & ((1LL << 12) - 1));
9926   case MVT::f32:
9927   case MVT::f64:
9928     // Same as ARM mode. FIXME: NEON?
9929     if (!Subtarget->hasVFP2())
9930       return false;
9931     if ((V & 3) != 0)
9932       return false;
9933     V >>= 2;
9934     return V == (V & ((1LL << 8) - 1));
9935   }
9936 }
9937
9938 /// isLegalAddressImmediate - Return true if the integer value can be used
9939 /// as the offset of the target addressing mode for load / store of the
9940 /// given type.
9941 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9942                                     const ARMSubtarget *Subtarget) {
9943   if (V == 0)
9944     return true;
9945
9946   if (!VT.isSimple())
9947     return false;
9948
9949   if (Subtarget->isThumb1Only())
9950     return isLegalT1AddressImmediate(V, VT);
9951   else if (Subtarget->isThumb2())
9952     return isLegalT2AddressImmediate(V, VT, Subtarget);
9953
9954   // ARM mode.
9955   if (V < 0)
9956     V = - V;
9957   switch (VT.getSimpleVT().SimpleTy) {
9958   default: return false;
9959   case MVT::i1:
9960   case MVT::i8:
9961   case MVT::i32:
9962     // +- imm12
9963     return V == (V & ((1LL << 12) - 1));
9964   case MVT::i16:
9965     // +- imm8
9966     return V == (V & ((1LL << 8) - 1));
9967   case MVT::f32:
9968   case MVT::f64:
9969     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9970       return false;
9971     if ((V & 3) != 0)
9972       return false;
9973     V >>= 2;
9974     return V == (V & ((1LL << 8) - 1));
9975   }
9976 }
9977
9978 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9979                                                       EVT VT) const {
9980   int Scale = AM.Scale;
9981   if (Scale < 0)
9982     return false;
9983
9984   switch (VT.getSimpleVT().SimpleTy) {
9985   default: return false;
9986   case MVT::i1:
9987   case MVT::i8:
9988   case MVT::i16:
9989   case MVT::i32:
9990     if (Scale == 1)
9991       return true;
9992     // r + r << imm
9993     Scale = Scale & ~1;
9994     return Scale == 2 || Scale == 4 || Scale == 8;
9995   case MVT::i64:
9996     // r + r
9997     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9998       return true;
9999     return false;
10000   case MVT::isVoid:
10001     // Note, we allow "void" uses (basically, uses that aren't loads or
10002     // stores), because arm allows folding a scale into many arithmetic
10003     // operations.  This should be made more precise and revisited later.
10004
10005     // Allow r << imm, but the imm has to be a multiple of two.
10006     if (Scale & 1) return false;
10007     return isPowerOf2_32(Scale);
10008   }
10009 }
10010
10011 /// isLegalAddressingMode - Return true if the addressing mode represented
10012 /// by AM is legal for this target, for a load/store of the specified type.
10013 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10014                                               Type *Ty) const {
10015   EVT VT = getValueType(Ty, true);
10016   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10017     return false;
10018
10019   // Can never fold addr of global into load/store.
10020   if (AM.BaseGV)
10021     return false;
10022
10023   switch (AM.Scale) {
10024   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10025     break;
10026   case 1:
10027     if (Subtarget->isThumb1Only())
10028       return false;
10029     // FALL THROUGH.
10030   default:
10031     // ARM doesn't support any R+R*scale+imm addr modes.
10032     if (AM.BaseOffs)
10033       return false;
10034
10035     if (!VT.isSimple())
10036       return false;
10037
10038     if (Subtarget->isThumb2())
10039       return isLegalT2ScaledAddressingMode(AM, VT);
10040
10041     int Scale = AM.Scale;
10042     switch (VT.getSimpleVT().SimpleTy) {
10043     default: return false;
10044     case MVT::i1:
10045     case MVT::i8:
10046     case MVT::i32:
10047       if (Scale < 0) Scale = -Scale;
10048       if (Scale == 1)
10049         return true;
10050       // r + r << imm
10051       return isPowerOf2_32(Scale & ~1);
10052     case MVT::i16:
10053     case MVT::i64:
10054       // r + r
10055       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10056         return true;
10057       return false;
10058
10059     case MVT::isVoid:
10060       // Note, we allow "void" uses (basically, uses that aren't loads or
10061       // stores), because arm allows folding a scale into many arithmetic
10062       // operations.  This should be made more precise and revisited later.
10063
10064       // Allow r << imm, but the imm has to be a multiple of two.
10065       if (Scale & 1) return false;
10066       return isPowerOf2_32(Scale);
10067     }
10068   }
10069   return true;
10070 }
10071
10072 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10073 /// icmp immediate, that is the target has icmp instructions which can compare
10074 /// a register against the immediate without having to materialize the
10075 /// immediate into a register.
10076 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10077   // Thumb2 and ARM modes can use cmn for negative immediates.
10078   if (!Subtarget->isThumb())
10079     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10080   if (Subtarget->isThumb2())
10081     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10082   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10083   return Imm >= 0 && Imm <= 255;
10084 }
10085
10086 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10087 /// *or sub* immediate, that is the target has add or sub instructions which can
10088 /// add a register with the immediate without having to materialize the
10089 /// immediate into a register.
10090 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10091   // Same encoding for add/sub, just flip the sign.
10092   int64_t AbsImm = llvm::abs64(Imm);
10093   if (!Subtarget->isThumb())
10094     return ARM_AM::getSOImmVal(AbsImm) != -1;
10095   if (Subtarget->isThumb2())
10096     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10097   // Thumb1 only has 8-bit unsigned immediate.
10098   return AbsImm >= 0 && AbsImm <= 255;
10099 }
10100
10101 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10102                                       bool isSEXTLoad, SDValue &Base,
10103                                       SDValue &Offset, bool &isInc,
10104                                       SelectionDAG &DAG) {
10105   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10106     return false;
10107
10108   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10109     // AddressingMode 3
10110     Base = Ptr->getOperand(0);
10111     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10112       int RHSC = (int)RHS->getZExtValue();
10113       if (RHSC < 0 && RHSC > -256) {
10114         assert(Ptr->getOpcode() == ISD::ADD);
10115         isInc = false;
10116         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10117         return true;
10118       }
10119     }
10120     isInc = (Ptr->getOpcode() == ISD::ADD);
10121     Offset = Ptr->getOperand(1);
10122     return true;
10123   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10124     // AddressingMode 2
10125     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10126       int RHSC = (int)RHS->getZExtValue();
10127       if (RHSC < 0 && RHSC > -0x1000) {
10128         assert(Ptr->getOpcode() == ISD::ADD);
10129         isInc = false;
10130         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10131         Base = Ptr->getOperand(0);
10132         return true;
10133       }
10134     }
10135
10136     if (Ptr->getOpcode() == ISD::ADD) {
10137       isInc = true;
10138       ARM_AM::ShiftOpc ShOpcVal=
10139         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10140       if (ShOpcVal != ARM_AM::no_shift) {
10141         Base = Ptr->getOperand(1);
10142         Offset = Ptr->getOperand(0);
10143       } else {
10144         Base = Ptr->getOperand(0);
10145         Offset = Ptr->getOperand(1);
10146       }
10147       return true;
10148     }
10149
10150     isInc = (Ptr->getOpcode() == ISD::ADD);
10151     Base = Ptr->getOperand(0);
10152     Offset = Ptr->getOperand(1);
10153     return true;
10154   }
10155
10156   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10157   return false;
10158 }
10159
10160 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10161                                      bool isSEXTLoad, SDValue &Base,
10162                                      SDValue &Offset, bool &isInc,
10163                                      SelectionDAG &DAG) {
10164   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10165     return false;
10166
10167   Base = Ptr->getOperand(0);
10168   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10169     int RHSC = (int)RHS->getZExtValue();
10170     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10171       assert(Ptr->getOpcode() == ISD::ADD);
10172       isInc = false;
10173       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10174       return true;
10175     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10176       isInc = Ptr->getOpcode() == ISD::ADD;
10177       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10178       return true;
10179     }
10180   }
10181
10182   return false;
10183 }
10184
10185 /// getPreIndexedAddressParts - returns true by value, base pointer and
10186 /// offset pointer and addressing mode by reference if the node's address
10187 /// can be legally represented as pre-indexed load / store address.
10188 bool
10189 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10190                                              SDValue &Offset,
10191                                              ISD::MemIndexedMode &AM,
10192                                              SelectionDAG &DAG) const {
10193   if (Subtarget->isThumb1Only())
10194     return false;
10195
10196   EVT VT;
10197   SDValue Ptr;
10198   bool isSEXTLoad = false;
10199   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10200     Ptr = LD->getBasePtr();
10201     VT  = LD->getMemoryVT();
10202     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10203   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10204     Ptr = ST->getBasePtr();
10205     VT  = ST->getMemoryVT();
10206   } else
10207     return false;
10208
10209   bool isInc;
10210   bool isLegal = false;
10211   if (Subtarget->isThumb2())
10212     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10213                                        Offset, isInc, DAG);
10214   else
10215     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10216                                         Offset, isInc, DAG);
10217   if (!isLegal)
10218     return false;
10219
10220   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10221   return true;
10222 }
10223
10224 /// getPostIndexedAddressParts - returns true by value, base pointer and
10225 /// offset pointer and addressing mode by reference if this node can be
10226 /// combined with a load / store to form a post-indexed load / store.
10227 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10228                                                    SDValue &Base,
10229                                                    SDValue &Offset,
10230                                                    ISD::MemIndexedMode &AM,
10231                                                    SelectionDAG &DAG) const {
10232   if (Subtarget->isThumb1Only())
10233     return false;
10234
10235   EVT VT;
10236   SDValue Ptr;
10237   bool isSEXTLoad = false;
10238   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10239     VT  = LD->getMemoryVT();
10240     Ptr = LD->getBasePtr();
10241     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10242   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10243     VT  = ST->getMemoryVT();
10244     Ptr = ST->getBasePtr();
10245   } else
10246     return false;
10247
10248   bool isInc;
10249   bool isLegal = false;
10250   if (Subtarget->isThumb2())
10251     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10252                                        isInc, DAG);
10253   else
10254     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10255                                         isInc, DAG);
10256   if (!isLegal)
10257     return false;
10258
10259   if (Ptr != Base) {
10260     // Swap base ptr and offset to catch more post-index load / store when
10261     // it's legal. In Thumb2 mode, offset must be an immediate.
10262     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10263         !Subtarget->isThumb2())
10264       std::swap(Base, Offset);
10265
10266     // Post-indexed load / store update the base pointer.
10267     if (Ptr != Base)
10268       return false;
10269   }
10270
10271   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10272   return true;
10273 }
10274
10275 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10276                                                       APInt &KnownZero,
10277                                                       APInt &KnownOne,
10278                                                       const SelectionDAG &DAG,
10279                                                       unsigned Depth) const {
10280   unsigned BitWidth = KnownOne.getBitWidth();
10281   KnownZero = KnownOne = APInt(BitWidth, 0);
10282   switch (Op.getOpcode()) {
10283   default: break;
10284   case ARMISD::ADDC:
10285   case ARMISD::ADDE:
10286   case ARMISD::SUBC:
10287   case ARMISD::SUBE:
10288     // These nodes' second result is a boolean
10289     if (Op.getResNo() == 0)
10290       break;
10291     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10292     break;
10293   case ARMISD::CMOV: {
10294     // Bits are known zero/one if known on the LHS and RHS.
10295     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10296     if (KnownZero == 0 && KnownOne == 0) return;
10297
10298     APInt KnownZeroRHS, KnownOneRHS;
10299     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10300     KnownZero &= KnownZeroRHS;
10301     KnownOne  &= KnownOneRHS;
10302     return;
10303   }
10304   case ISD::INTRINSIC_W_CHAIN: {
10305     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10306     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10307     switch (IntID) {
10308     default: return;
10309     case Intrinsic::arm_ldaex:
10310     case Intrinsic::arm_ldrex: {
10311       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10312       unsigned MemBits = VT.getScalarType().getSizeInBits();
10313       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10314       return;
10315     }
10316     }
10317   }
10318   }
10319 }
10320
10321 //===----------------------------------------------------------------------===//
10322 //                           ARM Inline Assembly Support
10323 //===----------------------------------------------------------------------===//
10324
10325 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10326   // Looking for "rev" which is V6+.
10327   if (!Subtarget->hasV6Ops())
10328     return false;
10329
10330   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10331   std::string AsmStr = IA->getAsmString();
10332   SmallVector<StringRef, 4> AsmPieces;
10333   SplitString(AsmStr, AsmPieces, ";\n");
10334
10335   switch (AsmPieces.size()) {
10336   default: return false;
10337   case 1:
10338     AsmStr = AsmPieces[0];
10339     AsmPieces.clear();
10340     SplitString(AsmStr, AsmPieces, " \t,");
10341
10342     // rev $0, $1
10343     if (AsmPieces.size() == 3 &&
10344         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10345         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10346       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10347       if (Ty && Ty->getBitWidth() == 32)
10348         return IntrinsicLowering::LowerToByteSwap(CI);
10349     }
10350     break;
10351   }
10352
10353   return false;
10354 }
10355
10356 /// getConstraintType - Given a constraint letter, return the type of
10357 /// constraint it is for this target.
10358 ARMTargetLowering::ConstraintType
10359 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10360   if (Constraint.size() == 1) {
10361     switch (Constraint[0]) {
10362     default:  break;
10363     case 'l': return C_RegisterClass;
10364     case 'w': return C_RegisterClass;
10365     case 'h': return C_RegisterClass;
10366     case 'x': return C_RegisterClass;
10367     case 't': return C_RegisterClass;
10368     case 'j': return C_Other; // Constant for movw.
10369       // An address with a single base register. Due to the way we
10370       // currently handle addresses it is the same as an 'r' memory constraint.
10371     case 'Q': return C_Memory;
10372     }
10373   } else if (Constraint.size() == 2) {
10374     switch (Constraint[0]) {
10375     default: break;
10376     // All 'U+' constraints are addresses.
10377     case 'U': return C_Memory;
10378     }
10379   }
10380   return TargetLowering::getConstraintType(Constraint);
10381 }
10382
10383 /// Examine constraint type and operand type and determine a weight value.
10384 /// This object must already have been set up with the operand type
10385 /// and the current alternative constraint selected.
10386 TargetLowering::ConstraintWeight
10387 ARMTargetLowering::getSingleConstraintMatchWeight(
10388     AsmOperandInfo &info, const char *constraint) const {
10389   ConstraintWeight weight = CW_Invalid;
10390   Value *CallOperandVal = info.CallOperandVal;
10391     // If we don't have a value, we can't do a match,
10392     // but allow it at the lowest weight.
10393   if (!CallOperandVal)
10394     return CW_Default;
10395   Type *type = CallOperandVal->getType();
10396   // Look at the constraint type.
10397   switch (*constraint) {
10398   default:
10399     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10400     break;
10401   case 'l':
10402     if (type->isIntegerTy()) {
10403       if (Subtarget->isThumb())
10404         weight = CW_SpecificReg;
10405       else
10406         weight = CW_Register;
10407     }
10408     break;
10409   case 'w':
10410     if (type->isFloatingPointTy())
10411       weight = CW_Register;
10412     break;
10413   }
10414   return weight;
10415 }
10416
10417 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10418 RCPair
10419 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10420                                                 MVT VT) const {
10421   if (Constraint.size() == 1) {
10422     // GCC ARM Constraint Letters
10423     switch (Constraint[0]) {
10424     case 'l': // Low regs or general regs.
10425       if (Subtarget->isThumb())
10426         return RCPair(0U, &ARM::tGPRRegClass);
10427       return RCPair(0U, &ARM::GPRRegClass);
10428     case 'h': // High regs or no regs.
10429       if (Subtarget->isThumb())
10430         return RCPair(0U, &ARM::hGPRRegClass);
10431       break;
10432     case 'r':
10433       return RCPair(0U, &ARM::GPRRegClass);
10434     case 'w':
10435       if (VT == MVT::Other)
10436         break;
10437       if (VT == MVT::f32)
10438         return RCPair(0U, &ARM::SPRRegClass);
10439       if (VT.getSizeInBits() == 64)
10440         return RCPair(0U, &ARM::DPRRegClass);
10441       if (VT.getSizeInBits() == 128)
10442         return RCPair(0U, &ARM::QPRRegClass);
10443       break;
10444     case 'x':
10445       if (VT == MVT::Other)
10446         break;
10447       if (VT == MVT::f32)
10448         return RCPair(0U, &ARM::SPR_8RegClass);
10449       if (VT.getSizeInBits() == 64)
10450         return RCPair(0U, &ARM::DPR_8RegClass);
10451       if (VT.getSizeInBits() == 128)
10452         return RCPair(0U, &ARM::QPR_8RegClass);
10453       break;
10454     case 't':
10455       if (VT == MVT::f32)
10456         return RCPair(0U, &ARM::SPRRegClass);
10457       break;
10458     }
10459   }
10460   if (StringRef("{cc}").equals_lower(Constraint))
10461     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10462
10463   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10464 }
10465
10466 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10467 /// vector.  If it is invalid, don't add anything to Ops.
10468 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10469                                                      std::string &Constraint,
10470                                                      std::vector<SDValue>&Ops,
10471                                                      SelectionDAG &DAG) const {
10472   SDValue Result;
10473
10474   // Currently only support length 1 constraints.
10475   if (Constraint.length() != 1) return;
10476
10477   char ConstraintLetter = Constraint[0];
10478   switch (ConstraintLetter) {
10479   default: break;
10480   case 'j':
10481   case 'I': case 'J': case 'K': case 'L':
10482   case 'M': case 'N': case 'O':
10483     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10484     if (!C)
10485       return;
10486
10487     int64_t CVal64 = C->getSExtValue();
10488     int CVal = (int) CVal64;
10489     // None of these constraints allow values larger than 32 bits.  Check
10490     // that the value fits in an int.
10491     if (CVal != CVal64)
10492       return;
10493
10494     switch (ConstraintLetter) {
10495       case 'j':
10496         // Constant suitable for movw, must be between 0 and
10497         // 65535.
10498         if (Subtarget->hasV6T2Ops())
10499           if (CVal >= 0 && CVal <= 65535)
10500             break;
10501         return;
10502       case 'I':
10503         if (Subtarget->isThumb1Only()) {
10504           // This must be a constant between 0 and 255, for ADD
10505           // immediates.
10506           if (CVal >= 0 && CVal <= 255)
10507             break;
10508         } else if (Subtarget->isThumb2()) {
10509           // A constant that can be used as an immediate value in a
10510           // data-processing instruction.
10511           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10512             break;
10513         } else {
10514           // A constant that can be used as an immediate value in a
10515           // data-processing instruction.
10516           if (ARM_AM::getSOImmVal(CVal) != -1)
10517             break;
10518         }
10519         return;
10520
10521       case 'J':
10522         if (Subtarget->isThumb()) {  // FIXME thumb2
10523           // This must be a constant between -255 and -1, for negated ADD
10524           // immediates. This can be used in GCC with an "n" modifier that
10525           // prints the negated value, for use with SUB instructions. It is
10526           // not useful otherwise but is implemented for compatibility.
10527           if (CVal >= -255 && CVal <= -1)
10528             break;
10529         } else {
10530           // This must be a constant between -4095 and 4095. It is not clear
10531           // what this constraint is intended for. Implemented for
10532           // compatibility with GCC.
10533           if (CVal >= -4095 && CVal <= 4095)
10534             break;
10535         }
10536         return;
10537
10538       case 'K':
10539         if (Subtarget->isThumb1Only()) {
10540           // A 32-bit value where only one byte has a nonzero value. Exclude
10541           // zero to match GCC. This constraint is used by GCC internally for
10542           // constants that can be loaded with a move/shift combination.
10543           // It is not useful otherwise but is implemented for compatibility.
10544           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10545             break;
10546         } else if (Subtarget->isThumb2()) {
10547           // A constant whose bitwise inverse can be used as an immediate
10548           // value in a data-processing instruction. This can be used in GCC
10549           // with a "B" modifier that prints the inverted value, for use with
10550           // BIC and MVN instructions. It is not useful otherwise but is
10551           // implemented for compatibility.
10552           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10553             break;
10554         } else {
10555           // A constant whose bitwise inverse can be used as an immediate
10556           // value in a data-processing instruction. This can be used in GCC
10557           // with a "B" modifier that prints the inverted value, for use with
10558           // BIC and MVN instructions. It is not useful otherwise but is
10559           // implemented for compatibility.
10560           if (ARM_AM::getSOImmVal(~CVal) != -1)
10561             break;
10562         }
10563         return;
10564
10565       case 'L':
10566         if (Subtarget->isThumb1Only()) {
10567           // This must be a constant between -7 and 7,
10568           // for 3-operand ADD/SUB immediate instructions.
10569           if (CVal >= -7 && CVal < 7)
10570             break;
10571         } else if (Subtarget->isThumb2()) {
10572           // A constant whose negation can be used as an immediate value in a
10573           // data-processing instruction. This can be used in GCC with an "n"
10574           // modifier that prints the negated value, for use with SUB
10575           // instructions. It is not useful otherwise but is implemented for
10576           // compatibility.
10577           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10578             break;
10579         } else {
10580           // A constant whose negation can be used as an immediate value in a
10581           // data-processing instruction. This can be used in GCC with an "n"
10582           // modifier that prints the negated value, for use with SUB
10583           // instructions. It is not useful otherwise but is implemented for
10584           // compatibility.
10585           if (ARM_AM::getSOImmVal(-CVal) != -1)
10586             break;
10587         }
10588         return;
10589
10590       case 'M':
10591         if (Subtarget->isThumb()) { // FIXME thumb2
10592           // This must be a multiple of 4 between 0 and 1020, for
10593           // ADD sp + immediate.
10594           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10595             break;
10596         } else {
10597           // A power of two or a constant between 0 and 32.  This is used in
10598           // GCC for the shift amount on shifted register operands, but it is
10599           // useful in general for any shift amounts.
10600           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10601             break;
10602         }
10603         return;
10604
10605       case 'N':
10606         if (Subtarget->isThumb()) {  // FIXME thumb2
10607           // This must be a constant between 0 and 31, for shift amounts.
10608           if (CVal >= 0 && CVal <= 31)
10609             break;
10610         }
10611         return;
10612
10613       case 'O':
10614         if (Subtarget->isThumb()) {  // FIXME thumb2
10615           // This must be a multiple of 4 between -508 and 508, for
10616           // ADD/SUB sp = sp + immediate.
10617           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10618             break;
10619         }
10620         return;
10621     }
10622     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10623     break;
10624   }
10625
10626   if (Result.getNode()) {
10627     Ops.push_back(Result);
10628     return;
10629   }
10630   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10631 }
10632
10633 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10634   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10635   unsigned Opcode = Op->getOpcode();
10636   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10637          "Invalid opcode for Div/Rem lowering");
10638   bool isSigned = (Opcode == ISD::SDIVREM);
10639   EVT VT = Op->getValueType(0);
10640   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10641
10642   RTLIB::Libcall LC;
10643   switch (VT.getSimpleVT().SimpleTy) {
10644   default: llvm_unreachable("Unexpected request for libcall!");
10645   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10646   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10647   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10648   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10649   }
10650
10651   SDValue InChain = DAG.getEntryNode();
10652
10653   TargetLowering::ArgListTy Args;
10654   TargetLowering::ArgListEntry Entry;
10655   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10656     EVT ArgVT = Op->getOperand(i).getValueType();
10657     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10658     Entry.Node = Op->getOperand(i);
10659     Entry.Ty = ArgTy;
10660     Entry.isSExt = isSigned;
10661     Entry.isZExt = !isSigned;
10662     Args.push_back(Entry);
10663   }
10664
10665   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10666                                          getPointerTy());
10667
10668   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10669
10670   SDLoc dl(Op);
10671   TargetLowering::CallLoweringInfo CLI(DAG);
10672   CLI.setDebugLoc(dl).setChain(InChain)
10673     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10674     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10675
10676   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10677   return CallInfo.first;
10678 }
10679
10680 SDValue
10681 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10682   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10683   SDLoc DL(Op);
10684
10685   // Get the inputs.
10686   SDValue Chain = Op.getOperand(0);
10687   SDValue Size  = Op.getOperand(1);
10688
10689   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10690                               DAG.getConstant(2, MVT::i32));
10691
10692   SDValue Flag;
10693   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10694   Flag = Chain.getValue(1);
10695
10696   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10697   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10698
10699   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10700   Chain = NewSP.getValue(1);
10701
10702   SDValue Ops[2] = { NewSP, Chain };
10703   return DAG.getMergeValues(Ops, DL);
10704 }
10705
10706 bool
10707 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10708   // The ARM target isn't yet aware of offsets.
10709   return false;
10710 }
10711
10712 bool ARM::isBitFieldInvertedMask(unsigned v) {
10713   if (v == 0xffffffff)
10714     return false;
10715
10716   // there can be 1's on either or both "outsides", all the "inside"
10717   // bits must be 0's
10718   unsigned TO = CountTrailingOnes_32(v);
10719   unsigned LO = CountLeadingOnes_32(v);
10720   v = (v >> TO) << TO;
10721   v = (v << LO) >> LO;
10722   return v == 0;
10723 }
10724
10725 /// isFPImmLegal - Returns true if the target can instruction select the
10726 /// specified FP immediate natively. If false, the legalizer will
10727 /// materialize the FP immediate as a load from a constant pool.
10728 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10729   if (!Subtarget->hasVFP3())
10730     return false;
10731   if (VT == MVT::f32)
10732     return ARM_AM::getFP32Imm(Imm) != -1;
10733   if (VT == MVT::f64)
10734     return ARM_AM::getFP64Imm(Imm) != -1;
10735   return false;
10736 }
10737
10738 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10739 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10740 /// specified in the intrinsic calls.
10741 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10742                                            const CallInst &I,
10743                                            unsigned Intrinsic) const {
10744   switch (Intrinsic) {
10745   case Intrinsic::arm_neon_vld1:
10746   case Intrinsic::arm_neon_vld2:
10747   case Intrinsic::arm_neon_vld3:
10748   case Intrinsic::arm_neon_vld4:
10749   case Intrinsic::arm_neon_vld2lane:
10750   case Intrinsic::arm_neon_vld3lane:
10751   case Intrinsic::arm_neon_vld4lane: {
10752     Info.opc = ISD::INTRINSIC_W_CHAIN;
10753     // Conservatively set memVT to the entire set of vectors loaded.
10754     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10755     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10756     Info.ptrVal = I.getArgOperand(0);
10757     Info.offset = 0;
10758     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10759     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10760     Info.vol = false; // volatile loads with NEON intrinsics not supported
10761     Info.readMem = true;
10762     Info.writeMem = false;
10763     return true;
10764   }
10765   case Intrinsic::arm_neon_vst1:
10766   case Intrinsic::arm_neon_vst2:
10767   case Intrinsic::arm_neon_vst3:
10768   case Intrinsic::arm_neon_vst4:
10769   case Intrinsic::arm_neon_vst2lane:
10770   case Intrinsic::arm_neon_vst3lane:
10771   case Intrinsic::arm_neon_vst4lane: {
10772     Info.opc = ISD::INTRINSIC_VOID;
10773     // Conservatively set memVT to the entire set of vectors stored.
10774     unsigned NumElts = 0;
10775     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10776       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10777       if (!ArgTy->isVectorTy())
10778         break;
10779       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10780     }
10781     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10782     Info.ptrVal = I.getArgOperand(0);
10783     Info.offset = 0;
10784     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10785     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10786     Info.vol = false; // volatile stores with NEON intrinsics not supported
10787     Info.readMem = false;
10788     Info.writeMem = true;
10789     return true;
10790   }
10791   case Intrinsic::arm_ldaex:
10792   case Intrinsic::arm_ldrex: {
10793     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10794     Info.opc = ISD::INTRINSIC_W_CHAIN;
10795     Info.memVT = MVT::getVT(PtrTy->getElementType());
10796     Info.ptrVal = I.getArgOperand(0);
10797     Info.offset = 0;
10798     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10799     Info.vol = true;
10800     Info.readMem = true;
10801     Info.writeMem = false;
10802     return true;
10803   }
10804   case Intrinsic::arm_stlex:
10805   case Intrinsic::arm_strex: {
10806     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10807     Info.opc = ISD::INTRINSIC_W_CHAIN;
10808     Info.memVT = MVT::getVT(PtrTy->getElementType());
10809     Info.ptrVal = I.getArgOperand(1);
10810     Info.offset = 0;
10811     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10812     Info.vol = true;
10813     Info.readMem = false;
10814     Info.writeMem = true;
10815     return true;
10816   }
10817   case Intrinsic::arm_stlexd:
10818   case Intrinsic::arm_strexd: {
10819     Info.opc = ISD::INTRINSIC_W_CHAIN;
10820     Info.memVT = MVT::i64;
10821     Info.ptrVal = I.getArgOperand(2);
10822     Info.offset = 0;
10823     Info.align = 8;
10824     Info.vol = true;
10825     Info.readMem = false;
10826     Info.writeMem = true;
10827     return true;
10828   }
10829   case Intrinsic::arm_ldaexd:
10830   case Intrinsic::arm_ldrexd: {
10831     Info.opc = ISD::INTRINSIC_W_CHAIN;
10832     Info.memVT = MVT::i64;
10833     Info.ptrVal = I.getArgOperand(0);
10834     Info.offset = 0;
10835     Info.align = 8;
10836     Info.vol = true;
10837     Info.readMem = true;
10838     Info.writeMem = false;
10839     return true;
10840   }
10841   default:
10842     break;
10843   }
10844
10845   return false;
10846 }
10847
10848 /// \brief Returns true if it is beneficial to convert a load of a constant
10849 /// to just the constant itself.
10850 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10851                                                           Type *Ty) const {
10852   assert(Ty->isIntegerTy());
10853
10854   unsigned Bits = Ty->getPrimitiveSizeInBits();
10855   if (Bits == 0 || Bits > 32)
10856     return false;
10857   return true;
10858 }
10859
10860 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10861   // Loads and stores less than 64-bits are already atomic; ones above that
10862   // are doomed anyway, so defer to the default libcall and blame the OS when
10863   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10864   // anything for those.
10865   bool IsMClass = Subtarget->isMClass();
10866   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10867     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10868     return Size == 64 && !IsMClass;
10869   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10870     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10871   }
10872
10873   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10874   // and up to 64 bits on the non-M profiles
10875   unsigned AtomicLimit = IsMClass ? 32 : 64;
10876   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10877 }
10878
10879 // This has so far only been implemented for MachO.
10880 bool ARMTargetLowering::useLoadStackGuardNode() const {
10881   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10882 }
10883
10884 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10885                                          AtomicOrdering Ord) const {
10886   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10887   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10888   bool IsAcquire = isAtLeastAcquire(Ord);
10889
10890   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10891   // intrinsic must return {i32, i32} and we have to recombine them into a
10892   // single i64 here.
10893   if (ValTy->getPrimitiveSizeInBits() == 64) {
10894     Intrinsic::ID Int =
10895         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10896     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10897
10898     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10899     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10900
10901     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10902     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10903     if (!Subtarget->isLittle())
10904       std::swap (Lo, Hi);
10905     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10906     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10907     return Builder.CreateOr(
10908         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10909   }
10910
10911   Type *Tys[] = { Addr->getType() };
10912   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10913   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10914
10915   return Builder.CreateTruncOrBitCast(
10916       Builder.CreateCall(Ldrex, Addr),
10917       cast<PointerType>(Addr->getType())->getElementType());
10918 }
10919
10920 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10921                                                Value *Addr,
10922                                                AtomicOrdering Ord) const {
10923   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10924   bool IsRelease = isAtLeastRelease(Ord);
10925
10926   // Since the intrinsics must have legal type, the i64 intrinsics take two
10927   // parameters: "i32, i32". We must marshal Val into the appropriate form
10928   // before the call.
10929   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10930     Intrinsic::ID Int =
10931         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10932     Function *Strex = Intrinsic::getDeclaration(M, Int);
10933     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10934
10935     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10936     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10937     if (!Subtarget->isLittle())
10938       std::swap (Lo, Hi);
10939     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10940     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10941   }
10942
10943   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10944   Type *Tys[] = { Addr->getType() };
10945   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10946
10947   return Builder.CreateCall2(
10948       Strex, Builder.CreateZExtOrBitCast(
10949                  Val, Strex->getFunctionType()->getParamType(0)),
10950       Addr);
10951 }
10952
10953 enum HABaseType {
10954   HA_UNKNOWN = 0,
10955   HA_FLOAT,
10956   HA_DOUBLE,
10957   HA_VECT64,
10958   HA_VECT128
10959 };
10960
10961 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10962                                    uint64_t &Members) {
10963   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10964     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10965       uint64_t SubMembers = 0;
10966       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10967         return false;
10968       Members += SubMembers;
10969     }
10970   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10971     uint64_t SubMembers = 0;
10972     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10973       return false;
10974     Members += SubMembers * AT->getNumElements();
10975   } else if (Ty->isFloatTy()) {
10976     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10977       return false;
10978     Members = 1;
10979     Base = HA_FLOAT;
10980   } else if (Ty->isDoubleTy()) {
10981     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10982       return false;
10983     Members = 1;
10984     Base = HA_DOUBLE;
10985   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10986     Members = 1;
10987     switch (Base) {
10988     case HA_FLOAT:
10989     case HA_DOUBLE:
10990       return false;
10991     case HA_VECT64:
10992       return VT->getBitWidth() == 64;
10993     case HA_VECT128:
10994       return VT->getBitWidth() == 128;
10995     case HA_UNKNOWN:
10996       switch (VT->getBitWidth()) {
10997       case 64:
10998         Base = HA_VECT64;
10999         return true;
11000       case 128:
11001         Base = HA_VECT128;
11002         return true;
11003       default:
11004         return false;
11005       }
11006     }
11007   }
11008
11009   return (Members > 0 && Members <= 4);
11010 }
11011
11012 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11013 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11014     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11015   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11016       CallingConv::ARM_AAPCS_VFP)
11017     return false;
11018
11019   HABaseType Base = HA_UNKNOWN;
11020   uint64_t Members = 0;
11021   bool result = isHomogeneousAggregate(Ty, Base, Members);
11022   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11023   return result;
11024 }