ARM / x86_64 varargs: Don't save regparms in prologue without va_start
[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     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
449   }
450
451   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
452        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
453     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
454          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
455       setTruncStoreAction((MVT::SimpleValueType)VT,
456                           (MVT::SimpleValueType)InnerVT, Expand);
457     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
458     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
459     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
460
461     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
462     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
463     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
464     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
465
466     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
467   }
468
469   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
470   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
471
472   if (Subtarget->hasNEON()) {
473     addDRTypeForNEON(MVT::v2f32);
474     addDRTypeForNEON(MVT::v8i8);
475     addDRTypeForNEON(MVT::v4i16);
476     addDRTypeForNEON(MVT::v2i32);
477     addDRTypeForNEON(MVT::v1i64);
478
479     addQRTypeForNEON(MVT::v4f32);
480     addQRTypeForNEON(MVT::v2f64);
481     addQRTypeForNEON(MVT::v16i8);
482     addQRTypeForNEON(MVT::v8i16);
483     addQRTypeForNEON(MVT::v4i32);
484     addQRTypeForNEON(MVT::v2i64);
485
486     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
487     // neither Neon nor VFP support any arithmetic operations on it.
488     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
489     // supported for v4f32.
490     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
492     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
493     // FIXME: Code duplication: FDIV and FREM are expanded always, see
494     // ARMTargetLowering::addTypeForNEON method for details.
495     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
496     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
497     // FIXME: Create unittest.
498     // In another words, find a way when "copysign" appears in DAG with vector
499     // operands.
500     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
501     // FIXME: Code duplication: SETCC has custom operation action, see
502     // ARMTargetLowering::addTypeForNEON method for details.
503     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FNEG and for FABS.
505     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
506     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
507     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
509     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
510     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
511     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
512     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
513     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
514     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
515     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
516     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
517     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
518     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
519     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
520     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
521     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
522     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
523     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
524
525     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
527     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
528     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
529     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
530     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
531     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
532     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
533     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
534     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
535     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
536     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
537     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
538     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
539     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
540
541     // Mark v2f32 intrinsics.
542     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
544     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
545     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
546     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
547     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
548     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
549     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
550     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
551     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
552     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
553     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
554     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
555     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
556     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
557
558     // Neon does not support some operations on v1i64 and v2i64 types.
559     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
560     // Custom handling for some quad-vector types to detect VMULL.
561     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
562     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
563     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
564     // Custom handling for some vector types to avoid expensive expansions
565     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
566     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
567     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
568     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
569     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
570     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
571     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
572     // a destination type that is wider than the source, and nor does
573     // it have a FP_TO_[SU]INT instruction with a narrower destination than
574     // source.
575     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
576     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
577     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
578     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
579
580     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
581     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
582
583     // NEON does not have single instruction CTPOP for vectors with element
584     // types wider than 8-bits.  However, custom lowering can leverage the
585     // v8i8/v16i8 vcnt instruction.
586     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
587     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
588     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
589     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
590
591     // NEON only has FMA instructions as of VFP4.
592     if (!Subtarget->hasVFP4()) {
593       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
594       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
595     }
596
597     setTargetDAGCombine(ISD::INTRINSIC_VOID);
598     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
599     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
600     setTargetDAGCombine(ISD::SHL);
601     setTargetDAGCombine(ISD::SRL);
602     setTargetDAGCombine(ISD::SRA);
603     setTargetDAGCombine(ISD::SIGN_EXTEND);
604     setTargetDAGCombine(ISD::ZERO_EXTEND);
605     setTargetDAGCombine(ISD::ANY_EXTEND);
606     setTargetDAGCombine(ISD::SELECT_CC);
607     setTargetDAGCombine(ISD::BUILD_VECTOR);
608     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
609     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
610     setTargetDAGCombine(ISD::STORE);
611     setTargetDAGCombine(ISD::FP_TO_SINT);
612     setTargetDAGCombine(ISD::FP_TO_UINT);
613     setTargetDAGCombine(ISD::FDIV);
614
615     // It is legal to extload from v4i8 to v4i16 or v4i32.
616     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
617                   MVT::v4i16, MVT::v2i16,
618                   MVT::v2i32};
619     for (unsigned i = 0; i < 6; ++i) {
620       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
621       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
622       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
623     }
624   }
625
626   // ARM and Thumb2 support UMLAL/SMLAL.
627   if (!Subtarget->isThumb1Only())
628     setTargetDAGCombine(ISD::ADDC);
629
630   if (Subtarget->isFPOnlySP()) {
631     // When targetting a floating-point unit with only single-precision
632     // operations, f64 is legal for the few double-precision instructions which
633     // are present However, no double-precision operations other than moves,
634     // loads and stores are provided by the hardware.
635     setOperationAction(ISD::FADD,       MVT::f64, Expand);
636     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
637     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
638     setOperationAction(ISD::FMA,        MVT::f64, Expand);
639     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
640     setOperationAction(ISD::FREM,       MVT::f64, Expand);
641     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
642     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
643     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
644     setOperationAction(ISD::FABS,       MVT::f64, Expand);
645     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
646     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
647     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
648     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
649     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
650     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
651     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
652     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
653     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
654     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
655     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
656     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
657     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
658     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
659     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
660     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
661     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
662   }
663
664   computeRegisterProperties();
665
666   // ARM does not have floating-point extending loads.
667   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
668   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
669
670   // ... or truncating stores
671   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
672   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
673   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
674
675   // ARM does not have i1 sign extending load.
676   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
677
678   // ARM supports all 4 flavors of integer indexed load / store.
679   if (!Subtarget->isThumb1Only()) {
680     for (unsigned im = (unsigned)ISD::PRE_INC;
681          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
682       setIndexedLoadAction(im,  MVT::i1,  Legal);
683       setIndexedLoadAction(im,  MVT::i8,  Legal);
684       setIndexedLoadAction(im,  MVT::i16, Legal);
685       setIndexedLoadAction(im,  MVT::i32, Legal);
686       setIndexedStoreAction(im, MVT::i1,  Legal);
687       setIndexedStoreAction(im, MVT::i8,  Legal);
688       setIndexedStoreAction(im, MVT::i16, Legal);
689       setIndexedStoreAction(im, MVT::i32, Legal);
690     }
691   }
692
693   setOperationAction(ISD::SADDO, MVT::i32, Custom);
694   setOperationAction(ISD::UADDO, MVT::i32, Custom);
695   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
696   setOperationAction(ISD::USUBO, MVT::i32, Custom);
697
698   // i64 operation support.
699   setOperationAction(ISD::MUL,     MVT::i64, Expand);
700   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
701   if (Subtarget->isThumb1Only()) {
702     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
703     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
704   }
705   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
706       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
707     setOperationAction(ISD::MULHS, MVT::i32, Expand);
708
709   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
710   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
711   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
712   setOperationAction(ISD::SRL,       MVT::i64, Custom);
713   setOperationAction(ISD::SRA,       MVT::i64, Custom);
714
715   if (!Subtarget->isThumb1Only()) {
716     // FIXME: We should do this for Thumb1 as well.
717     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
718     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
719     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
720     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
721   }
722
723   // ARM does not have ROTL.
724   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
725   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
726   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
727   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
728     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
729
730   // These just redirect to CTTZ and CTLZ on ARM.
731   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
732   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
733
734   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
735
736   // Only ARMv6 has BSWAP.
737   if (!Subtarget->hasV6Ops())
738     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
739
740   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
741       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
742     // These are expanded into libcalls if the cpu doesn't have HW divider.
743     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
744     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
745   }
746
747   // FIXME: Also set divmod for SREM on EABI
748   setOperationAction(ISD::SREM, MVT::i32, Expand);
749   setOperationAction(ISD::UREM, MVT::i32, Expand);
750   if (!Subtarget->isTargetAEABI()) {
751     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
752     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
753   }
754
755   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
756   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
757   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
758   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
759   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
760
761   setOperationAction(ISD::TRAP, MVT::Other, Legal);
762
763   // Use the default implementation.
764   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
765   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
766   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
767   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
768   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
769   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
770
771   if (!Subtarget->isTargetMachO()) {
772     // Non-MachO platforms may return values in these registers via the
773     // personality function.
774     setExceptionPointerRegister(ARM::R0);
775     setExceptionSelectorRegister(ARM::R1);
776   }
777
778   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
779     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
780   else
781     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
782
783   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
784   // the default expansion. If we are targeting a single threaded system,
785   // then set them all for expand so we can lower them later into their
786   // non-atomic form.
787   if (TM.Options.ThreadModel == ThreadModel::Single)
788     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
789   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
790     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
791     // to ldrex/strex loops already.
792     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
793
794     // On v8, we have particularly efficient implementations of atomic fences
795     // if they can be combined with nearby atomic loads and stores.
796     if (!Subtarget->hasV8Ops()) {
797       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
798       setInsertFencesForAtomic(true);
799     }
800   } else {
801     // If there's anything we can use as a barrier, go through custom lowering
802     // for ATOMIC_FENCE.
803     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
804                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
805
806     // Set them all for expansion, which will force libcalls.
807     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
808     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
809     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
810     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
811     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
812     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
813     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
814     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
815     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
816     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
817     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
818     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
819     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
820     // Unordered/Monotonic case.
821     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
822     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
823   }
824
825   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
826
827   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
828   if (!Subtarget->hasV6Ops()) {
829     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
830     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
831   }
832   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
833
834   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
835       !Subtarget->isThumb1Only()) {
836     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
837     // iff target supports vfp2.
838     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
839     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
840   }
841
842   // We want to custom lower some of our intrinsics.
843   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
844   if (Subtarget->isTargetDarwin()) {
845     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
846     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
847     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
848   }
849
850   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
851   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
852   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
853   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
854   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
855   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
856   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
857   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
858   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
859
860   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
861   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
862   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
863   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
864   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
865
866   // We don't support sin/cos/fmod/copysign/pow
867   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
868   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
869   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
870   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
871   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
872   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
873   setOperationAction(ISD::FREM,      MVT::f64, Expand);
874   setOperationAction(ISD::FREM,      MVT::f32, Expand);
875   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
876       !Subtarget->isThumb1Only()) {
877     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
878     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
879   }
880   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
881   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
882
883   if (!Subtarget->hasVFP4()) {
884     setOperationAction(ISD::FMA, MVT::f64, Expand);
885     setOperationAction(ISD::FMA, MVT::f32, Expand);
886   }
887
888   // Various VFP goodness
889   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
890     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
891     if (Subtarget->hasVFP2()) {
892       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
893       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
894       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
895       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
896     }
897
898     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
899     if (!Subtarget->hasV8Ops()) {
900       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
901       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
902     }
903
904     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
905     if (!Subtarget->hasFP16()) {
906       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
907       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
908     }
909   }
910
911   // Combine sin / cos into one node or libcall if possible.
912   if (Subtarget->hasSinCos()) {
913     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
914     setLibcallName(RTLIB::SINCOS_F64, "sincos");
915     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
916       // For iOS, we don't want to the normal expansion of a libcall to
917       // sincos. We want to issue a libcall to __sincos_stret.
918       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
919       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
920     }
921   }
922
923   // ARMv8 implements a lot of rounding-like FP operations.
924   if (Subtarget->hasV8Ops()) {
925     static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
926     for (const auto Ty : RoundingTypes) {
927       setOperationAction(ISD::FFLOOR, Ty, Legal);
928       setOperationAction(ISD::FCEIL, Ty, Legal);
929       setOperationAction(ISD::FROUND, Ty, Legal);
930       setOperationAction(ISD::FTRUNC, Ty, Legal);
931       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
932       setOperationAction(ISD::FRINT, Ty, Legal);
933     }
934   }
935   // We have target-specific dag combine patterns for the following nodes:
936   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
937   setTargetDAGCombine(ISD::ADD);
938   setTargetDAGCombine(ISD::SUB);
939   setTargetDAGCombine(ISD::MUL);
940   setTargetDAGCombine(ISD::AND);
941   setTargetDAGCombine(ISD::OR);
942   setTargetDAGCombine(ISD::XOR);
943
944   if (Subtarget->hasV6Ops())
945     setTargetDAGCombine(ISD::SRL);
946
947   setStackPointerRegisterToSaveRestore(ARM::SP);
948
949   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
950       !Subtarget->hasVFP2())
951     setSchedulingPreference(Sched::RegPressure);
952   else
953     setSchedulingPreference(Sched::Hybrid);
954
955   //// temporary - rewrite interface to use type
956   MaxStoresPerMemset = 8;
957   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
958   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
959   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
960   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
961   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
962
963   // On ARM arguments smaller than 4 bytes are extended, so all arguments
964   // are at least 4 bytes aligned.
965   setMinStackArgumentAlignment(4);
966
967   // Prefer likely predicted branches to selects on out-of-order cores.
968   PredictableSelectIsExpensive = Subtarget->isLikeA9();
969
970   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
971 }
972
973 // FIXME: It might make sense to define the representative register class as the
974 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
975 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
976 // SPR's representative would be DPR_VFP2. This should work well if register
977 // pressure tracking were modified such that a register use would increment the
978 // pressure of the register class's representative and all of it's super
979 // classes' representatives transitively. We have not implemented this because
980 // of the difficulty prior to coalescing of modeling operand register classes
981 // due to the common occurrence of cross class copies and subregister insertions
982 // and extractions.
983 std::pair<const TargetRegisterClass*, uint8_t>
984 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
985   const TargetRegisterClass *RRC = nullptr;
986   uint8_t Cost = 1;
987   switch (VT.SimpleTy) {
988   default:
989     return TargetLowering::findRepresentativeClass(VT);
990   // Use DPR as representative register class for all floating point
991   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
992   // the cost is 1 for both f32 and f64.
993   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
994   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
995     RRC = &ARM::DPRRegClass;
996     // When NEON is used for SP, only half of the register file is available
997     // because operations that define both SP and DP results will be constrained
998     // to the VFP2 class (D0-D15). We currently model this constraint prior to
999     // coalescing by double-counting the SP regs. See the FIXME above.
1000     if (Subtarget->useNEONForSinglePrecisionFP())
1001       Cost = 2;
1002     break;
1003   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1004   case MVT::v4f32: case MVT::v2f64:
1005     RRC = &ARM::DPRRegClass;
1006     Cost = 2;
1007     break;
1008   case MVT::v4i64:
1009     RRC = &ARM::DPRRegClass;
1010     Cost = 4;
1011     break;
1012   case MVT::v8i64:
1013     RRC = &ARM::DPRRegClass;
1014     Cost = 8;
1015     break;
1016   }
1017   return std::make_pair(RRC, Cost);
1018 }
1019
1020 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1021   switch (Opcode) {
1022   default: return nullptr;
1023   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1024   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1025   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1026   case ARMISD::CALL:          return "ARMISD::CALL";
1027   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1028   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1029   case ARMISD::tCALL:         return "ARMISD::tCALL";
1030   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1031   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1032   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1033   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1034   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1035   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1036   case ARMISD::CMP:           return "ARMISD::CMP";
1037   case ARMISD::CMN:           return "ARMISD::CMN";
1038   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1039   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1040   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1041   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1042   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1043
1044   case ARMISD::CMOV:          return "ARMISD::CMOV";
1045
1046   case ARMISD::RBIT:          return "ARMISD::RBIT";
1047
1048   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1049   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1050   case ARMISD::SITOF:         return "ARMISD::SITOF";
1051   case ARMISD::UITOF:         return "ARMISD::UITOF";
1052
1053   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1054   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1055   case ARMISD::RRX:           return "ARMISD::RRX";
1056
1057   case ARMISD::ADDC:          return "ARMISD::ADDC";
1058   case ARMISD::ADDE:          return "ARMISD::ADDE";
1059   case ARMISD::SUBC:          return "ARMISD::SUBC";
1060   case ARMISD::SUBE:          return "ARMISD::SUBE";
1061
1062   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1063   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1064
1065   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1066   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1067
1068   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1069
1070   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1071
1072   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1073
1074   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1075
1076   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1077
1078   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1079
1080   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1081   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1082   case ARMISD::VCGE:          return "ARMISD::VCGE";
1083   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1084   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1085   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1086   case ARMISD::VCGT:          return "ARMISD::VCGT";
1087   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1088   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1089   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1090   case ARMISD::VTST:          return "ARMISD::VTST";
1091
1092   case ARMISD::VSHL:          return "ARMISD::VSHL";
1093   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1094   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1095   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1096   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1097   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1098   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1099   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1100   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1101   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1102   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1103   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1104   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1105   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1106   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1107   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1108   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1109   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1110   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1111   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1112   case ARMISD::VDUP:          return "ARMISD::VDUP";
1113   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1114   case ARMISD::VEXT:          return "ARMISD::VEXT";
1115   case ARMISD::VREV64:        return "ARMISD::VREV64";
1116   case ARMISD::VREV32:        return "ARMISD::VREV32";
1117   case ARMISD::VREV16:        return "ARMISD::VREV16";
1118   case ARMISD::VZIP:          return "ARMISD::VZIP";
1119   case ARMISD::VUZP:          return "ARMISD::VUZP";
1120   case ARMISD::VTRN:          return "ARMISD::VTRN";
1121   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1122   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1123   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1124   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1125   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1126   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1127   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1128   case ARMISD::FMAX:          return "ARMISD::FMAX";
1129   case ARMISD::FMIN:          return "ARMISD::FMIN";
1130   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1131   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1132   case ARMISD::BFI:           return "ARMISD::BFI";
1133   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1134   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1135   case ARMISD::VBSL:          return "ARMISD::VBSL";
1136   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1137   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1138   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1139   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1140   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1141   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1142   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1143   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1144   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1145   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1146   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1147   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1148   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1149   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1150   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1151   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1152   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1153   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1154   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1155   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1156   }
1157 }
1158
1159 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1160   if (!VT.isVector()) return getPointerTy();
1161   return VT.changeVectorElementTypeToInteger();
1162 }
1163
1164 /// getRegClassFor - Return the register class that should be used for the
1165 /// specified value type.
1166 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1167   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1168   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1169   // load / store 4 to 8 consecutive D registers.
1170   if (Subtarget->hasNEON()) {
1171     if (VT == MVT::v4i64)
1172       return &ARM::QQPRRegClass;
1173     if (VT == MVT::v8i64)
1174       return &ARM::QQQQPRRegClass;
1175   }
1176   return TargetLowering::getRegClassFor(VT);
1177 }
1178
1179 // Create a fast isel object.
1180 FastISel *
1181 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1182                                   const TargetLibraryInfo *libInfo) const {
1183   return ARM::createFastISel(funcInfo, libInfo);
1184 }
1185
1186 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1187 /// be used for loads / stores from the global.
1188 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1189   return (Subtarget->isThumb1Only() ? 127 : 4095);
1190 }
1191
1192 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1193   unsigned NumVals = N->getNumValues();
1194   if (!NumVals)
1195     return Sched::RegPressure;
1196
1197   for (unsigned i = 0; i != NumVals; ++i) {
1198     EVT VT = N->getValueType(i);
1199     if (VT == MVT::Glue || VT == MVT::Other)
1200       continue;
1201     if (VT.isFloatingPoint() || VT.isVector())
1202       return Sched::ILP;
1203   }
1204
1205   if (!N->isMachineOpcode())
1206     return Sched::RegPressure;
1207
1208   // Load are scheduled for latency even if there instruction itinerary
1209   // is not available.
1210   const TargetInstrInfo *TII =
1211       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1212   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1213
1214   if (MCID.getNumDefs() == 0)
1215     return Sched::RegPressure;
1216   if (!Itins->isEmpty() &&
1217       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1218     return Sched::ILP;
1219
1220   return Sched::RegPressure;
1221 }
1222
1223 //===----------------------------------------------------------------------===//
1224 // Lowering Code
1225 //===----------------------------------------------------------------------===//
1226
1227 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1228 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1229   switch (CC) {
1230   default: llvm_unreachable("Unknown condition code!");
1231   case ISD::SETNE:  return ARMCC::NE;
1232   case ISD::SETEQ:  return ARMCC::EQ;
1233   case ISD::SETGT:  return ARMCC::GT;
1234   case ISD::SETGE:  return ARMCC::GE;
1235   case ISD::SETLT:  return ARMCC::LT;
1236   case ISD::SETLE:  return ARMCC::LE;
1237   case ISD::SETUGT: return ARMCC::HI;
1238   case ISD::SETUGE: return ARMCC::HS;
1239   case ISD::SETULT: return ARMCC::LO;
1240   case ISD::SETULE: return ARMCC::LS;
1241   }
1242 }
1243
1244 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1245 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1246                         ARMCC::CondCodes &CondCode2) {
1247   CondCode2 = ARMCC::AL;
1248   switch (CC) {
1249   default: llvm_unreachable("Unknown FP condition!");
1250   case ISD::SETEQ:
1251   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1252   case ISD::SETGT:
1253   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1254   case ISD::SETGE:
1255   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1256   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1257   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1258   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1259   case ISD::SETO:   CondCode = ARMCC::VC; break;
1260   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1261   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1262   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1263   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1264   case ISD::SETLT:
1265   case ISD::SETULT: CondCode = ARMCC::LT; break;
1266   case ISD::SETLE:
1267   case ISD::SETULE: CondCode = ARMCC::LE; break;
1268   case ISD::SETNE:
1269   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1270   }
1271 }
1272
1273 //===----------------------------------------------------------------------===//
1274 //                      Calling Convention Implementation
1275 //===----------------------------------------------------------------------===//
1276
1277 #include "ARMGenCallingConv.inc"
1278
1279 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1280 /// account presence of floating point hardware and calling convention
1281 /// limitations, such as support for variadic functions.
1282 CallingConv::ID
1283 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1284                                            bool isVarArg) const {
1285   switch (CC) {
1286   default:
1287     llvm_unreachable("Unsupported calling convention");
1288   case CallingConv::ARM_AAPCS:
1289   case CallingConv::ARM_APCS:
1290   case CallingConv::GHC:
1291     return CC;
1292   case CallingConv::ARM_AAPCS_VFP:
1293     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1294   case CallingConv::C:
1295     if (!Subtarget->isAAPCS_ABI())
1296       return CallingConv::ARM_APCS;
1297     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1298              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1299              !isVarArg)
1300       return CallingConv::ARM_AAPCS_VFP;
1301     else
1302       return CallingConv::ARM_AAPCS;
1303   case CallingConv::Fast:
1304     if (!Subtarget->isAAPCS_ABI()) {
1305       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1306         return CallingConv::Fast;
1307       return CallingConv::ARM_APCS;
1308     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1309       return CallingConv::ARM_AAPCS_VFP;
1310     else
1311       return CallingConv::ARM_AAPCS;
1312   }
1313 }
1314
1315 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1316 /// CallingConvention.
1317 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1318                                                  bool Return,
1319                                                  bool isVarArg) const {
1320   switch (getEffectiveCallingConv(CC, isVarArg)) {
1321   default:
1322     llvm_unreachable("Unsupported calling convention");
1323   case CallingConv::ARM_APCS:
1324     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1325   case CallingConv::ARM_AAPCS:
1326     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1327   case CallingConv::ARM_AAPCS_VFP:
1328     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1329   case CallingConv::Fast:
1330     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1331   case CallingConv::GHC:
1332     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1333   }
1334 }
1335
1336 /// LowerCallResult - Lower the result values of a call into the
1337 /// appropriate copies out of appropriate physical registers.
1338 SDValue
1339 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1340                                    CallingConv::ID CallConv, bool isVarArg,
1341                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1342                                    SDLoc dl, SelectionDAG &DAG,
1343                                    SmallVectorImpl<SDValue> &InVals,
1344                                    bool isThisReturn, SDValue ThisVal) const {
1345
1346   // Assign locations to each value returned by this call.
1347   SmallVector<CCValAssign, 16> RVLocs;
1348   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1349                     *DAG.getContext(), Call);
1350   CCInfo.AnalyzeCallResult(Ins,
1351                            CCAssignFnForNode(CallConv, /* Return*/ true,
1352                                              isVarArg));
1353
1354   // Copy all of the result registers out of their specified physreg.
1355   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356     CCValAssign VA = RVLocs[i];
1357
1358     // Pass 'this' value directly from the argument to return value, to avoid
1359     // reg unit interference
1360     if (i == 0 && isThisReturn) {
1361       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1362              "unexpected return calling convention register assignment");
1363       InVals.push_back(ThisVal);
1364       continue;
1365     }
1366
1367     SDValue Val;
1368     if (VA.needsCustom()) {
1369       // Handle f64 or half of a v2f64.
1370       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1371                                       InFlag);
1372       Chain = Lo.getValue(1);
1373       InFlag = Lo.getValue(2);
1374       VA = RVLocs[++i]; // skip ahead to next loc
1375       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1376                                       InFlag);
1377       Chain = Hi.getValue(1);
1378       InFlag = Hi.getValue(2);
1379       if (!Subtarget->isLittle())
1380         std::swap (Lo, Hi);
1381       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1382
1383       if (VA.getLocVT() == MVT::v2f64) {
1384         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1385         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386                           DAG.getConstant(0, MVT::i32));
1387
1388         VA = RVLocs[++i]; // skip ahead to next loc
1389         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1390         Chain = Lo.getValue(1);
1391         InFlag = Lo.getValue(2);
1392         VA = RVLocs[++i]; // skip ahead to next loc
1393         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1394         Chain = Hi.getValue(1);
1395         InFlag = Hi.getValue(2);
1396         if (!Subtarget->isLittle())
1397           std::swap (Lo, Hi);
1398         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1399         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1400                           DAG.getConstant(1, MVT::i32));
1401       }
1402     } else {
1403       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1404                                InFlag);
1405       Chain = Val.getValue(1);
1406       InFlag = Val.getValue(2);
1407     }
1408
1409     switch (VA.getLocInfo()) {
1410     default: llvm_unreachable("Unknown loc info!");
1411     case CCValAssign::Full: break;
1412     case CCValAssign::BCvt:
1413       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1414       break;
1415     }
1416
1417     InVals.push_back(Val);
1418   }
1419
1420   return Chain;
1421 }
1422
1423 /// LowerMemOpCallTo - Store the argument to the stack.
1424 SDValue
1425 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1426                                     SDValue StackPtr, SDValue Arg,
1427                                     SDLoc dl, SelectionDAG &DAG,
1428                                     const CCValAssign &VA,
1429                                     ISD::ArgFlagsTy Flags) const {
1430   unsigned LocMemOffset = VA.getLocMemOffset();
1431   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1432   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1433   return DAG.getStore(Chain, dl, Arg, PtrOff,
1434                       MachinePointerInfo::getStack(LocMemOffset),
1435                       false, false, 0);
1436 }
1437
1438 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1439                                          SDValue Chain, SDValue &Arg,
1440                                          RegsToPassVector &RegsToPass,
1441                                          CCValAssign &VA, CCValAssign &NextVA,
1442                                          SDValue &StackPtr,
1443                                          SmallVectorImpl<SDValue> &MemOpChains,
1444                                          ISD::ArgFlagsTy Flags) const {
1445
1446   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1447                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1448   unsigned id = Subtarget->isLittle() ? 0 : 1;
1449   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1450
1451   if (NextVA.isRegLoc())
1452     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1453   else {
1454     assert(NextVA.isMemLoc());
1455     if (!StackPtr.getNode())
1456       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1457
1458     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1459                                            dl, DAG, NextVA,
1460                                            Flags));
1461   }
1462 }
1463
1464 /// LowerCall - Lowering a call into a callseq_start <-
1465 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1466 /// nodes.
1467 SDValue
1468 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1469                              SmallVectorImpl<SDValue> &InVals) const {
1470   SelectionDAG &DAG                     = CLI.DAG;
1471   SDLoc &dl                          = CLI.DL;
1472   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1473   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1474   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1475   SDValue Chain                         = CLI.Chain;
1476   SDValue Callee                        = CLI.Callee;
1477   bool &isTailCall                      = CLI.IsTailCall;
1478   CallingConv::ID CallConv              = CLI.CallConv;
1479   bool doesNotRet                       = CLI.DoesNotReturn;
1480   bool isVarArg                         = CLI.IsVarArg;
1481
1482   MachineFunction &MF = DAG.getMachineFunction();
1483   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1484   bool isThisReturn   = false;
1485   bool isSibCall      = false;
1486
1487   // Disable tail calls if they're not supported.
1488   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1489     isTailCall = false;
1490
1491   if (isTailCall) {
1492     // Check if it's really possible to do a tail call.
1493     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1494                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1495                                                    Outs, OutVals, Ins, DAG);
1496     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1497       report_fatal_error("failed to perform tail call elimination on a call "
1498                          "site marked musttail");
1499     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1500     // detected sibcalls.
1501     if (isTailCall) {
1502       ++NumTailCalls;
1503       isSibCall = true;
1504     }
1505   }
1506
1507   // Analyze operands of the call, assigning locations to each operand.
1508   SmallVector<CCValAssign, 16> ArgLocs;
1509   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1510                     *DAG.getContext(), Call);
1511   CCInfo.AnalyzeCallOperands(Outs,
1512                              CCAssignFnForNode(CallConv, /* Return*/ false,
1513                                                isVarArg));
1514
1515   // Get a count of how many bytes are to be pushed on the stack.
1516   unsigned NumBytes = CCInfo.getNextStackOffset();
1517
1518   // For tail calls, memory operands are available in our caller's stack.
1519   if (isSibCall)
1520     NumBytes = 0;
1521
1522   // Adjust the stack pointer for the new arguments...
1523   // These operations are automatically eliminated by the prolog/epilog pass
1524   if (!isSibCall)
1525     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1526                                  dl);
1527
1528   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1529
1530   RegsToPassVector RegsToPass;
1531   SmallVector<SDValue, 8> MemOpChains;
1532
1533   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1534   // of tail call optimization, arguments are handled later.
1535   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1536        i != e;
1537        ++i, ++realArgIdx) {
1538     CCValAssign &VA = ArgLocs[i];
1539     SDValue Arg = OutVals[realArgIdx];
1540     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1541     bool isByVal = Flags.isByVal();
1542
1543     // Promote the value if needed.
1544     switch (VA.getLocInfo()) {
1545     default: llvm_unreachable("Unknown loc info!");
1546     case CCValAssign::Full: break;
1547     case CCValAssign::SExt:
1548       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1549       break;
1550     case CCValAssign::ZExt:
1551       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1552       break;
1553     case CCValAssign::AExt:
1554       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1555       break;
1556     case CCValAssign::BCvt:
1557       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1558       break;
1559     }
1560
1561     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1562     if (VA.needsCustom()) {
1563       if (VA.getLocVT() == MVT::v2f64) {
1564         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1565                                   DAG.getConstant(0, MVT::i32));
1566         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1567                                   DAG.getConstant(1, MVT::i32));
1568
1569         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1570                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1571
1572         VA = ArgLocs[++i]; // skip ahead to next loc
1573         if (VA.isRegLoc()) {
1574           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1575                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1576         } else {
1577           assert(VA.isMemLoc());
1578
1579           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1580                                                  dl, DAG, VA, Flags));
1581         }
1582       } else {
1583         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1584                          StackPtr, MemOpChains, Flags);
1585       }
1586     } else if (VA.isRegLoc()) {
1587       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1588         assert(VA.getLocVT() == MVT::i32 &&
1589                "unexpected calling convention register assignment");
1590         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1591                "unexpected use of 'returned'");
1592         isThisReturn = true;
1593       }
1594       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1595     } else if (isByVal) {
1596       assert(VA.isMemLoc());
1597       unsigned offset = 0;
1598
1599       // True if this byval aggregate will be split between registers
1600       // and memory.
1601       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1602       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1603
1604       if (CurByValIdx < ByValArgsCount) {
1605
1606         unsigned RegBegin, RegEnd;
1607         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1608
1609         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1610         unsigned int i, j;
1611         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1612           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1613           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1614           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1615                                      MachinePointerInfo(),
1616                                      false, false, false,
1617                                      DAG.InferPtrAlignment(AddArg));
1618           MemOpChains.push_back(Load.getValue(1));
1619           RegsToPass.push_back(std::make_pair(j, Load));
1620         }
1621
1622         // If parameter size outsides register area, "offset" value
1623         // helps us to calculate stack slot for remained part properly.
1624         offset = RegEnd - RegBegin;
1625
1626         CCInfo.nextInRegsParam();
1627       }
1628
1629       if (Flags.getByValSize() > 4*offset) {
1630         unsigned LocMemOffset = VA.getLocMemOffset();
1631         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1632         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1633                                   StkPtrOff);
1634         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1635         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1636         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1637                                            MVT::i32);
1638         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1639
1640         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1641         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1642         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1643                                           Ops));
1644       }
1645     } else if (!isSibCall) {
1646       assert(VA.isMemLoc());
1647
1648       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1649                                              dl, DAG, VA, Flags));
1650     }
1651   }
1652
1653   if (!MemOpChains.empty())
1654     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1655
1656   // Build a sequence of copy-to-reg nodes chained together with token chain
1657   // and flag operands which copy the outgoing args into the appropriate regs.
1658   SDValue InFlag;
1659   // Tail call byval lowering might overwrite argument registers so in case of
1660   // tail call optimization the copies to registers are lowered later.
1661   if (!isTailCall)
1662     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1663       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1664                                RegsToPass[i].second, InFlag);
1665       InFlag = Chain.getValue(1);
1666     }
1667
1668   // For tail calls lower the arguments to the 'real' stack slot.
1669   if (isTailCall) {
1670     // Force all the incoming stack arguments to be loaded from the stack
1671     // before any new outgoing arguments are stored to the stack, because the
1672     // outgoing stack slots may alias the incoming argument stack slots, and
1673     // the alias isn't otherwise explicit. This is slightly more conservative
1674     // than necessary, because it means that each store effectively depends
1675     // on every argument instead of just those arguments it would clobber.
1676
1677     // Do not flag preceding copytoreg stuff together with the following stuff.
1678     InFlag = SDValue();
1679     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1680       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1681                                RegsToPass[i].second, InFlag);
1682       InFlag = Chain.getValue(1);
1683     }
1684     InFlag = SDValue();
1685   }
1686
1687   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1688   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1689   // node so that legalize doesn't hack it.
1690   bool isDirect = false;
1691   bool isARMFunc = false;
1692   bool isLocalARMFunc = false;
1693   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1694
1695   if (EnableARMLongCalls) {
1696     assert((Subtarget->isTargetWindows() ||
1697             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1698            "long-calls with non-static relocation model!");
1699     // Handle a global address or an external symbol. If it's not one of
1700     // those, the target's already in a register, so we don't need to do
1701     // anything extra.
1702     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1703       const GlobalValue *GV = G->getGlobal();
1704       // Create a constant pool entry for the callee address
1705       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1706       ARMConstantPoolValue *CPV =
1707         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1708
1709       // Get the address of the callee into a register
1710       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1711       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1712       Callee = DAG.getLoad(getPointerTy(), dl,
1713                            DAG.getEntryNode(), CPAddr,
1714                            MachinePointerInfo::getConstantPool(),
1715                            false, false, false, 0);
1716     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1717       const char *Sym = S->getSymbol();
1718
1719       // Create a constant pool entry for the callee address
1720       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1721       ARMConstantPoolValue *CPV =
1722         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1723                                       ARMPCLabelIndex, 0);
1724       // Get the address of the callee into a register
1725       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1726       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1727       Callee = DAG.getLoad(getPointerTy(), dl,
1728                            DAG.getEntryNode(), CPAddr,
1729                            MachinePointerInfo::getConstantPool(),
1730                            false, false, false, 0);
1731     }
1732   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1733     const GlobalValue *GV = G->getGlobal();
1734     isDirect = true;
1735     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1736     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1737                    getTargetMachine().getRelocationModel() != Reloc::Static;
1738     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1739     // ARM call to a local ARM function is predicable.
1740     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1741     // tBX takes a register source operand.
1742     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1743       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1744       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1745                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1746                                                       0, ARMII::MO_NONLAZY));
1747       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1748                            MachinePointerInfo::getGOT(), false, false, true, 0);
1749     } else if (Subtarget->isTargetCOFF()) {
1750       assert(Subtarget->isTargetWindows() &&
1751              "Windows is the only supported COFF target");
1752       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1753                                  ? ARMII::MO_DLLIMPORT
1754                                  : ARMII::MO_NO_FLAG;
1755       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1756                                           TargetFlags);
1757       if (GV->hasDLLImportStorageClass())
1758         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1759                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1760                                          Callee), MachinePointerInfo::getGOT(),
1761                              false, false, false, 0);
1762     } else {
1763       // On ELF targets for PIC code, direct calls should go through the PLT
1764       unsigned OpFlags = 0;
1765       if (Subtarget->isTargetELF() &&
1766           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1767         OpFlags = ARMII::MO_PLT;
1768       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1769     }
1770   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1771     isDirect = true;
1772     bool isStub = Subtarget->isTargetMachO() &&
1773                   getTargetMachine().getRelocationModel() != Reloc::Static;
1774     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1775     // tBX takes a register source operand.
1776     const char *Sym = S->getSymbol();
1777     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1778       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1779       ARMConstantPoolValue *CPV =
1780         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1781                                       ARMPCLabelIndex, 4);
1782       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1783       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1784       Callee = DAG.getLoad(getPointerTy(), dl,
1785                            DAG.getEntryNode(), CPAddr,
1786                            MachinePointerInfo::getConstantPool(),
1787                            false, false, false, 0);
1788       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1789       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1790                            getPointerTy(), Callee, PICLabel);
1791     } else {
1792       unsigned OpFlags = 0;
1793       // On ELF targets for PIC code, direct calls should go through the PLT
1794       if (Subtarget->isTargetELF() &&
1795                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1796         OpFlags = ARMII::MO_PLT;
1797       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1798     }
1799   }
1800
1801   // FIXME: handle tail calls differently.
1802   unsigned CallOpc;
1803   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1804       AttributeSet::FunctionIndex, Attribute::MinSize);
1805   if (Subtarget->isThumb()) {
1806     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1807       CallOpc = ARMISD::CALL_NOLINK;
1808     else
1809       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1810   } else {
1811     if (!isDirect && !Subtarget->hasV5TOps())
1812       CallOpc = ARMISD::CALL_NOLINK;
1813     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1814                // Emit regular call when code size is the priority
1815                !HasMinSizeAttr)
1816       // "mov lr, pc; b _foo" to avoid confusing the RSP
1817       CallOpc = ARMISD::CALL_NOLINK;
1818     else
1819       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1820   }
1821
1822   std::vector<SDValue> Ops;
1823   Ops.push_back(Chain);
1824   Ops.push_back(Callee);
1825
1826   // Add argument registers to the end of the list so that they are known live
1827   // into the call.
1828   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1829     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1830                                   RegsToPass[i].second.getValueType()));
1831
1832   // Add a register mask operand representing the call-preserved registers.
1833   if (!isTailCall) {
1834     const uint32_t *Mask;
1835     const TargetRegisterInfo *TRI =
1836         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1837     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1838     if (isThisReturn) {
1839       // For 'this' returns, use the R0-preserving mask if applicable
1840       Mask = ARI->getThisReturnPreservedMask(CallConv);
1841       if (!Mask) {
1842         // Set isThisReturn to false if the calling convention is not one that
1843         // allows 'returned' to be modeled in this way, so LowerCallResult does
1844         // not try to pass 'this' straight through
1845         isThisReturn = false;
1846         Mask = ARI->getCallPreservedMask(CallConv);
1847       }
1848     } else
1849       Mask = ARI->getCallPreservedMask(CallConv);
1850
1851     assert(Mask && "Missing call preserved mask for calling convention");
1852     Ops.push_back(DAG.getRegisterMask(Mask));
1853   }
1854
1855   if (InFlag.getNode())
1856     Ops.push_back(InFlag);
1857
1858   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1859   if (isTailCall)
1860     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1861
1862   // Returns a chain and a flag for retval copy to use.
1863   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1864   InFlag = Chain.getValue(1);
1865
1866   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1867                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1868   if (!Ins.empty())
1869     InFlag = Chain.getValue(1);
1870
1871   // Handle result values, copying them out of physregs into vregs that we
1872   // return.
1873   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1874                          InVals, isThisReturn,
1875                          isThisReturn ? OutVals[0] : SDValue());
1876 }
1877
1878 /// HandleByVal - Every parameter *after* a byval parameter is passed
1879 /// on the stack.  Remember the next parameter register to allocate,
1880 /// and then confiscate the rest of the parameter registers to insure
1881 /// this.
1882 void
1883 ARMTargetLowering::HandleByVal(
1884     CCState *State, unsigned &size, unsigned Align) const {
1885   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1886   assert((State->getCallOrPrologue() == Prologue ||
1887           State->getCallOrPrologue() == Call) &&
1888          "unhandled ParmContext");
1889
1890   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1891     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1892       unsigned AlignInRegs = Align / 4;
1893       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1894       for (unsigned i = 0; i < Waste; ++i)
1895         reg = State->AllocateReg(GPRArgRegs, 4);
1896     }
1897     if (reg != 0) {
1898       unsigned excess = 4 * (ARM::R4 - reg);
1899
1900       // Special case when NSAA != SP and parameter size greater than size of
1901       // all remained GPR regs. In that case we can't split parameter, we must
1902       // send it to stack. We also must set NCRN to R4, so waste all
1903       // remained registers.
1904       const unsigned NSAAOffset = State->getNextStackOffset();
1905       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1906         while (State->AllocateReg(GPRArgRegs, 4))
1907           ;
1908         return;
1909       }
1910
1911       // First register for byval parameter is the first register that wasn't
1912       // allocated before this method call, so it would be "reg".
1913       // If parameter is small enough to be saved in range [reg, r4), then
1914       // the end (first after last) register would be reg + param-size-in-regs,
1915       // else parameter would be splitted between registers and stack,
1916       // end register would be r4 in this case.
1917       unsigned ByValRegBegin = reg;
1918       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1919       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1920       // Note, first register is allocated in the beginning of function already,
1921       // allocate remained amount of registers we need.
1922       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1923         State->AllocateReg(GPRArgRegs, 4);
1924       // A byval parameter that is split between registers and memory needs its
1925       // size truncated here.
1926       // In the case where the entire structure fits in registers, we set the
1927       // size in memory to zero.
1928       if (size < excess)
1929         size = 0;
1930       else
1931         size -= excess;
1932     }
1933   }
1934 }
1935
1936 /// MatchingStackOffset - Return true if the given stack call argument is
1937 /// already available in the same position (relatively) of the caller's
1938 /// incoming argument stack.
1939 static
1940 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1941                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1942                          const TargetInstrInfo *TII) {
1943   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1944   int FI = INT_MAX;
1945   if (Arg.getOpcode() == ISD::CopyFromReg) {
1946     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1947     if (!TargetRegisterInfo::isVirtualRegister(VR))
1948       return false;
1949     MachineInstr *Def = MRI->getVRegDef(VR);
1950     if (!Def)
1951       return false;
1952     if (!Flags.isByVal()) {
1953       if (!TII->isLoadFromStackSlot(Def, FI))
1954         return false;
1955     } else {
1956       return false;
1957     }
1958   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1959     if (Flags.isByVal())
1960       // ByVal argument is passed in as a pointer but it's now being
1961       // dereferenced. e.g.
1962       // define @foo(%struct.X* %A) {
1963       //   tail call @bar(%struct.X* byval %A)
1964       // }
1965       return false;
1966     SDValue Ptr = Ld->getBasePtr();
1967     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1968     if (!FINode)
1969       return false;
1970     FI = FINode->getIndex();
1971   } else
1972     return false;
1973
1974   assert(FI != INT_MAX);
1975   if (!MFI->isFixedObjectIndex(FI))
1976     return false;
1977   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1978 }
1979
1980 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1981 /// for tail call optimization. Targets which want to do tail call
1982 /// optimization should implement this function.
1983 bool
1984 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1985                                                      CallingConv::ID CalleeCC,
1986                                                      bool isVarArg,
1987                                                      bool isCalleeStructRet,
1988                                                      bool isCallerStructRet,
1989                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1990                                     const SmallVectorImpl<SDValue> &OutVals,
1991                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1992                                                      SelectionDAG& DAG) const {
1993   const Function *CallerF = DAG.getMachineFunction().getFunction();
1994   CallingConv::ID CallerCC = CallerF->getCallingConv();
1995   bool CCMatch = CallerCC == CalleeCC;
1996
1997   // Look for obvious safe cases to perform tail call optimization that do not
1998   // require ABI changes. This is what gcc calls sibcall.
1999
2000   // Do not sibcall optimize vararg calls unless the call site is not passing
2001   // any arguments.
2002   if (isVarArg && !Outs.empty())
2003     return false;
2004
2005   // Exception-handling functions need a special set of instructions to indicate
2006   // a return to the hardware. Tail-calling another function would probably
2007   // break this.
2008   if (CallerF->hasFnAttribute("interrupt"))
2009     return false;
2010
2011   // Also avoid sibcall optimization if either caller or callee uses struct
2012   // return semantics.
2013   if (isCalleeStructRet || isCallerStructRet)
2014     return false;
2015
2016   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2017   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2018   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2019   // support in the assembler and linker to be used. This would need to be
2020   // fixed to fully support tail calls in Thumb1.
2021   //
2022   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2023   // LR.  This means if we need to reload LR, it takes an extra instructions,
2024   // which outweighs the value of the tail call; but here we don't know yet
2025   // whether LR is going to be used.  Probably the right approach is to
2026   // generate the tail call here and turn it back into CALL/RET in
2027   // emitEpilogue if LR is used.
2028
2029   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2030   // but we need to make sure there are enough registers; the only valid
2031   // registers are the 4 used for parameters.  We don't currently do this
2032   // case.
2033   if (Subtarget->isThumb1Only())
2034     return false;
2035
2036   // Externally-defined functions with weak linkage should not be
2037   // tail-called on ARM when the OS does not support dynamic
2038   // pre-emption of symbols, as the AAELF spec requires normal calls
2039   // to undefined weak functions to be replaced with a NOP or jump to the
2040   // next instruction. The behaviour of branch instructions in this
2041   // situation (as used for tail calls) is implementation-defined, so we
2042   // cannot rely on the linker replacing the tail call with a return.
2043   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2044     const GlobalValue *GV = G->getGlobal();
2045     if (GV->hasExternalWeakLinkage())
2046       return false;
2047   }
2048
2049   // If the calling conventions do not match, then we'd better make sure the
2050   // results are returned in the same way as what the caller expects.
2051   if (!CCMatch) {
2052     SmallVector<CCValAssign, 16> RVLocs1;
2053     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2054                        *DAG.getContext(), Call);
2055     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2056
2057     SmallVector<CCValAssign, 16> RVLocs2;
2058     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2059                        *DAG.getContext(), Call);
2060     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2061
2062     if (RVLocs1.size() != RVLocs2.size())
2063       return false;
2064     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2065       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2066         return false;
2067       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2068         return false;
2069       if (RVLocs1[i].isRegLoc()) {
2070         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2071           return false;
2072       } else {
2073         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2074           return false;
2075       }
2076     }
2077   }
2078
2079   // If Caller's vararg or byval argument has been split between registers and
2080   // stack, do not perform tail call, since part of the argument is in caller's
2081   // local frame.
2082   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2083                                       getInfo<ARMFunctionInfo>();
2084   if (AFI_Caller->getArgRegsSaveSize())
2085     return false;
2086
2087   // If the callee takes no arguments then go on to check the results of the
2088   // call.
2089   if (!Outs.empty()) {
2090     // Check if stack adjustment is needed. For now, do not do this if any
2091     // argument is passed on the stack.
2092     SmallVector<CCValAssign, 16> ArgLocs;
2093     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2094                       *DAG.getContext(), Call);
2095     CCInfo.AnalyzeCallOperands(Outs,
2096                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2097     if (CCInfo.getNextStackOffset()) {
2098       MachineFunction &MF = DAG.getMachineFunction();
2099
2100       // Check if the arguments are already laid out in the right way as
2101       // the caller's fixed stack objects.
2102       MachineFrameInfo *MFI = MF.getFrameInfo();
2103       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2104       const TargetInstrInfo *TII =
2105           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2106       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2107            i != e;
2108            ++i, ++realArgIdx) {
2109         CCValAssign &VA = ArgLocs[i];
2110         EVT RegVT = VA.getLocVT();
2111         SDValue Arg = OutVals[realArgIdx];
2112         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2113         if (VA.getLocInfo() == CCValAssign::Indirect)
2114           return false;
2115         if (VA.needsCustom()) {
2116           // f64 and vector types are split into multiple registers or
2117           // register/stack-slot combinations.  The types will not match
2118           // the registers; give up on memory f64 refs until we figure
2119           // out what to do about this.
2120           if (!VA.isRegLoc())
2121             return false;
2122           if (!ArgLocs[++i].isRegLoc())
2123             return false;
2124           if (RegVT == MVT::v2f64) {
2125             if (!ArgLocs[++i].isRegLoc())
2126               return false;
2127             if (!ArgLocs[++i].isRegLoc())
2128               return false;
2129           }
2130         } else if (!VA.isRegLoc()) {
2131           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2132                                    MFI, MRI, TII))
2133             return false;
2134         }
2135       }
2136     }
2137   }
2138
2139   return true;
2140 }
2141
2142 bool
2143 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2144                                   MachineFunction &MF, bool isVarArg,
2145                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2146                                   LLVMContext &Context) const {
2147   SmallVector<CCValAssign, 16> RVLocs;
2148   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2149   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2150                                                     isVarArg));
2151 }
2152
2153 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2154                                     SDLoc DL, SelectionDAG &DAG) {
2155   const MachineFunction &MF = DAG.getMachineFunction();
2156   const Function *F = MF.getFunction();
2157
2158   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2159
2160   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2161   // version of the "preferred return address". These offsets affect the return
2162   // instruction if this is a return from PL1 without hypervisor extensions.
2163   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2164   //    SWI:     0      "subs pc, lr, #0"
2165   //    ABORT:   +4     "subs pc, lr, #4"
2166   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2167   // UNDEF varies depending on where the exception came from ARM or Thumb
2168   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2169
2170   int64_t LROffset;
2171   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2172       IntKind == "ABORT")
2173     LROffset = 4;
2174   else if (IntKind == "SWI" || IntKind == "UNDEF")
2175     LROffset = 0;
2176   else
2177     report_fatal_error("Unsupported interrupt attribute. If present, value "
2178                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2179
2180   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2181
2182   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2183 }
2184
2185 SDValue
2186 ARMTargetLowering::LowerReturn(SDValue Chain,
2187                                CallingConv::ID CallConv, bool isVarArg,
2188                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2189                                const SmallVectorImpl<SDValue> &OutVals,
2190                                SDLoc dl, SelectionDAG &DAG) const {
2191
2192   // CCValAssign - represent the assignment of the return value to a location.
2193   SmallVector<CCValAssign, 16> RVLocs;
2194
2195   // CCState - Info about the registers and stack slots.
2196   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2197                     *DAG.getContext(), Call);
2198
2199   // Analyze outgoing return values.
2200   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2201                                                isVarArg));
2202
2203   SDValue Flag;
2204   SmallVector<SDValue, 4> RetOps;
2205   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2206   bool isLittleEndian = Subtarget->isLittle();
2207
2208   MachineFunction &MF = DAG.getMachineFunction();
2209   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2210   AFI->setReturnRegsCount(RVLocs.size());
2211
2212   // Copy the result values into the output registers.
2213   for (unsigned i = 0, realRVLocIdx = 0;
2214        i != RVLocs.size();
2215        ++i, ++realRVLocIdx) {
2216     CCValAssign &VA = RVLocs[i];
2217     assert(VA.isRegLoc() && "Can only return in registers!");
2218
2219     SDValue Arg = OutVals[realRVLocIdx];
2220
2221     switch (VA.getLocInfo()) {
2222     default: llvm_unreachable("Unknown loc info!");
2223     case CCValAssign::Full: break;
2224     case CCValAssign::BCvt:
2225       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2226       break;
2227     }
2228
2229     if (VA.needsCustom()) {
2230       if (VA.getLocVT() == MVT::v2f64) {
2231         // Extract the first half and return it in two registers.
2232         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2233                                    DAG.getConstant(0, MVT::i32));
2234         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2235                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2236
2237         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2238                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2239                                  Flag);
2240         Flag = Chain.getValue(1);
2241         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2242         VA = RVLocs[++i]; // skip ahead to next loc
2243         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2245                                  Flag);
2246         Flag = Chain.getValue(1);
2247         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2248         VA = RVLocs[++i]; // skip ahead to next loc
2249
2250         // Extract the 2nd half and fall through to handle it as an f64 value.
2251         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2252                           DAG.getConstant(1, MVT::i32));
2253       }
2254       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2255       // available.
2256       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2257                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2258       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2259                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2260                                Flag);
2261       Flag = Chain.getValue(1);
2262       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2263       VA = RVLocs[++i]; // skip ahead to next loc
2264       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2265                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2266                                Flag);
2267     } else
2268       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2269
2270     // Guarantee that all emitted copies are
2271     // stuck together, avoiding something bad.
2272     Flag = Chain.getValue(1);
2273     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2274   }
2275
2276   // Update chain and glue.
2277   RetOps[0] = Chain;
2278   if (Flag.getNode())
2279     RetOps.push_back(Flag);
2280
2281   // CPUs which aren't M-class use a special sequence to return from
2282   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2283   // though we use "subs pc, lr, #N").
2284   //
2285   // M-class CPUs actually use a normal return sequence with a special
2286   // (hardware-provided) value in LR, so the normal code path works.
2287   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2288       !Subtarget->isMClass()) {
2289     if (Subtarget->isThumb1Only())
2290       report_fatal_error("interrupt attribute is not supported in Thumb1");
2291     return LowerInterruptReturn(RetOps, dl, DAG);
2292   }
2293
2294   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2295 }
2296
2297 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2298   if (N->getNumValues() != 1)
2299     return false;
2300   if (!N->hasNUsesOfValue(1, 0))
2301     return false;
2302
2303   SDValue TCChain = Chain;
2304   SDNode *Copy = *N->use_begin();
2305   if (Copy->getOpcode() == ISD::CopyToReg) {
2306     // If the copy has a glue operand, we conservatively assume it isn't safe to
2307     // perform a tail call.
2308     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2309       return false;
2310     TCChain = Copy->getOperand(0);
2311   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2312     SDNode *VMov = Copy;
2313     // f64 returned in a pair of GPRs.
2314     SmallPtrSet<SDNode*, 2> Copies;
2315     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2316          UI != UE; ++UI) {
2317       if (UI->getOpcode() != ISD::CopyToReg)
2318         return false;
2319       Copies.insert(*UI);
2320     }
2321     if (Copies.size() > 2)
2322       return false;
2323
2324     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2325          UI != UE; ++UI) {
2326       SDValue UseChain = UI->getOperand(0);
2327       if (Copies.count(UseChain.getNode()))
2328         // Second CopyToReg
2329         Copy = *UI;
2330       else
2331         // First CopyToReg
2332         TCChain = UseChain;
2333     }
2334   } else if (Copy->getOpcode() == ISD::BITCAST) {
2335     // f32 returned in a single GPR.
2336     if (!Copy->hasOneUse())
2337       return false;
2338     Copy = *Copy->use_begin();
2339     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2340       return false;
2341     TCChain = Copy->getOperand(0);
2342   } else {
2343     return false;
2344   }
2345
2346   bool HasRet = false;
2347   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2348        UI != UE; ++UI) {
2349     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2350         UI->getOpcode() != ARMISD::INTRET_FLAG)
2351       return false;
2352     HasRet = true;
2353   }
2354
2355   if (!HasRet)
2356     return false;
2357
2358   Chain = TCChain;
2359   return true;
2360 }
2361
2362 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2363   if (!Subtarget->supportsTailCall())
2364     return false;
2365
2366   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2367     return false;
2368
2369   return !Subtarget->isThumb1Only();
2370 }
2371
2372 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2373 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2374 // one of the above mentioned nodes. It has to be wrapped because otherwise
2375 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2376 // be used to form addressing mode. These wrapped nodes will be selected
2377 // into MOVi.
2378 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2379   EVT PtrVT = Op.getValueType();
2380   // FIXME there is no actual debug info here
2381   SDLoc dl(Op);
2382   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2383   SDValue Res;
2384   if (CP->isMachineConstantPoolEntry())
2385     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2386                                     CP->getAlignment());
2387   else
2388     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2389                                     CP->getAlignment());
2390   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2391 }
2392
2393 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2394   return MachineJumpTableInfo::EK_Inline;
2395 }
2396
2397 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2398                                              SelectionDAG &DAG) const {
2399   MachineFunction &MF = DAG.getMachineFunction();
2400   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2401   unsigned ARMPCLabelIndex = 0;
2402   SDLoc DL(Op);
2403   EVT PtrVT = getPointerTy();
2404   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2405   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2406   SDValue CPAddr;
2407   if (RelocM == Reloc::Static) {
2408     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2409   } else {
2410     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2411     ARMPCLabelIndex = AFI->createPICLabelUId();
2412     ARMConstantPoolValue *CPV =
2413       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2414                                       ARMCP::CPBlockAddress, PCAdj);
2415     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2416   }
2417   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2418   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2419                                MachinePointerInfo::getConstantPool(),
2420                                false, false, false, 0);
2421   if (RelocM == Reloc::Static)
2422     return Result;
2423   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2424   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2425 }
2426
2427 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2428 SDValue
2429 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2430                                                  SelectionDAG &DAG) const {
2431   SDLoc dl(GA);
2432   EVT PtrVT = getPointerTy();
2433   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2434   MachineFunction &MF = DAG.getMachineFunction();
2435   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2436   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2437   ARMConstantPoolValue *CPV =
2438     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2439                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2440   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2441   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2442   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2443                          MachinePointerInfo::getConstantPool(),
2444                          false, false, false, 0);
2445   SDValue Chain = Argument.getValue(1);
2446
2447   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2448   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2449
2450   // call __tls_get_addr.
2451   ArgListTy Args;
2452   ArgListEntry Entry;
2453   Entry.Node = Argument;
2454   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2455   Args.push_back(Entry);
2456
2457   // FIXME: is there useful debug info available here?
2458   TargetLowering::CallLoweringInfo CLI(DAG);
2459   CLI.setDebugLoc(dl).setChain(Chain)
2460     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2461                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2462                0);
2463
2464   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2465   return CallResult.first;
2466 }
2467
2468 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2469 // "local exec" model.
2470 SDValue
2471 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2472                                         SelectionDAG &DAG,
2473                                         TLSModel::Model model) const {
2474   const GlobalValue *GV = GA->getGlobal();
2475   SDLoc dl(GA);
2476   SDValue Offset;
2477   SDValue Chain = DAG.getEntryNode();
2478   EVT PtrVT = getPointerTy();
2479   // Get the Thread Pointer
2480   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2481
2482   if (model == TLSModel::InitialExec) {
2483     MachineFunction &MF = DAG.getMachineFunction();
2484     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2485     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2486     // Initial exec model.
2487     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2488     ARMConstantPoolValue *CPV =
2489       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2490                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2491                                       true);
2492     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2494     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2495                          MachinePointerInfo::getConstantPool(),
2496                          false, false, false, 0);
2497     Chain = Offset.getValue(1);
2498
2499     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2500     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2501
2502     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2503                          MachinePointerInfo::getConstantPool(),
2504                          false, false, false, 0);
2505   } else {
2506     // local exec model
2507     assert(model == TLSModel::LocalExec);
2508     ARMConstantPoolValue *CPV =
2509       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2510     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2511     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2512     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2513                          MachinePointerInfo::getConstantPool(),
2514                          false, false, false, 0);
2515   }
2516
2517   // The address of the thread local variable is the add of the thread
2518   // pointer with the offset of the variable.
2519   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2520 }
2521
2522 SDValue
2523 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2524   // TODO: implement the "local dynamic" model
2525   assert(Subtarget->isTargetELF() &&
2526          "TLS not implemented for non-ELF targets");
2527   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2528
2529   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2530
2531   switch (model) {
2532     case TLSModel::GeneralDynamic:
2533     case TLSModel::LocalDynamic:
2534       return LowerToTLSGeneralDynamicModel(GA, DAG);
2535     case TLSModel::InitialExec:
2536     case TLSModel::LocalExec:
2537       return LowerToTLSExecModels(GA, DAG, model);
2538   }
2539   llvm_unreachable("bogus TLS model");
2540 }
2541
2542 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2543                                                  SelectionDAG &DAG) const {
2544   EVT PtrVT = getPointerTy();
2545   SDLoc dl(Op);
2546   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2547   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2548     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2549     ARMConstantPoolValue *CPV =
2550       ARMConstantPoolConstant::Create(GV,
2551                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2552     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2553     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2554     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2555                                  CPAddr,
2556                                  MachinePointerInfo::getConstantPool(),
2557                                  false, false, false, 0);
2558     SDValue Chain = Result.getValue(1);
2559     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2560     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2561     if (!UseGOTOFF)
2562       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2563                            MachinePointerInfo::getGOT(),
2564                            false, false, false, 0);
2565     return Result;
2566   }
2567
2568   // If we have T2 ops, we can materialize the address directly via movt/movw
2569   // pair. This is always cheaper.
2570   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2571     ++NumMovwMovt;
2572     // FIXME: Once remat is capable of dealing with instructions with register
2573     // operands, expand this into two nodes.
2574     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2575                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2576   } else {
2577     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2578     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2579     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2580                        MachinePointerInfo::getConstantPool(),
2581                        false, false, false, 0);
2582   }
2583 }
2584
2585 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2586                                                     SelectionDAG &DAG) const {
2587   EVT PtrVT = getPointerTy();
2588   SDLoc dl(Op);
2589   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2590   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2591
2592   if (Subtarget->useMovt(DAG.getMachineFunction()))
2593     ++NumMovwMovt;
2594
2595   // FIXME: Once remat is capable of dealing with instructions with register
2596   // operands, expand this into multiple nodes
2597   unsigned Wrapper =
2598       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2599
2600   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2601   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2602
2603   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2604     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2605                          MachinePointerInfo::getGOT(), false, false, false, 0);
2606   return Result;
2607 }
2608
2609 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2610                                                      SelectionDAG &DAG) const {
2611   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2612   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2613          "Windows on ARM expects to use movw/movt");
2614
2615   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2616   const ARMII::TOF TargetFlags =
2617     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2618   EVT PtrVT = getPointerTy();
2619   SDValue Result;
2620   SDLoc DL(Op);
2621
2622   ++NumMovwMovt;
2623
2624   // FIXME: Once remat is capable of dealing with instructions with register
2625   // operands, expand this into two nodes.
2626   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2627                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2628                                                   TargetFlags));
2629   if (GV->hasDLLImportStorageClass())
2630     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2631                          MachinePointerInfo::getGOT(), false, false, false, 0);
2632   return Result;
2633 }
2634
2635 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2636                                                     SelectionDAG &DAG) const {
2637   assert(Subtarget->isTargetELF() &&
2638          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2639   MachineFunction &MF = DAG.getMachineFunction();
2640   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2641   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2642   EVT PtrVT = getPointerTy();
2643   SDLoc dl(Op);
2644   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2645   ARMConstantPoolValue *CPV =
2646     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2647                                   ARMPCLabelIndex, PCAdj);
2648   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2649   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2650   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2651                                MachinePointerInfo::getConstantPool(),
2652                                false, false, false, 0);
2653   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2654   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2655 }
2656
2657 SDValue
2658 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2659   SDLoc dl(Op);
2660   SDValue Val = DAG.getConstant(0, MVT::i32);
2661   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2662                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2663                      Op.getOperand(1), Val);
2664 }
2665
2666 SDValue
2667 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2668   SDLoc dl(Op);
2669   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2670                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2671 }
2672
2673 SDValue
2674 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2675                                           const ARMSubtarget *Subtarget) const {
2676   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2677   SDLoc dl(Op);
2678   switch (IntNo) {
2679   default: return SDValue();    // Don't custom lower most intrinsics.
2680   case Intrinsic::arm_rbit: {
2681     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2682            "RBIT intrinsic must have i32 type!");
2683     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2684   }
2685   case Intrinsic::arm_thread_pointer: {
2686     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2687     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2688   }
2689   case Intrinsic::eh_sjlj_lsda: {
2690     MachineFunction &MF = DAG.getMachineFunction();
2691     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2692     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2693     EVT PtrVT = getPointerTy();
2694     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2695     SDValue CPAddr;
2696     unsigned PCAdj = (RelocM != Reloc::PIC_)
2697       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2698     ARMConstantPoolValue *CPV =
2699       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2700                                       ARMCP::CPLSDA, PCAdj);
2701     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2702     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2703     SDValue Result =
2704       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2705                   MachinePointerInfo::getConstantPool(),
2706                   false, false, false, 0);
2707
2708     if (RelocM == Reloc::PIC_) {
2709       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2710       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2711     }
2712     return Result;
2713   }
2714   case Intrinsic::arm_neon_vmulls:
2715   case Intrinsic::arm_neon_vmullu: {
2716     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2717       ? ARMISD::VMULLs : ARMISD::VMULLu;
2718     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2719                        Op.getOperand(1), Op.getOperand(2));
2720   }
2721   }
2722 }
2723
2724 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2725                                  const ARMSubtarget *Subtarget) {
2726   // FIXME: handle "fence singlethread" more efficiently.
2727   SDLoc dl(Op);
2728   if (!Subtarget->hasDataBarrier()) {
2729     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2730     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2731     // here.
2732     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2733            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2734     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2735                        DAG.getConstant(0, MVT::i32));
2736   }
2737
2738   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2739   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2740   unsigned Domain = ARM_MB::ISH;
2741   if (Subtarget->isMClass()) {
2742     // Only a full system barrier exists in the M-class architectures.
2743     Domain = ARM_MB::SY;
2744   } else if (Subtarget->isSwift() && Ord == Release) {
2745     // Swift happens to implement ISHST barriers in a way that's compatible with
2746     // Release semantics but weaker than ISH so we'd be fools not to use
2747     // it. Beware: other processors probably don't!
2748     Domain = ARM_MB::ISHST;
2749   }
2750
2751   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2752                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2753                      DAG.getConstant(Domain, MVT::i32));
2754 }
2755
2756 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2757                              const ARMSubtarget *Subtarget) {
2758   // ARM pre v5TE and Thumb1 does not have preload instructions.
2759   if (!(Subtarget->isThumb2() ||
2760         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2761     // Just preserve the chain.
2762     return Op.getOperand(0);
2763
2764   SDLoc dl(Op);
2765   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2766   if (!isRead &&
2767       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2768     // ARMv7 with MP extension has PLDW.
2769     return Op.getOperand(0);
2770
2771   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2772   if (Subtarget->isThumb()) {
2773     // Invert the bits.
2774     isRead = ~isRead & 1;
2775     isData = ~isData & 1;
2776   }
2777
2778   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2779                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2780                      DAG.getConstant(isData, MVT::i32));
2781 }
2782
2783 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2784   MachineFunction &MF = DAG.getMachineFunction();
2785   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2786
2787   // vastart just stores the address of the VarArgsFrameIndex slot into the
2788   // memory location argument.
2789   SDLoc dl(Op);
2790   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2791   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2792   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2793   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2794                       MachinePointerInfo(SV), false, false, 0);
2795 }
2796
2797 SDValue
2798 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2799                                         SDValue &Root, SelectionDAG &DAG,
2800                                         SDLoc dl) const {
2801   MachineFunction &MF = DAG.getMachineFunction();
2802   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2803
2804   const TargetRegisterClass *RC;
2805   if (AFI->isThumb1OnlyFunction())
2806     RC = &ARM::tGPRRegClass;
2807   else
2808     RC = &ARM::GPRRegClass;
2809
2810   // Transform the arguments stored in physical registers into virtual ones.
2811   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2812   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2813
2814   SDValue ArgValue2;
2815   if (NextVA.isMemLoc()) {
2816     MachineFrameInfo *MFI = MF.getFrameInfo();
2817     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2818
2819     // Create load node to retrieve arguments from the stack.
2820     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2821     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2822                             MachinePointerInfo::getFixedStack(FI),
2823                             false, false, false, 0);
2824   } else {
2825     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2826     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2827   }
2828   if (!Subtarget->isLittle())
2829     std::swap (ArgValue, ArgValue2);
2830   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2831 }
2832
2833 void
2834 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2835                                   unsigned InRegsParamRecordIdx,
2836                                   unsigned ArgSize,
2837                                   unsigned &ArgRegsSize,
2838                                   unsigned &ArgRegsSaveSize)
2839   const {
2840   unsigned NumGPRs;
2841   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2842     unsigned RBegin, REnd;
2843     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2844     NumGPRs = REnd - RBegin;
2845   } else {
2846     unsigned int firstUnalloced;
2847     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2848                                                 sizeof(GPRArgRegs) /
2849                                                 sizeof(GPRArgRegs[0]));
2850     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2851   }
2852
2853   unsigned Align = MF.getTarget()
2854                        .getSubtargetImpl()
2855                        ->getFrameLowering()
2856                        ->getStackAlignment();
2857   ArgRegsSize = NumGPRs * 4;
2858
2859   // If parameter is split between stack and GPRs...
2860   if (NumGPRs && Align > 4 &&
2861       (ArgRegsSize < ArgSize ||
2862         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2863     // Add padding for part of param recovered from GPRs.  For example,
2864     // if Align == 8, its last byte must be at address K*8 - 1.
2865     // We need to do it, since remained (stack) part of parameter has
2866     // stack alignment, and we need to "attach" "GPRs head" without gaps
2867     // to it:
2868     // Stack:
2869     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2870     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2871     //
2872     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2873     unsigned Padding =
2874         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2875     ArgRegsSaveSize = ArgRegsSize + Padding;
2876   } else
2877     // We don't need to extend regs save size for byval parameters if they
2878     // are passed via GPRs only.
2879     ArgRegsSaveSize = ArgRegsSize;
2880 }
2881
2882 // The remaining GPRs hold either the beginning of variable-argument
2883 // data, or the beginning of an aggregate passed by value (usually
2884 // byval).  Either way, we allocate stack slots adjacent to the data
2885 // provided by our caller, and store the unallocated registers there.
2886 // If this is a variadic function, the va_list pointer will begin with
2887 // these values; otherwise, this reassembles a (byval) structure that
2888 // was split between registers and memory.
2889 // Return: The frame index registers were stored into.
2890 int
2891 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2892                                   SDLoc dl, SDValue &Chain,
2893                                   const Value *OrigArg,
2894                                   unsigned InRegsParamRecordIdx,
2895                                   unsigned OffsetFromOrigArg,
2896                                   unsigned ArgOffset,
2897                                   unsigned ArgSize,
2898                                   bool ForceMutable,
2899                                   unsigned ByValStoreOffset,
2900                                   unsigned TotalArgRegsSaveSize) const {
2901
2902   // Currently, two use-cases possible:
2903   // Case #1. Non-var-args function, and we meet first byval parameter.
2904   //          Setup first unallocated register as first byval register;
2905   //          eat all remained registers
2906   //          (these two actions are performed by HandleByVal method).
2907   //          Then, here, we initialize stack frame with
2908   //          "store-reg" instructions.
2909   // Case #2. Var-args function, that doesn't contain byval parameters.
2910   //          The same: eat all remained unallocated registers,
2911   //          initialize stack frame.
2912
2913   MachineFunction &MF = DAG.getMachineFunction();
2914   MachineFrameInfo *MFI = MF.getFrameInfo();
2915   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2916   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2917   unsigned RBegin, REnd;
2918   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2919     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2920     firstRegToSaveIndex = RBegin - ARM::R0;
2921     lastRegToSaveIndex = REnd - ARM::R0;
2922   } else {
2923     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2924       (GPRArgRegs, array_lengthof(GPRArgRegs));
2925     lastRegToSaveIndex = 4;
2926   }
2927
2928   unsigned ArgRegsSize, ArgRegsSaveSize;
2929   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2930                  ArgRegsSize, ArgRegsSaveSize);
2931
2932   // Store any by-val regs to their spots on the stack so that they may be
2933   // loaded by deferencing the result of formal parameter pointer or va_next.
2934   // Note: once stack area for byval/varargs registers
2935   // was initialized, it can't be initialized again.
2936   if (ArgRegsSaveSize) {
2937     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2938
2939     if (Padding) {
2940       assert(AFI->getStoredByValParamsPadding() == 0 &&
2941              "The only parameter may be padded.");
2942       AFI->setStoredByValParamsPadding(Padding);
2943     }
2944
2945     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2946                                             Padding +
2947                                               ByValStoreOffset -
2948                                               (int64_t)TotalArgRegsSaveSize,
2949                                             false);
2950     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2951     if (Padding) {
2952        MFI->CreateFixedObject(Padding,
2953                               ArgOffset + ByValStoreOffset -
2954                                 (int64_t)ArgRegsSaveSize,
2955                               false);
2956     }
2957
2958     SmallVector<SDValue, 4> MemOps;
2959     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2960          ++firstRegToSaveIndex, ++i) {
2961       const TargetRegisterClass *RC;
2962       if (AFI->isThumb1OnlyFunction())
2963         RC = &ARM::tGPRRegClass;
2964       else
2965         RC = &ARM::GPRRegClass;
2966
2967       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2968       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2969       SDValue Store =
2970         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2971                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2972                      false, false, 0);
2973       MemOps.push_back(Store);
2974       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2975                         DAG.getConstant(4, getPointerTy()));
2976     }
2977
2978     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2979
2980     if (!MemOps.empty())
2981       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2982     return FrameIndex;
2983   } else {
2984     if (ArgSize == 0) {
2985       // We cannot allocate a zero-byte object for the first variadic argument,
2986       // so just make up a size.
2987       ArgSize = 4;
2988     }
2989     // This will point to the next argument passed via stack.
2990     return MFI->CreateFixedObject(
2991       ArgSize, ArgOffset, !ForceMutable);
2992   }
2993 }
2994
2995 // Setup stack frame, the va_list pointer will start from.
2996 void
2997 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2998                                         SDLoc dl, SDValue &Chain,
2999                                         unsigned ArgOffset,
3000                                         unsigned TotalArgRegsSaveSize,
3001                                         bool ForceMutable) const {
3002   MachineFunction &MF = DAG.getMachineFunction();
3003   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3004
3005   // Try to store any remaining integer argument regs
3006   // to their spots on the stack so that they may be loaded by deferencing
3007   // the result of va_next.
3008   // If there is no regs to be stored, just point address after last
3009   // argument passed via stack.
3010   int FrameIndex =
3011     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3012                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3013                    0, TotalArgRegsSaveSize);
3014
3015   AFI->setVarArgsFrameIndex(FrameIndex);
3016 }
3017
3018 SDValue
3019 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3020                                         CallingConv::ID CallConv, bool isVarArg,
3021                                         const SmallVectorImpl<ISD::InputArg>
3022                                           &Ins,
3023                                         SDLoc dl, SelectionDAG &DAG,
3024                                         SmallVectorImpl<SDValue> &InVals)
3025                                           const {
3026   MachineFunction &MF = DAG.getMachineFunction();
3027   MachineFrameInfo *MFI = MF.getFrameInfo();
3028
3029   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3030
3031   // Assign locations to all of the incoming arguments.
3032   SmallVector<CCValAssign, 16> ArgLocs;
3033   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3034                     *DAG.getContext(), Prologue);
3035   CCInfo.AnalyzeFormalArguments(Ins,
3036                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3037                                                   isVarArg));
3038
3039   SmallVector<SDValue, 16> ArgValues;
3040   int lastInsIndex = -1;
3041   SDValue ArgValue;
3042   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3043   unsigned CurArgIdx = 0;
3044
3045   // Initially ArgRegsSaveSize is zero.
3046   // Then we increase this value each time we meet byval parameter.
3047   // We also increase this value in case of varargs function.
3048   AFI->setArgRegsSaveSize(0);
3049
3050   unsigned ByValStoreOffset = 0;
3051   unsigned TotalArgRegsSaveSize = 0;
3052   unsigned ArgRegsSaveSizeMaxAlign = 4;
3053
3054   // Calculate the amount of stack space that we need to allocate to store
3055   // byval and variadic arguments that are passed in registers.
3056   // We need to know this before we allocate the first byval or variadic
3057   // argument, as they will be allocated a stack slot below the CFA (Canonical
3058   // Frame Address, the stack pointer at entry to the function).
3059   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3060     CCValAssign &VA = ArgLocs[i];
3061     if (VA.isMemLoc()) {
3062       int index = VA.getValNo();
3063       if (index != lastInsIndex) {
3064         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3065         if (Flags.isByVal()) {
3066           unsigned ExtraArgRegsSize;
3067           unsigned ExtraArgRegsSaveSize;
3068           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3069                          Flags.getByValSize(),
3070                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3071
3072           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3073           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3074               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3075           CCInfo.nextInRegsParam();
3076         }
3077         lastInsIndex = index;
3078       }
3079     }
3080   }
3081   CCInfo.rewindByValRegsInfo();
3082   lastInsIndex = -1;
3083   if (isVarArg && MFI->hasVAStart()) {
3084     unsigned ExtraArgRegsSize;
3085     unsigned ExtraArgRegsSaveSize;
3086     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3087                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3088     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3089   }
3090   // If the arg regs save area contains N-byte aligned values, the
3091   // bottom of it must be at least N-byte aligned.
3092   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3093   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3094
3095   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3096     CCValAssign &VA = ArgLocs[i];
3097     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3098     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3099     // Arguments stored in registers.
3100     if (VA.isRegLoc()) {
3101       EVT RegVT = VA.getLocVT();
3102
3103       if (VA.needsCustom()) {
3104         // f64 and vector types are split up into multiple registers or
3105         // combinations of registers and stack slots.
3106         if (VA.getLocVT() == MVT::v2f64) {
3107           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3108                                                    Chain, DAG, dl);
3109           VA = ArgLocs[++i]; // skip ahead to next loc
3110           SDValue ArgValue2;
3111           if (VA.isMemLoc()) {
3112             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3113             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3114             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3115                                     MachinePointerInfo::getFixedStack(FI),
3116                                     false, false, false, 0);
3117           } else {
3118             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3119                                              Chain, DAG, dl);
3120           }
3121           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3122           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3123                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3124           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3125                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3126         } else
3127           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3128
3129       } else {
3130         const TargetRegisterClass *RC;
3131
3132         if (RegVT == MVT::f32)
3133           RC = &ARM::SPRRegClass;
3134         else if (RegVT == MVT::f64)
3135           RC = &ARM::DPRRegClass;
3136         else if (RegVT == MVT::v2f64)
3137           RC = &ARM::QPRRegClass;
3138         else if (RegVT == MVT::i32)
3139           RC = AFI->isThumb1OnlyFunction() ?
3140             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3141             (const TargetRegisterClass*)&ARM::GPRRegClass;
3142         else
3143           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3144
3145         // Transform the arguments in physical registers into virtual ones.
3146         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3147         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3148       }
3149
3150       // If this is an 8 or 16-bit value, it is really passed promoted
3151       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3152       // truncate to the right size.
3153       switch (VA.getLocInfo()) {
3154       default: llvm_unreachable("Unknown loc info!");
3155       case CCValAssign::Full: break;
3156       case CCValAssign::BCvt:
3157         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3158         break;
3159       case CCValAssign::SExt:
3160         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3161                                DAG.getValueType(VA.getValVT()));
3162         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3163         break;
3164       case CCValAssign::ZExt:
3165         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3166                                DAG.getValueType(VA.getValVT()));
3167         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3168         break;
3169       }
3170
3171       InVals.push_back(ArgValue);
3172
3173     } else { // VA.isRegLoc()
3174
3175       // sanity check
3176       assert(VA.isMemLoc());
3177       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3178
3179       int index = ArgLocs[i].getValNo();
3180
3181       // Some Ins[] entries become multiple ArgLoc[] entries.
3182       // Process them only once.
3183       if (index != lastInsIndex)
3184         {
3185           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3186           // FIXME: For now, all byval parameter objects are marked mutable.
3187           // This can be changed with more analysis.
3188           // In case of tail call optimization mark all arguments mutable.
3189           // Since they could be overwritten by lowering of arguments in case of
3190           // a tail call.
3191           if (Flags.isByVal()) {
3192             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3193
3194             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3195             int FrameIndex = StoreByValRegs(
3196                 CCInfo, DAG, dl, Chain, CurOrigArg,
3197                 CurByValIndex,
3198                 Ins[VA.getValNo()].PartOffset,
3199                 VA.getLocMemOffset(),
3200                 Flags.getByValSize(),
3201                 true /*force mutable frames*/,
3202                 ByValStoreOffset,
3203                 TotalArgRegsSaveSize);
3204             ByValStoreOffset += Flags.getByValSize();
3205             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3206             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3207             CCInfo.nextInRegsParam();
3208           } else {
3209             unsigned FIOffset = VA.getLocMemOffset();
3210             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3211                                             FIOffset, true);
3212
3213             // Create load nodes to retrieve arguments from the stack.
3214             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3215             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3216                                          MachinePointerInfo::getFixedStack(FI),
3217                                          false, false, false, 0));
3218           }
3219           lastInsIndex = index;
3220         }
3221     }
3222   }
3223
3224   // varargs
3225   if (isVarArg && MFI->hasVAStart())
3226     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3227                          CCInfo.getNextStackOffset(),
3228                          TotalArgRegsSaveSize);
3229
3230   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3231
3232   return Chain;
3233 }
3234
3235 /// isFloatingPointZero - Return true if this is +0.0.
3236 static bool isFloatingPointZero(SDValue Op) {
3237   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3238     return CFP->getValueAPF().isPosZero();
3239   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3240     // Maybe this has already been legalized into the constant pool?
3241     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3242       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3243       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3244         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3245           return CFP->getValueAPF().isPosZero();
3246     }
3247   }
3248   return false;
3249 }
3250
3251 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3252 /// the given operands.
3253 SDValue
3254 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3255                              SDValue &ARMcc, SelectionDAG &DAG,
3256                              SDLoc dl) const {
3257   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3258     unsigned C = RHSC->getZExtValue();
3259     if (!isLegalICmpImmediate(C)) {
3260       // Constant does not fit, try adjusting it by one?
3261       switch (CC) {
3262       default: break;
3263       case ISD::SETLT:
3264       case ISD::SETGE:
3265         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3266           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3267           RHS = DAG.getConstant(C-1, MVT::i32);
3268         }
3269         break;
3270       case ISD::SETULT:
3271       case ISD::SETUGE:
3272         if (C != 0 && isLegalICmpImmediate(C-1)) {
3273           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3274           RHS = DAG.getConstant(C-1, MVT::i32);
3275         }
3276         break;
3277       case ISD::SETLE:
3278       case ISD::SETGT:
3279         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3280           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3281           RHS = DAG.getConstant(C+1, MVT::i32);
3282         }
3283         break;
3284       case ISD::SETULE:
3285       case ISD::SETUGT:
3286         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3287           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3288           RHS = DAG.getConstant(C+1, MVT::i32);
3289         }
3290         break;
3291       }
3292     }
3293   }
3294
3295   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3296   ARMISD::NodeType CompareType;
3297   switch (CondCode) {
3298   default:
3299     CompareType = ARMISD::CMP;
3300     break;
3301   case ARMCC::EQ:
3302   case ARMCC::NE:
3303     // Uses only Z Flag
3304     CompareType = ARMISD::CMPZ;
3305     break;
3306   }
3307   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3308   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3309 }
3310
3311 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3312 SDValue
3313 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3314                              SDLoc dl) const {
3315   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3316   SDValue Cmp;
3317   if (!isFloatingPointZero(RHS))
3318     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3319   else
3320     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3321   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3322 }
3323
3324 /// duplicateCmp - Glue values can have only one use, so this function
3325 /// duplicates a comparison node.
3326 SDValue
3327 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3328   unsigned Opc = Cmp.getOpcode();
3329   SDLoc DL(Cmp);
3330   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3331     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3332
3333   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3334   Cmp = Cmp.getOperand(0);
3335   Opc = Cmp.getOpcode();
3336   if (Opc == ARMISD::CMPFP)
3337     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3338   else {
3339     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3340     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3341   }
3342   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3343 }
3344
3345 std::pair<SDValue, SDValue>
3346 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3347                                  SDValue &ARMcc) const {
3348   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3349
3350   SDValue Value, OverflowCmp;
3351   SDValue LHS = Op.getOperand(0);
3352   SDValue RHS = Op.getOperand(1);
3353
3354
3355   // FIXME: We are currently always generating CMPs because we don't support
3356   // generating CMN through the backend. This is not as good as the natural
3357   // CMP case because it causes a register dependency and cannot be folded
3358   // later.
3359
3360   switch (Op.getOpcode()) {
3361   default:
3362     llvm_unreachable("Unknown overflow instruction!");
3363   case ISD::SADDO:
3364     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3365     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3366     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3367     break;
3368   case ISD::UADDO:
3369     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3370     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3371     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3372     break;
3373   case ISD::SSUBO:
3374     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3375     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3376     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3377     break;
3378   case ISD::USUBO:
3379     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3380     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3381     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3382     break;
3383   } // switch (...)
3384
3385   return std::make_pair(Value, OverflowCmp);
3386 }
3387
3388
3389 SDValue
3390 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3391   // Let legalize expand this if it isn't a legal type yet.
3392   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3393     return SDValue();
3394
3395   SDValue Value, OverflowCmp;
3396   SDValue ARMcc;
3397   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3398   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399   // We use 0 and 1 as false and true values.
3400   SDValue TVal = DAG.getConstant(1, MVT::i32);
3401   SDValue FVal = DAG.getConstant(0, MVT::i32);
3402   EVT VT = Op.getValueType();
3403
3404   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3405                                  ARMcc, CCR, OverflowCmp);
3406
3407   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3408   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3409 }
3410
3411
3412 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3413   SDValue Cond = Op.getOperand(0);
3414   SDValue SelectTrue = Op.getOperand(1);
3415   SDValue SelectFalse = Op.getOperand(2);
3416   SDLoc dl(Op);
3417   unsigned Opc = Cond.getOpcode();
3418
3419   if (Cond.getResNo() == 1 &&
3420       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3421        Opc == ISD::USUBO)) {
3422     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3423       return SDValue();
3424
3425     SDValue Value, OverflowCmp;
3426     SDValue ARMcc;
3427     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3428     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3429     EVT VT = Op.getValueType();
3430
3431     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3432                    OverflowCmp, DAG);
3433   }
3434
3435   // Convert:
3436   //
3437   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3438   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3439   //
3440   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3441     const ConstantSDNode *CMOVTrue =
3442       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3443     const ConstantSDNode *CMOVFalse =
3444       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3445
3446     if (CMOVTrue && CMOVFalse) {
3447       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3448       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3449
3450       SDValue True;
3451       SDValue False;
3452       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3453         True = SelectTrue;
3454         False = SelectFalse;
3455       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3456         True = SelectFalse;
3457         False = SelectTrue;
3458       }
3459
3460       if (True.getNode() && False.getNode()) {
3461         EVT VT = Op.getValueType();
3462         SDValue ARMcc = Cond.getOperand(2);
3463         SDValue CCR = Cond.getOperand(3);
3464         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3465         assert(True.getValueType() == VT);
3466         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3467       }
3468     }
3469   }
3470
3471   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3472   // undefined bits before doing a full-word comparison with zero.
3473   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3474                      DAG.getConstant(1, Cond.getValueType()));
3475
3476   return DAG.getSelectCC(dl, Cond,
3477                          DAG.getConstant(0, Cond.getValueType()),
3478                          SelectTrue, SelectFalse, ISD::SETNE);
3479 }
3480
3481 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3482   if (CC == ISD::SETNE)
3483     return ISD::SETEQ;
3484   return ISD::getSetCCInverse(CC, true);
3485 }
3486
3487 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3488                                  bool &swpCmpOps, bool &swpVselOps) {
3489   // Start by selecting the GE condition code for opcodes that return true for
3490   // 'equality'
3491   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3492       CC == ISD::SETULE)
3493     CondCode = ARMCC::GE;
3494
3495   // and GT for opcodes that return false for 'equality'.
3496   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3497            CC == ISD::SETULT)
3498     CondCode = ARMCC::GT;
3499
3500   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3501   // to swap the compare operands.
3502   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3503       CC == ISD::SETULT)
3504     swpCmpOps = true;
3505
3506   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3507   // If we have an unordered opcode, we need to swap the operands to the VSEL
3508   // instruction (effectively negating the condition).
3509   //
3510   // This also has the effect of swapping which one of 'less' or 'greater'
3511   // returns true, so we also swap the compare operands. It also switches
3512   // whether we return true for 'equality', so we compensate by picking the
3513   // opposite condition code to our original choice.
3514   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3515       CC == ISD::SETUGT) {
3516     swpCmpOps = !swpCmpOps;
3517     swpVselOps = !swpVselOps;
3518     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3519   }
3520
3521   // 'ordered' is 'anything but unordered', so use the VS condition code and
3522   // swap the VSEL operands.
3523   if (CC == ISD::SETO) {
3524     CondCode = ARMCC::VS;
3525     swpVselOps = true;
3526   }
3527
3528   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3529   // code and swap the VSEL operands.
3530   if (CC == ISD::SETUNE) {
3531     CondCode = ARMCC::EQ;
3532     swpVselOps = true;
3533   }
3534 }
3535
3536 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3537                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3538                                    SDValue Cmp, SelectionDAG &DAG) const {
3539   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3540     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3541                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3542     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3543                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3544
3545     SDValue TrueLow = TrueVal.getValue(0);
3546     SDValue TrueHigh = TrueVal.getValue(1);
3547     SDValue FalseLow = FalseVal.getValue(0);
3548     SDValue FalseHigh = FalseVal.getValue(1);
3549
3550     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3551                               ARMcc, CCR, Cmp);
3552     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3553                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3554
3555     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3556   } else {
3557     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3558                        Cmp);
3559   }
3560 }
3561
3562 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3563   EVT VT = Op.getValueType();
3564   SDValue LHS = Op.getOperand(0);
3565   SDValue RHS = Op.getOperand(1);
3566   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3567   SDValue TrueVal = Op.getOperand(2);
3568   SDValue FalseVal = Op.getOperand(3);
3569   SDLoc dl(Op);
3570
3571   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3572     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3573                                                     dl);
3574
3575     // If softenSetCCOperands only returned one value, we should compare it to
3576     // zero.
3577     if (!RHS.getNode()) {
3578       RHS = DAG.getConstant(0, LHS.getValueType());
3579       CC = ISD::SETNE;
3580     }
3581   }
3582
3583   if (LHS.getValueType() == MVT::i32) {
3584     // Try to generate VSEL on ARMv8.
3585     // The VSEL instruction can't use all the usual ARM condition
3586     // codes: it only has two bits to select the condition code, so it's
3587     // constrained to use only GE, GT, VS and EQ.
3588     //
3589     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3590     // swap the operands of the previous compare instruction (effectively
3591     // inverting the compare condition, swapping 'less' and 'greater') and
3592     // sometimes need to swap the operands to the VSEL (which inverts the
3593     // condition in the sense of firing whenever the previous condition didn't)
3594     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3595                                       TrueVal.getValueType() == MVT::f64)) {
3596       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3597       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3598           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3599         CC = getInverseCCForVSEL(CC);
3600         std::swap(TrueVal, FalseVal);
3601       }
3602     }
3603
3604     SDValue ARMcc;
3605     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3606     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3607     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3608   }
3609
3610   ARMCC::CondCodes CondCode, CondCode2;
3611   FPCCToARMCC(CC, CondCode, CondCode2);
3612
3613   // Try to generate VSEL on ARMv8.
3614   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3615                                     TrueVal.getValueType() == MVT::f64)) {
3616     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3617     // same operands, as follows:
3618     //   c = fcmp [ogt, olt, ugt, ult] a, b
3619     //   select c, a, b
3620     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3621     // handled differently than the original code sequence.
3622     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3623         RHS == FalseVal) {
3624       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3625         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3626       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3627         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3628     }
3629
3630     bool swpCmpOps = false;
3631     bool swpVselOps = false;
3632     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3633
3634     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3635         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3636       if (swpCmpOps)
3637         std::swap(LHS, RHS);
3638       if (swpVselOps)
3639         std::swap(TrueVal, FalseVal);
3640     }
3641   }
3642
3643   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3644   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3645   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3646   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3647   if (CondCode2 != ARMCC::AL) {
3648     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3649     // FIXME: Needs another CMP because flag can have but one use.
3650     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3651     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3652   }
3653   return Result;
3654 }
3655
3656 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3657 /// to morph to an integer compare sequence.
3658 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3659                            const ARMSubtarget *Subtarget) {
3660   SDNode *N = Op.getNode();
3661   if (!N->hasOneUse())
3662     // Otherwise it requires moving the value from fp to integer registers.
3663     return false;
3664   if (!N->getNumValues())
3665     return false;
3666   EVT VT = Op.getValueType();
3667   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3668     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3669     // vmrs are very slow, e.g. cortex-a8.
3670     return false;
3671
3672   if (isFloatingPointZero(Op)) {
3673     SeenZero = true;
3674     return true;
3675   }
3676   return ISD::isNormalLoad(N);
3677 }
3678
3679 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3680   if (isFloatingPointZero(Op))
3681     return DAG.getConstant(0, MVT::i32);
3682
3683   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3684     return DAG.getLoad(MVT::i32, SDLoc(Op),
3685                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3686                        Ld->isVolatile(), Ld->isNonTemporal(),
3687                        Ld->isInvariant(), Ld->getAlignment());
3688
3689   llvm_unreachable("Unknown VFP cmp argument!");
3690 }
3691
3692 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3693                            SDValue &RetVal1, SDValue &RetVal2) {
3694   if (isFloatingPointZero(Op)) {
3695     RetVal1 = DAG.getConstant(0, MVT::i32);
3696     RetVal2 = DAG.getConstant(0, MVT::i32);
3697     return;
3698   }
3699
3700   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3701     SDValue Ptr = Ld->getBasePtr();
3702     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3703                           Ld->getChain(), Ptr,
3704                           Ld->getPointerInfo(),
3705                           Ld->isVolatile(), Ld->isNonTemporal(),
3706                           Ld->isInvariant(), Ld->getAlignment());
3707
3708     EVT PtrType = Ptr.getValueType();
3709     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3710     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3711                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3712     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3713                           Ld->getChain(), NewPtr,
3714                           Ld->getPointerInfo().getWithOffset(4),
3715                           Ld->isVolatile(), Ld->isNonTemporal(),
3716                           Ld->isInvariant(), NewAlign);
3717     return;
3718   }
3719
3720   llvm_unreachable("Unknown VFP cmp argument!");
3721 }
3722
3723 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3724 /// f32 and even f64 comparisons to integer ones.
3725 SDValue
3726 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3727   SDValue Chain = Op.getOperand(0);
3728   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3729   SDValue LHS = Op.getOperand(2);
3730   SDValue RHS = Op.getOperand(3);
3731   SDValue Dest = Op.getOperand(4);
3732   SDLoc dl(Op);
3733
3734   bool LHSSeenZero = false;
3735   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3736   bool RHSSeenZero = false;
3737   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3738   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3739     // If unsafe fp math optimization is enabled and there are no other uses of
3740     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3741     // to an integer comparison.
3742     if (CC == ISD::SETOEQ)
3743       CC = ISD::SETEQ;
3744     else if (CC == ISD::SETUNE)
3745       CC = ISD::SETNE;
3746
3747     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3748     SDValue ARMcc;
3749     if (LHS.getValueType() == MVT::f32) {
3750       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3751                         bitcastf32Toi32(LHS, DAG), Mask);
3752       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3753                         bitcastf32Toi32(RHS, DAG), Mask);
3754       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3755       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3756       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3757                          Chain, Dest, ARMcc, CCR, Cmp);
3758     }
3759
3760     SDValue LHS1, LHS2;
3761     SDValue RHS1, RHS2;
3762     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3763     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3764     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3765     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3766     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3767     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3768     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3769     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3770     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3771   }
3772
3773   return SDValue();
3774 }
3775
3776 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3777   SDValue Chain = Op.getOperand(0);
3778   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3779   SDValue LHS = Op.getOperand(2);
3780   SDValue RHS = Op.getOperand(3);
3781   SDValue Dest = Op.getOperand(4);
3782   SDLoc dl(Op);
3783
3784   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3785     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3786                                                     dl);
3787
3788     // If softenSetCCOperands only returned one value, we should compare it to
3789     // zero.
3790     if (!RHS.getNode()) {
3791       RHS = DAG.getConstant(0, LHS.getValueType());
3792       CC = ISD::SETNE;
3793     }
3794   }
3795
3796   if (LHS.getValueType() == MVT::i32) {
3797     SDValue ARMcc;
3798     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3799     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3800     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3801                        Chain, Dest, ARMcc, CCR, Cmp);
3802   }
3803
3804   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3805
3806   if (getTargetMachine().Options.UnsafeFPMath &&
3807       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3808        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3809     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3810     if (Result.getNode())
3811       return Result;
3812   }
3813
3814   ARMCC::CondCodes CondCode, CondCode2;
3815   FPCCToARMCC(CC, CondCode, CondCode2);
3816
3817   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3818   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3819   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3820   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3821   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3822   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3823   if (CondCode2 != ARMCC::AL) {
3824     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3825     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3826     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3827   }
3828   return Res;
3829 }
3830
3831 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3832   SDValue Chain = Op.getOperand(0);
3833   SDValue Table = Op.getOperand(1);
3834   SDValue Index = Op.getOperand(2);
3835   SDLoc dl(Op);
3836
3837   EVT PTy = getPointerTy();
3838   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3839   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3840   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3841   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3842   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3843   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3844   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3845   if (Subtarget->isThumb2()) {
3846     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3847     // which does another jump to the destination. This also makes it easier
3848     // to translate it to TBB / TBH later.
3849     // FIXME: This might not work if the function is extremely large.
3850     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3851                        Addr, Op.getOperand(2), JTI, UId);
3852   }
3853   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3854     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3855                        MachinePointerInfo::getJumpTable(),
3856                        false, false, false, 0);
3857     Chain = Addr.getValue(1);
3858     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3859     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3860   } else {
3861     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3862                        MachinePointerInfo::getJumpTable(),
3863                        false, false, false, 0);
3864     Chain = Addr.getValue(1);
3865     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3866   }
3867 }
3868
3869 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3870   EVT VT = Op.getValueType();
3871   SDLoc dl(Op);
3872
3873   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3874     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3875       return Op;
3876     return DAG.UnrollVectorOp(Op.getNode());
3877   }
3878
3879   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3880          "Invalid type for custom lowering!");
3881   if (VT != MVT::v4i16)
3882     return DAG.UnrollVectorOp(Op.getNode());
3883
3884   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3885   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3886 }
3887
3888 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3889   EVT VT = Op.getValueType();
3890   if (VT.isVector())
3891     return LowerVectorFP_TO_INT(Op, DAG);
3892
3893   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3894     RTLIB::Libcall LC;
3895     if (Op.getOpcode() == ISD::FP_TO_SINT)
3896       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3897                               Op.getValueType());
3898     else
3899       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3900                               Op.getValueType());
3901     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3902                        /*isSigned*/ false, SDLoc(Op)).first;
3903   }
3904
3905   SDLoc dl(Op);
3906   unsigned Opc;
3907
3908   switch (Op.getOpcode()) {
3909   default: llvm_unreachable("Invalid opcode!");
3910   case ISD::FP_TO_SINT:
3911     Opc = ARMISD::FTOSI;
3912     break;
3913   case ISD::FP_TO_UINT:
3914     Opc = ARMISD::FTOUI;
3915     break;
3916   }
3917   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3918   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3919 }
3920
3921 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3922   EVT VT = Op.getValueType();
3923   SDLoc dl(Op);
3924
3925   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3926     if (VT.getVectorElementType() == MVT::f32)
3927       return Op;
3928     return DAG.UnrollVectorOp(Op.getNode());
3929   }
3930
3931   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3932          "Invalid type for custom lowering!");
3933   if (VT != MVT::v4f32)
3934     return DAG.UnrollVectorOp(Op.getNode());
3935
3936   unsigned CastOpc;
3937   unsigned Opc;
3938   switch (Op.getOpcode()) {
3939   default: llvm_unreachable("Invalid opcode!");
3940   case ISD::SINT_TO_FP:
3941     CastOpc = ISD::SIGN_EXTEND;
3942     Opc = ISD::SINT_TO_FP;
3943     break;
3944   case ISD::UINT_TO_FP:
3945     CastOpc = ISD::ZERO_EXTEND;
3946     Opc = ISD::UINT_TO_FP;
3947     break;
3948   }
3949
3950   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3951   return DAG.getNode(Opc, dl, VT, Op);
3952 }
3953
3954 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3955   EVT VT = Op.getValueType();
3956   if (VT.isVector())
3957     return LowerVectorINT_TO_FP(Op, DAG);
3958
3959   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3960     RTLIB::Libcall LC;
3961     if (Op.getOpcode() == ISD::SINT_TO_FP)
3962       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3963                               Op.getValueType());
3964     else
3965       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3966                               Op.getValueType());
3967     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3968                        /*isSigned*/ false, SDLoc(Op)).first;
3969   }
3970
3971   SDLoc dl(Op);
3972   unsigned Opc;
3973
3974   switch (Op.getOpcode()) {
3975   default: llvm_unreachable("Invalid opcode!");
3976   case ISD::SINT_TO_FP:
3977     Opc = ARMISD::SITOF;
3978     break;
3979   case ISD::UINT_TO_FP:
3980     Opc = ARMISD::UITOF;
3981     break;
3982   }
3983
3984   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3985   return DAG.getNode(Opc, dl, VT, Op);
3986 }
3987
3988 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3989   // Implement fcopysign with a fabs and a conditional fneg.
3990   SDValue Tmp0 = Op.getOperand(0);
3991   SDValue Tmp1 = Op.getOperand(1);
3992   SDLoc dl(Op);
3993   EVT VT = Op.getValueType();
3994   EVT SrcVT = Tmp1.getValueType();
3995   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3996     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3997   bool UseNEON = !InGPR && Subtarget->hasNEON();
3998
3999   if (UseNEON) {
4000     // Use VBSL to copy the sign bit.
4001     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4002     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4003                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4004     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4005     if (VT == MVT::f64)
4006       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4007                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4008                          DAG.getConstant(32, MVT::i32));
4009     else /*if (VT == MVT::f32)*/
4010       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4011     if (SrcVT == MVT::f32) {
4012       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4013       if (VT == MVT::f64)
4014         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4015                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4016                            DAG.getConstant(32, MVT::i32));
4017     } else if (VT == MVT::f32)
4018       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4019                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4020                          DAG.getConstant(32, MVT::i32));
4021     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4022     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4023
4024     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4025                                             MVT::i32);
4026     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4027     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4028                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4029
4030     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4031                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4032                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4033     if (VT == MVT::f32) {
4034       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4035       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4036                         DAG.getConstant(0, MVT::i32));
4037     } else {
4038       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4039     }
4040
4041     return Res;
4042   }
4043
4044   // Bitcast operand 1 to i32.
4045   if (SrcVT == MVT::f64)
4046     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4047                        Tmp1).getValue(1);
4048   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4049
4050   // Or in the signbit with integer operations.
4051   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4052   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4053   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4054   if (VT == MVT::f32) {
4055     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4056                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4057     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4058                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4059   }
4060
4061   // f64: Or the high part with signbit and then combine two parts.
4062   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4063                      Tmp0);
4064   SDValue Lo = Tmp0.getValue(0);
4065   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4066   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4067   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4068 }
4069
4070 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4071   MachineFunction &MF = DAG.getMachineFunction();
4072   MachineFrameInfo *MFI = MF.getFrameInfo();
4073   MFI->setReturnAddressIsTaken(true);
4074
4075   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4076     return SDValue();
4077
4078   EVT VT = Op.getValueType();
4079   SDLoc dl(Op);
4080   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4081   if (Depth) {
4082     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4083     SDValue Offset = DAG.getConstant(4, MVT::i32);
4084     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4085                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4086                        MachinePointerInfo(), false, false, false, 0);
4087   }
4088
4089   // Return LR, which contains the return address. Mark it an implicit live-in.
4090   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4091   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4092 }
4093
4094 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4095   const ARMBaseRegisterInfo &ARI =
4096     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4097   MachineFunction &MF = DAG.getMachineFunction();
4098   MachineFrameInfo *MFI = MF.getFrameInfo();
4099   MFI->setFrameAddressIsTaken(true);
4100
4101   EVT VT = Op.getValueType();
4102   SDLoc dl(Op);  // FIXME probably not meaningful
4103   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4104   unsigned FrameReg = ARI.getFrameRegister(MF);
4105   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4106   while (Depth--)
4107     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4108                             MachinePointerInfo(),
4109                             false, false, false, 0);
4110   return FrameAddr;
4111 }
4112
4113 // FIXME? Maybe this could be a TableGen attribute on some registers and
4114 // this table could be generated automatically from RegInfo.
4115 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4116                                               EVT VT) const {
4117   unsigned Reg = StringSwitch<unsigned>(RegName)
4118                        .Case("sp", ARM::SP)
4119                        .Default(0);
4120   if (Reg)
4121     return Reg;
4122   report_fatal_error("Invalid register name global variable");
4123 }
4124
4125 /// ExpandBITCAST - If the target supports VFP, this function is called to
4126 /// expand a bit convert where either the source or destination type is i64 to
4127 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4128 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4129 /// vectors), since the legalizer won't know what to do with that.
4130 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4131   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4132   SDLoc dl(N);
4133   SDValue Op = N->getOperand(0);
4134
4135   // This function is only supposed to be called for i64 types, either as the
4136   // source or destination of the bit convert.
4137   EVT SrcVT = Op.getValueType();
4138   EVT DstVT = N->getValueType(0);
4139   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4140          "ExpandBITCAST called for non-i64 type");
4141
4142   // Turn i64->f64 into VMOVDRR.
4143   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4144     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4145                              DAG.getConstant(0, MVT::i32));
4146     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4147                              DAG.getConstant(1, MVT::i32));
4148     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4149                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4150   }
4151
4152   // Turn f64->i64 into VMOVRRD.
4153   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4154     SDValue Cvt;
4155     if (TLI.isBigEndian() && SrcVT.isVector() &&
4156         SrcVT.getVectorNumElements() > 1)
4157       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4158                         DAG.getVTList(MVT::i32, MVT::i32),
4159                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4160     else
4161       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4162                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4163     // Merge the pieces into a single i64 value.
4164     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4165   }
4166
4167   return SDValue();
4168 }
4169
4170 /// getZeroVector - Returns a vector of specified type with all zero elements.
4171 /// Zero vectors are used to represent vector negation and in those cases
4172 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4173 /// not support i64 elements, so sometimes the zero vectors will need to be
4174 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4175 /// zero vector.
4176 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4177   assert(VT.isVector() && "Expected a vector type");
4178   // The canonical modified immediate encoding of a zero vector is....0!
4179   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4180   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4181   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4182   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4183 }
4184
4185 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4186 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4187 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4188                                                 SelectionDAG &DAG) const {
4189   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4190   EVT VT = Op.getValueType();
4191   unsigned VTBits = VT.getSizeInBits();
4192   SDLoc dl(Op);
4193   SDValue ShOpLo = Op.getOperand(0);
4194   SDValue ShOpHi = Op.getOperand(1);
4195   SDValue ShAmt  = Op.getOperand(2);
4196   SDValue ARMcc;
4197   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4198
4199   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4200
4201   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4202                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4203   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4204   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4205                                    DAG.getConstant(VTBits, MVT::i32));
4206   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4207   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4208   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4209
4210   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4211   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4212                           ARMcc, DAG, dl);
4213   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4214   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4215                            CCR, Cmp);
4216
4217   SDValue Ops[2] = { Lo, Hi };
4218   return DAG.getMergeValues(Ops, dl);
4219 }
4220
4221 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4222 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4223 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4224                                                SelectionDAG &DAG) const {
4225   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4226   EVT VT = Op.getValueType();
4227   unsigned VTBits = VT.getSizeInBits();
4228   SDLoc dl(Op);
4229   SDValue ShOpLo = Op.getOperand(0);
4230   SDValue ShOpHi = Op.getOperand(1);
4231   SDValue ShAmt  = Op.getOperand(2);
4232   SDValue ARMcc;
4233
4234   assert(Op.getOpcode() == ISD::SHL_PARTS);
4235   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4236                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4237   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4238   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4239                                    DAG.getConstant(VTBits, MVT::i32));
4240   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4241   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4242
4243   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4244   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4245   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4246                           ARMcc, DAG, dl);
4247   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4248   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4249                            CCR, Cmp);
4250
4251   SDValue Ops[2] = { Lo, Hi };
4252   return DAG.getMergeValues(Ops, dl);
4253 }
4254
4255 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4256                                             SelectionDAG &DAG) const {
4257   // The rounding mode is in bits 23:22 of the FPSCR.
4258   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4259   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4260   // so that the shift + and get folded into a bitfield extract.
4261   SDLoc dl(Op);
4262   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4263                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4264                                               MVT::i32));
4265   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4266                                   DAG.getConstant(1U << 22, MVT::i32));
4267   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4268                               DAG.getConstant(22, MVT::i32));
4269   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4270                      DAG.getConstant(3, MVT::i32));
4271 }
4272
4273 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4274                          const ARMSubtarget *ST) {
4275   EVT VT = N->getValueType(0);
4276   SDLoc dl(N);
4277
4278   if (!ST->hasV6T2Ops())
4279     return SDValue();
4280
4281   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4282   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4283 }
4284
4285 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4286 /// for each 16-bit element from operand, repeated.  The basic idea is to
4287 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4288 ///
4289 /// Trace for v4i16:
4290 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4291 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4292 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4293 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4294 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4295 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4296 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4297 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4298 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4299   EVT VT = N->getValueType(0);
4300   SDLoc DL(N);
4301
4302   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4303   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4304   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4305   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4306   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4307   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4308 }
4309
4310 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4311 /// bit-count for each 16-bit element from the operand.  We need slightly
4312 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4313 /// 64/128-bit registers.
4314 ///
4315 /// Trace for v4i16:
4316 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4317 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4318 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4319 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4320 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4321   EVT VT = N->getValueType(0);
4322   SDLoc DL(N);
4323
4324   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4325   if (VT.is64BitVector()) {
4326     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4327     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4328                        DAG.getIntPtrConstant(0));
4329   } else {
4330     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4331                                     BitCounts, DAG.getIntPtrConstant(0));
4332     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4333   }
4334 }
4335
4336 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4337 /// bit-count for each 32-bit element from the operand.  The idea here is
4338 /// to split the vector into 16-bit elements, leverage the 16-bit count
4339 /// routine, and then combine the results.
4340 ///
4341 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4342 /// input    = [v0    v1    ] (vi: 32-bit elements)
4343 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4344 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4345 /// vrev: N0 = [k1 k0 k3 k2 ]
4346 ///            [k0 k1 k2 k3 ]
4347 ///       N1 =+[k1 k0 k3 k2 ]
4348 ///            [k0 k2 k1 k3 ]
4349 ///       N2 =+[k1 k3 k0 k2 ]
4350 ///            [k0    k2    k1    k3    ]
4351 /// Extended =+[k1    k3    k0    k2    ]
4352 ///            [k0    k2    ]
4353 /// Extracted=+[k1    k3    ]
4354 ///
4355 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4356   EVT VT = N->getValueType(0);
4357   SDLoc DL(N);
4358
4359   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4360
4361   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4362   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4363   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4364   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4365   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4366
4367   if (VT.is64BitVector()) {
4368     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4369     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4370                        DAG.getIntPtrConstant(0));
4371   } else {
4372     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4373                                     DAG.getIntPtrConstant(0));
4374     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4375   }
4376 }
4377
4378 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4379                           const ARMSubtarget *ST) {
4380   EVT VT = N->getValueType(0);
4381
4382   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4383   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4384           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4385          "Unexpected type for custom ctpop lowering");
4386
4387   if (VT.getVectorElementType() == MVT::i32)
4388     return lowerCTPOP32BitElements(N, DAG);
4389   else
4390     return lowerCTPOP16BitElements(N, DAG);
4391 }
4392
4393 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4394                           const ARMSubtarget *ST) {
4395   EVT VT = N->getValueType(0);
4396   SDLoc dl(N);
4397
4398   if (!VT.isVector())
4399     return SDValue();
4400
4401   // Lower vector shifts on NEON to use VSHL.
4402   assert(ST->hasNEON() && "unexpected vector shift");
4403
4404   // Left shifts translate directly to the vshiftu intrinsic.
4405   if (N->getOpcode() == ISD::SHL)
4406     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4407                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4408                        N->getOperand(0), N->getOperand(1));
4409
4410   assert((N->getOpcode() == ISD::SRA ||
4411           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4412
4413   // NEON uses the same intrinsics for both left and right shifts.  For
4414   // right shifts, the shift amounts are negative, so negate the vector of
4415   // shift amounts.
4416   EVT ShiftVT = N->getOperand(1).getValueType();
4417   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4418                                      getZeroVector(ShiftVT, DAG, dl),
4419                                      N->getOperand(1));
4420   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4421                              Intrinsic::arm_neon_vshifts :
4422                              Intrinsic::arm_neon_vshiftu);
4423   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4424                      DAG.getConstant(vshiftInt, MVT::i32),
4425                      N->getOperand(0), NegatedCount);
4426 }
4427
4428 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4429                                 const ARMSubtarget *ST) {
4430   EVT VT = N->getValueType(0);
4431   SDLoc dl(N);
4432
4433   // We can get here for a node like i32 = ISD::SHL i32, i64
4434   if (VT != MVT::i64)
4435     return SDValue();
4436
4437   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4438          "Unknown shift to lower!");
4439
4440   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4441   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4442       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4443     return SDValue();
4444
4445   // If we are in thumb mode, we don't have RRX.
4446   if (ST->isThumb1Only()) return SDValue();
4447
4448   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4449   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4450                            DAG.getConstant(0, MVT::i32));
4451   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4452                            DAG.getConstant(1, MVT::i32));
4453
4454   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4455   // captures the result into a carry flag.
4456   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4457   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4458
4459   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4460   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4461
4462   // Merge the pieces into a single i64 value.
4463  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4464 }
4465
4466 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4467   SDValue TmpOp0, TmpOp1;
4468   bool Invert = false;
4469   bool Swap = false;
4470   unsigned Opc = 0;
4471
4472   SDValue Op0 = Op.getOperand(0);
4473   SDValue Op1 = Op.getOperand(1);
4474   SDValue CC = Op.getOperand(2);
4475   EVT VT = Op.getValueType();
4476   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4477   SDLoc dl(Op);
4478
4479   if (Op1.getValueType().isFloatingPoint()) {
4480     switch (SetCCOpcode) {
4481     default: llvm_unreachable("Illegal FP comparison");
4482     case ISD::SETUNE:
4483     case ISD::SETNE:  Invert = true; // Fallthrough
4484     case ISD::SETOEQ:
4485     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4486     case ISD::SETOLT:
4487     case ISD::SETLT: Swap = true; // Fallthrough
4488     case ISD::SETOGT:
4489     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4490     case ISD::SETOLE:
4491     case ISD::SETLE:  Swap = true; // Fallthrough
4492     case ISD::SETOGE:
4493     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4494     case ISD::SETUGE: Swap = true; // Fallthrough
4495     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4496     case ISD::SETUGT: Swap = true; // Fallthrough
4497     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4498     case ISD::SETUEQ: Invert = true; // Fallthrough
4499     case ISD::SETONE:
4500       // Expand this to (OLT | OGT).
4501       TmpOp0 = Op0;
4502       TmpOp1 = Op1;
4503       Opc = ISD::OR;
4504       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4505       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4506       break;
4507     case ISD::SETUO: Invert = true; // Fallthrough
4508     case ISD::SETO:
4509       // Expand this to (OLT | OGE).
4510       TmpOp0 = Op0;
4511       TmpOp1 = Op1;
4512       Opc = ISD::OR;
4513       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4514       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4515       break;
4516     }
4517   } else {
4518     // Integer comparisons.
4519     switch (SetCCOpcode) {
4520     default: llvm_unreachable("Illegal integer comparison");
4521     case ISD::SETNE:  Invert = true;
4522     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4523     case ISD::SETLT:  Swap = true;
4524     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4525     case ISD::SETLE:  Swap = true;
4526     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4527     case ISD::SETULT: Swap = true;
4528     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4529     case ISD::SETULE: Swap = true;
4530     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4531     }
4532
4533     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4534     if (Opc == ARMISD::VCEQ) {
4535
4536       SDValue AndOp;
4537       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4538         AndOp = Op0;
4539       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4540         AndOp = Op1;
4541
4542       // Ignore bitconvert.
4543       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4544         AndOp = AndOp.getOperand(0);
4545
4546       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4547         Opc = ARMISD::VTST;
4548         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4549         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4550         Invert = !Invert;
4551       }
4552     }
4553   }
4554
4555   if (Swap)
4556     std::swap(Op0, Op1);
4557
4558   // If one of the operands is a constant vector zero, attempt to fold the
4559   // comparison to a specialized compare-against-zero form.
4560   SDValue SingleOp;
4561   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4562     SingleOp = Op0;
4563   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4564     if (Opc == ARMISD::VCGE)
4565       Opc = ARMISD::VCLEZ;
4566     else if (Opc == ARMISD::VCGT)
4567       Opc = ARMISD::VCLTZ;
4568     SingleOp = Op1;
4569   }
4570
4571   SDValue Result;
4572   if (SingleOp.getNode()) {
4573     switch (Opc) {
4574     case ARMISD::VCEQ:
4575       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4576     case ARMISD::VCGE:
4577       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4578     case ARMISD::VCLEZ:
4579       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4580     case ARMISD::VCGT:
4581       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4582     case ARMISD::VCLTZ:
4583       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4584     default:
4585       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4586     }
4587   } else {
4588      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4589   }
4590
4591   if (Invert)
4592     Result = DAG.getNOT(dl, Result, VT);
4593
4594   return Result;
4595 }
4596
4597 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4598 /// valid vector constant for a NEON instruction with a "modified immediate"
4599 /// operand (e.g., VMOV).  If so, return the encoded value.
4600 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4601                                  unsigned SplatBitSize, SelectionDAG &DAG,
4602                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4603   unsigned OpCmode, Imm;
4604
4605   // SplatBitSize is set to the smallest size that splats the vector, so a
4606   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4607   // immediate instructions others than VMOV do not support the 8-bit encoding
4608   // of a zero vector, and the default encoding of zero is supposed to be the
4609   // 32-bit version.
4610   if (SplatBits == 0)
4611     SplatBitSize = 32;
4612
4613   switch (SplatBitSize) {
4614   case 8:
4615     if (type != VMOVModImm)
4616       return SDValue();
4617     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4618     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4619     OpCmode = 0xe;
4620     Imm = SplatBits;
4621     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4622     break;
4623
4624   case 16:
4625     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4626     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4627     if ((SplatBits & ~0xff) == 0) {
4628       // Value = 0x00nn: Op=x, Cmode=100x.
4629       OpCmode = 0x8;
4630       Imm = SplatBits;
4631       break;
4632     }
4633     if ((SplatBits & ~0xff00) == 0) {
4634       // Value = 0xnn00: Op=x, Cmode=101x.
4635       OpCmode = 0xa;
4636       Imm = SplatBits >> 8;
4637       break;
4638     }
4639     return SDValue();
4640
4641   case 32:
4642     // NEON's 32-bit VMOV supports splat values where:
4643     // * only one byte is nonzero, or
4644     // * the least significant byte is 0xff and the second byte is nonzero, or
4645     // * the least significant 2 bytes are 0xff and the third is nonzero.
4646     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4647     if ((SplatBits & ~0xff) == 0) {
4648       // Value = 0x000000nn: Op=x, Cmode=000x.
4649       OpCmode = 0;
4650       Imm = SplatBits;
4651       break;
4652     }
4653     if ((SplatBits & ~0xff00) == 0) {
4654       // Value = 0x0000nn00: Op=x, Cmode=001x.
4655       OpCmode = 0x2;
4656       Imm = SplatBits >> 8;
4657       break;
4658     }
4659     if ((SplatBits & ~0xff0000) == 0) {
4660       // Value = 0x00nn0000: Op=x, Cmode=010x.
4661       OpCmode = 0x4;
4662       Imm = SplatBits >> 16;
4663       break;
4664     }
4665     if ((SplatBits & ~0xff000000) == 0) {
4666       // Value = 0xnn000000: Op=x, Cmode=011x.
4667       OpCmode = 0x6;
4668       Imm = SplatBits >> 24;
4669       break;
4670     }
4671
4672     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4673     if (type == OtherModImm) return SDValue();
4674
4675     if ((SplatBits & ~0xffff) == 0 &&
4676         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4677       // Value = 0x0000nnff: Op=x, Cmode=1100.
4678       OpCmode = 0xc;
4679       Imm = SplatBits >> 8;
4680       break;
4681     }
4682
4683     if ((SplatBits & ~0xffffff) == 0 &&
4684         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4685       // Value = 0x00nnffff: Op=x, Cmode=1101.
4686       OpCmode = 0xd;
4687       Imm = SplatBits >> 16;
4688       break;
4689     }
4690
4691     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4692     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4693     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4694     // and fall through here to test for a valid 64-bit splat.  But, then the
4695     // caller would also need to check and handle the change in size.
4696     return SDValue();
4697
4698   case 64: {
4699     if (type != VMOVModImm)
4700       return SDValue();
4701     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4702     uint64_t BitMask = 0xff;
4703     uint64_t Val = 0;
4704     unsigned ImmMask = 1;
4705     Imm = 0;
4706     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4707       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4708         Val |= BitMask;
4709         Imm |= ImmMask;
4710       } else if ((SplatBits & BitMask) != 0) {
4711         return SDValue();
4712       }
4713       BitMask <<= 8;
4714       ImmMask <<= 1;
4715     }
4716
4717     if (DAG.getTargetLoweringInfo().isBigEndian())
4718       // swap higher and lower 32 bit word
4719       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4720
4721     // Op=1, Cmode=1110.
4722     OpCmode = 0x1e;
4723     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4724     break;
4725   }
4726
4727   default:
4728     llvm_unreachable("unexpected size for isNEONModifiedImm");
4729   }
4730
4731   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4732   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4733 }
4734
4735 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4736                                            const ARMSubtarget *ST) const {
4737   if (!ST->hasVFP3())
4738     return SDValue();
4739
4740   bool IsDouble = Op.getValueType() == MVT::f64;
4741   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4742
4743   // Use the default (constant pool) lowering for double constants when we have
4744   // an SP-only FPU
4745   if (IsDouble && Subtarget->isFPOnlySP())
4746     return SDValue();
4747
4748   // Try splatting with a VMOV.f32...
4749   APFloat FPVal = CFP->getValueAPF();
4750   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4751
4752   if (ImmVal != -1) {
4753     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4754       // We have code in place to select a valid ConstantFP already, no need to
4755       // do any mangling.
4756       return Op;
4757     }
4758
4759     // It's a float and we are trying to use NEON operations where
4760     // possible. Lower it to a splat followed by an extract.
4761     SDLoc DL(Op);
4762     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4763     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4764                                       NewVal);
4765     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4766                        DAG.getConstant(0, MVT::i32));
4767   }
4768
4769   // The rest of our options are NEON only, make sure that's allowed before
4770   // proceeding..
4771   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4772     return SDValue();
4773
4774   EVT VMovVT;
4775   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4776
4777   // It wouldn't really be worth bothering for doubles except for one very
4778   // important value, which does happen to match: 0.0. So make sure we don't do
4779   // anything stupid.
4780   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4781     return SDValue();
4782
4783   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4784   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4785                                      false, VMOVModImm);
4786   if (NewVal != SDValue()) {
4787     SDLoc DL(Op);
4788     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4789                                       NewVal);
4790     if (IsDouble)
4791       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4792
4793     // It's a float: cast and extract a vector element.
4794     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4795                                        VecConstant);
4796     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4797                        DAG.getConstant(0, MVT::i32));
4798   }
4799
4800   // Finally, try a VMVN.i32
4801   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4802                              false, VMVNModImm);
4803   if (NewVal != SDValue()) {
4804     SDLoc DL(Op);
4805     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4806
4807     if (IsDouble)
4808       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4809
4810     // It's a float: cast and extract a vector element.
4811     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4812                                        VecConstant);
4813     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4814                        DAG.getConstant(0, MVT::i32));
4815   }
4816
4817   return SDValue();
4818 }
4819
4820 // check if an VEXT instruction can handle the shuffle mask when the
4821 // vector sources of the shuffle are the same.
4822 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4823   unsigned NumElts = VT.getVectorNumElements();
4824
4825   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4826   if (M[0] < 0)
4827     return false;
4828
4829   Imm = M[0];
4830
4831   // If this is a VEXT shuffle, the immediate value is the index of the first
4832   // element.  The other shuffle indices must be the successive elements after
4833   // the first one.
4834   unsigned ExpectedElt = Imm;
4835   for (unsigned i = 1; i < NumElts; ++i) {
4836     // Increment the expected index.  If it wraps around, just follow it
4837     // back to index zero and keep going.
4838     ++ExpectedElt;
4839     if (ExpectedElt == NumElts)
4840       ExpectedElt = 0;
4841
4842     if (M[i] < 0) continue; // ignore UNDEF indices
4843     if (ExpectedElt != static_cast<unsigned>(M[i]))
4844       return false;
4845   }
4846
4847   return true;
4848 }
4849
4850
4851 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4852                        bool &ReverseVEXT, unsigned &Imm) {
4853   unsigned NumElts = VT.getVectorNumElements();
4854   ReverseVEXT = false;
4855
4856   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4857   if (M[0] < 0)
4858     return false;
4859
4860   Imm = M[0];
4861
4862   // If this is a VEXT shuffle, the immediate value is the index of the first
4863   // element.  The other shuffle indices must be the successive elements after
4864   // the first one.
4865   unsigned ExpectedElt = Imm;
4866   for (unsigned i = 1; i < NumElts; ++i) {
4867     // Increment the expected index.  If it wraps around, it may still be
4868     // a VEXT but the source vectors must be swapped.
4869     ExpectedElt += 1;
4870     if (ExpectedElt == NumElts * 2) {
4871       ExpectedElt = 0;
4872       ReverseVEXT = true;
4873     }
4874
4875     if (M[i] < 0) continue; // ignore UNDEF indices
4876     if (ExpectedElt != static_cast<unsigned>(M[i]))
4877       return false;
4878   }
4879
4880   // Adjust the index value if the source operands will be swapped.
4881   if (ReverseVEXT)
4882     Imm -= NumElts;
4883
4884   return true;
4885 }
4886
4887 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4888 /// instruction with the specified blocksize.  (The order of the elements
4889 /// within each block of the vector is reversed.)
4890 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4891   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4892          "Only possible block sizes for VREV are: 16, 32, 64");
4893
4894   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4895   if (EltSz == 64)
4896     return false;
4897
4898   unsigned NumElts = VT.getVectorNumElements();
4899   unsigned BlockElts = M[0] + 1;
4900   // If the first shuffle index is UNDEF, be optimistic.
4901   if (M[0] < 0)
4902     BlockElts = BlockSize / EltSz;
4903
4904   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4905     return false;
4906
4907   for (unsigned i = 0; i < NumElts; ++i) {
4908     if (M[i] < 0) continue; // ignore UNDEF indices
4909     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4910       return false;
4911   }
4912
4913   return true;
4914 }
4915
4916 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4917   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4918   // range, then 0 is placed into the resulting vector. So pretty much any mask
4919   // of 8 elements can work here.
4920   return VT == MVT::v8i8 && M.size() == 8;
4921 }
4922
4923 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4924   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4925   if (EltSz == 64)
4926     return false;
4927
4928   unsigned NumElts = VT.getVectorNumElements();
4929   WhichResult = (M[0] == 0 ? 0 : 1);
4930   for (unsigned i = 0; i < NumElts; i += 2) {
4931     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4932         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4933       return false;
4934   }
4935   return true;
4936 }
4937
4938 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4939 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4940 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4941 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4942   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4943   if (EltSz == 64)
4944     return false;
4945
4946   unsigned NumElts = VT.getVectorNumElements();
4947   WhichResult = (M[0] == 0 ? 0 : 1);
4948   for (unsigned i = 0; i < NumElts; i += 2) {
4949     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4950         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4951       return false;
4952   }
4953   return true;
4954 }
4955
4956 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4957   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4958   if (EltSz == 64)
4959     return false;
4960
4961   unsigned NumElts = VT.getVectorNumElements();
4962   WhichResult = (M[0] == 0 ? 0 : 1);
4963   for (unsigned i = 0; i != NumElts; ++i) {
4964     if (M[i] < 0) continue; // ignore UNDEF indices
4965     if ((unsigned) M[i] != 2 * i + WhichResult)
4966       return false;
4967   }
4968
4969   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4970   if (VT.is64BitVector() && EltSz == 32)
4971     return false;
4972
4973   return true;
4974 }
4975
4976 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4977 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4978 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4979 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4980   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4981   if (EltSz == 64)
4982     return false;
4983
4984   unsigned Half = VT.getVectorNumElements() / 2;
4985   WhichResult = (M[0] == 0 ? 0 : 1);
4986   for (unsigned j = 0; j != 2; ++j) {
4987     unsigned Idx = WhichResult;
4988     for (unsigned i = 0; i != Half; ++i) {
4989       int MIdx = M[i + j * Half];
4990       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4991         return false;
4992       Idx += 2;
4993     }
4994   }
4995
4996   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4997   if (VT.is64BitVector() && EltSz == 32)
4998     return false;
4999
5000   return true;
5001 }
5002
5003 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5004   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5005   if (EltSz == 64)
5006     return false;
5007
5008   unsigned NumElts = VT.getVectorNumElements();
5009   WhichResult = (M[0] == 0 ? 0 : 1);
5010   unsigned Idx = WhichResult * NumElts / 2;
5011   for (unsigned i = 0; i != NumElts; i += 2) {
5012     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5013         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5014       return false;
5015     Idx += 1;
5016   }
5017
5018   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5019   if (VT.is64BitVector() && EltSz == 32)
5020     return false;
5021
5022   return true;
5023 }
5024
5025 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5026 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5027 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5028 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5029   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5030   if (EltSz == 64)
5031     return false;
5032
5033   unsigned NumElts = VT.getVectorNumElements();
5034   WhichResult = (M[0] == 0 ? 0 : 1);
5035   unsigned Idx = WhichResult * NumElts / 2;
5036   for (unsigned i = 0; i != NumElts; i += 2) {
5037     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5038         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5039       return false;
5040     Idx += 1;
5041   }
5042
5043   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5044   if (VT.is64BitVector() && EltSz == 32)
5045     return false;
5046
5047   return true;
5048 }
5049
5050 /// \return true if this is a reverse operation on an vector.
5051 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5052   unsigned NumElts = VT.getVectorNumElements();
5053   // Make sure the mask has the right size.
5054   if (NumElts != M.size())
5055       return false;
5056
5057   // Look for <15, ..., 3, -1, 1, 0>.
5058   for (unsigned i = 0; i != NumElts; ++i)
5059     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5060       return false;
5061
5062   return true;
5063 }
5064
5065 // If N is an integer constant that can be moved into a register in one
5066 // instruction, return an SDValue of such a constant (will become a MOV
5067 // instruction).  Otherwise return null.
5068 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5069                                      const ARMSubtarget *ST, SDLoc dl) {
5070   uint64_t Val;
5071   if (!isa<ConstantSDNode>(N))
5072     return SDValue();
5073   Val = cast<ConstantSDNode>(N)->getZExtValue();
5074
5075   if (ST->isThumb1Only()) {
5076     if (Val <= 255 || ~Val <= 255)
5077       return DAG.getConstant(Val, MVT::i32);
5078   } else {
5079     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5080       return DAG.getConstant(Val, MVT::i32);
5081   }
5082   return SDValue();
5083 }
5084
5085 // If this is a case we can't handle, return null and let the default
5086 // expansion code take care of it.
5087 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5088                                              const ARMSubtarget *ST) const {
5089   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5090   SDLoc dl(Op);
5091   EVT VT = Op.getValueType();
5092
5093   APInt SplatBits, SplatUndef;
5094   unsigned SplatBitSize;
5095   bool HasAnyUndefs;
5096   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5097     if (SplatBitSize <= 64) {
5098       // Check if an immediate VMOV works.
5099       EVT VmovVT;
5100       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5101                                       SplatUndef.getZExtValue(), SplatBitSize,
5102                                       DAG, VmovVT, VT.is128BitVector(),
5103                                       VMOVModImm);
5104       if (Val.getNode()) {
5105         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5106         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5107       }
5108
5109       // Try an immediate VMVN.
5110       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5111       Val = isNEONModifiedImm(NegatedImm,
5112                                       SplatUndef.getZExtValue(), SplatBitSize,
5113                                       DAG, VmovVT, VT.is128BitVector(),
5114                                       VMVNModImm);
5115       if (Val.getNode()) {
5116         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5117         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5118       }
5119
5120       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5121       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5122         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5123         if (ImmVal != -1) {
5124           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5125           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5126         }
5127       }
5128     }
5129   }
5130
5131   // Scan through the operands to see if only one value is used.
5132   //
5133   // As an optimisation, even if more than one value is used it may be more
5134   // profitable to splat with one value then change some lanes.
5135   //
5136   // Heuristically we decide to do this if the vector has a "dominant" value,
5137   // defined as splatted to more than half of the lanes.
5138   unsigned NumElts = VT.getVectorNumElements();
5139   bool isOnlyLowElement = true;
5140   bool usesOnlyOneValue = true;
5141   bool hasDominantValue = false;
5142   bool isConstant = true;
5143
5144   // Map of the number of times a particular SDValue appears in the
5145   // element list.
5146   DenseMap<SDValue, unsigned> ValueCounts;
5147   SDValue Value;
5148   for (unsigned i = 0; i < NumElts; ++i) {
5149     SDValue V = Op.getOperand(i);
5150     if (V.getOpcode() == ISD::UNDEF)
5151       continue;
5152     if (i > 0)
5153       isOnlyLowElement = false;
5154     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5155       isConstant = false;
5156
5157     ValueCounts.insert(std::make_pair(V, 0));
5158     unsigned &Count = ValueCounts[V];
5159
5160     // Is this value dominant? (takes up more than half of the lanes)
5161     if (++Count > (NumElts / 2)) {
5162       hasDominantValue = true;
5163       Value = V;
5164     }
5165   }
5166   if (ValueCounts.size() != 1)
5167     usesOnlyOneValue = false;
5168   if (!Value.getNode() && ValueCounts.size() > 0)
5169     Value = ValueCounts.begin()->first;
5170
5171   if (ValueCounts.size() == 0)
5172     return DAG.getUNDEF(VT);
5173
5174   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5175   // Keep going if we are hitting this case.
5176   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5177     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5178
5179   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5180
5181   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5182   // i32 and try again.
5183   if (hasDominantValue && EltSize <= 32) {
5184     if (!isConstant) {
5185       SDValue N;
5186
5187       // If we are VDUPing a value that comes directly from a vector, that will
5188       // cause an unnecessary move to and from a GPR, where instead we could
5189       // just use VDUPLANE. We can only do this if the lane being extracted
5190       // is at a constant index, as the VDUP from lane instructions only have
5191       // constant-index forms.
5192       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5193           isa<ConstantSDNode>(Value->getOperand(1))) {
5194         // We need to create a new undef vector to use for the VDUPLANE if the
5195         // size of the vector from which we get the value is different than the
5196         // size of the vector that we need to create. We will insert the element
5197         // such that the register coalescer will remove unnecessary copies.
5198         if (VT != Value->getOperand(0).getValueType()) {
5199           ConstantSDNode *constIndex;
5200           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5201           assert(constIndex && "The index is not a constant!");
5202           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5203                              VT.getVectorNumElements();
5204           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5205                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5206                         Value, DAG.getConstant(index, MVT::i32)),
5207                            DAG.getConstant(index, MVT::i32));
5208         } else
5209           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5210                         Value->getOperand(0), Value->getOperand(1));
5211       } else
5212         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5213
5214       if (!usesOnlyOneValue) {
5215         // The dominant value was splatted as 'N', but we now have to insert
5216         // all differing elements.
5217         for (unsigned I = 0; I < NumElts; ++I) {
5218           if (Op.getOperand(I) == Value)
5219             continue;
5220           SmallVector<SDValue, 3> Ops;
5221           Ops.push_back(N);
5222           Ops.push_back(Op.getOperand(I));
5223           Ops.push_back(DAG.getConstant(I, MVT::i32));
5224           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5225         }
5226       }
5227       return N;
5228     }
5229     if (VT.getVectorElementType().isFloatingPoint()) {
5230       SmallVector<SDValue, 8> Ops;
5231       for (unsigned i = 0; i < NumElts; ++i)
5232         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5233                                   Op.getOperand(i)));
5234       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5235       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5236       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5237       if (Val.getNode())
5238         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5239     }
5240     if (usesOnlyOneValue) {
5241       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5242       if (isConstant && Val.getNode())
5243         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5244     }
5245   }
5246
5247   // If all elements are constants and the case above didn't get hit, fall back
5248   // to the default expansion, which will generate a load from the constant
5249   // pool.
5250   if (isConstant)
5251     return SDValue();
5252
5253   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5254   if (NumElts >= 4) {
5255     SDValue shuffle = ReconstructShuffle(Op, DAG);
5256     if (shuffle != SDValue())
5257       return shuffle;
5258   }
5259
5260   // Vectors with 32- or 64-bit elements can be built by directly assigning
5261   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5262   // will be legalized.
5263   if (EltSize >= 32) {
5264     // Do the expansion with floating-point types, since that is what the VFP
5265     // registers are defined to use, and since i64 is not legal.
5266     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5267     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5268     SmallVector<SDValue, 8> Ops;
5269     for (unsigned i = 0; i < NumElts; ++i)
5270       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5271     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5272     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5273   }
5274
5275   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5276   // know the default expansion would otherwise fall back on something even
5277   // worse. For a vector with one or two non-undef values, that's
5278   // scalar_to_vector for the elements followed by a shuffle (provided the
5279   // shuffle is valid for the target) and materialization element by element
5280   // on the stack followed by a load for everything else.
5281   if (!isConstant && !usesOnlyOneValue) {
5282     SDValue Vec = DAG.getUNDEF(VT);
5283     for (unsigned i = 0 ; i < NumElts; ++i) {
5284       SDValue V = Op.getOperand(i);
5285       if (V.getOpcode() == ISD::UNDEF)
5286         continue;
5287       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5288       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5289     }
5290     return Vec;
5291   }
5292
5293   return SDValue();
5294 }
5295
5296 // Gather data to see if the operation can be modelled as a
5297 // shuffle in combination with VEXTs.
5298 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5299                                               SelectionDAG &DAG) const {
5300   SDLoc dl(Op);
5301   EVT VT = Op.getValueType();
5302   unsigned NumElts = VT.getVectorNumElements();
5303
5304   SmallVector<SDValue, 2> SourceVecs;
5305   SmallVector<unsigned, 2> MinElts;
5306   SmallVector<unsigned, 2> MaxElts;
5307
5308   for (unsigned i = 0; i < NumElts; ++i) {
5309     SDValue V = Op.getOperand(i);
5310     if (V.getOpcode() == ISD::UNDEF)
5311       continue;
5312     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5313       // A shuffle can only come from building a vector from various
5314       // elements of other vectors.
5315       return SDValue();
5316     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5317                VT.getVectorElementType()) {
5318       // This code doesn't know how to handle shuffles where the vector
5319       // element types do not match (this happens because type legalization
5320       // promotes the return type of EXTRACT_VECTOR_ELT).
5321       // FIXME: It might be appropriate to extend this code to handle
5322       // mismatched types.
5323       return SDValue();
5324     }
5325
5326     // Record this extraction against the appropriate vector if possible...
5327     SDValue SourceVec = V.getOperand(0);
5328     // If the element number isn't a constant, we can't effectively
5329     // analyze what's going on.
5330     if (!isa<ConstantSDNode>(V.getOperand(1)))
5331       return SDValue();
5332     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5333     bool FoundSource = false;
5334     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5335       if (SourceVecs[j] == SourceVec) {
5336         if (MinElts[j] > EltNo)
5337           MinElts[j] = EltNo;
5338         if (MaxElts[j] < EltNo)
5339           MaxElts[j] = EltNo;
5340         FoundSource = true;
5341         break;
5342       }
5343     }
5344
5345     // Or record a new source if not...
5346     if (!FoundSource) {
5347       SourceVecs.push_back(SourceVec);
5348       MinElts.push_back(EltNo);
5349       MaxElts.push_back(EltNo);
5350     }
5351   }
5352
5353   // Currently only do something sane when at most two source vectors
5354   // involved.
5355   if (SourceVecs.size() > 2)
5356     return SDValue();
5357
5358   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5359   int VEXTOffsets[2] = {0, 0};
5360
5361   // This loop extracts the usage patterns of the source vectors
5362   // and prepares appropriate SDValues for a shuffle if possible.
5363   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5364     if (SourceVecs[i].getValueType() == VT) {
5365       // No VEXT necessary
5366       ShuffleSrcs[i] = SourceVecs[i];
5367       VEXTOffsets[i] = 0;
5368       continue;
5369     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5370       // It probably isn't worth padding out a smaller vector just to
5371       // break it down again in a shuffle.
5372       return SDValue();
5373     }
5374
5375     // Since only 64-bit and 128-bit vectors are legal on ARM and
5376     // we've eliminated the other cases...
5377     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5378            "unexpected vector sizes in ReconstructShuffle");
5379
5380     if (MaxElts[i] - MinElts[i] >= NumElts) {
5381       // Span too large for a VEXT to cope
5382       return SDValue();
5383     }
5384
5385     if (MinElts[i] >= NumElts) {
5386       // The extraction can just take the second half
5387       VEXTOffsets[i] = NumElts;
5388       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5389                                    SourceVecs[i],
5390                                    DAG.getIntPtrConstant(NumElts));
5391     } else if (MaxElts[i] < NumElts) {
5392       // The extraction can just take the first half
5393       VEXTOffsets[i] = 0;
5394       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5395                                    SourceVecs[i],
5396                                    DAG.getIntPtrConstant(0));
5397     } else {
5398       // An actual VEXT is needed
5399       VEXTOffsets[i] = MinElts[i];
5400       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5401                                      SourceVecs[i],
5402                                      DAG.getIntPtrConstant(0));
5403       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5404                                      SourceVecs[i],
5405                                      DAG.getIntPtrConstant(NumElts));
5406       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5407                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5408     }
5409   }
5410
5411   SmallVector<int, 8> Mask;
5412
5413   for (unsigned i = 0; i < NumElts; ++i) {
5414     SDValue Entry = Op.getOperand(i);
5415     if (Entry.getOpcode() == ISD::UNDEF) {
5416       Mask.push_back(-1);
5417       continue;
5418     }
5419
5420     SDValue ExtractVec = Entry.getOperand(0);
5421     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5422                                           .getOperand(1))->getSExtValue();
5423     if (ExtractVec == SourceVecs[0]) {
5424       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5425     } else {
5426       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5427     }
5428   }
5429
5430   // Final check before we try to produce nonsense...
5431   if (isShuffleMaskLegal(Mask, VT))
5432     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5433                                 &Mask[0]);
5434
5435   return SDValue();
5436 }
5437
5438 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5439 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5440 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5441 /// are assumed to be legal.
5442 bool
5443 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5444                                       EVT VT) const {
5445   if (VT.getVectorNumElements() == 4 &&
5446       (VT.is128BitVector() || VT.is64BitVector())) {
5447     unsigned PFIndexes[4];
5448     for (unsigned i = 0; i != 4; ++i) {
5449       if (M[i] < 0)
5450         PFIndexes[i] = 8;
5451       else
5452         PFIndexes[i] = M[i];
5453     }
5454
5455     // Compute the index in the perfect shuffle table.
5456     unsigned PFTableIndex =
5457       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5458     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5459     unsigned Cost = (PFEntry >> 30);
5460
5461     if (Cost <= 4)
5462       return true;
5463   }
5464
5465   bool ReverseVEXT;
5466   unsigned Imm, WhichResult;
5467
5468   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5469   return (EltSize >= 32 ||
5470           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5471           isVREVMask(M, VT, 64) ||
5472           isVREVMask(M, VT, 32) ||
5473           isVREVMask(M, VT, 16) ||
5474           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5475           isVTBLMask(M, VT) ||
5476           isVTRNMask(M, VT, WhichResult) ||
5477           isVUZPMask(M, VT, WhichResult) ||
5478           isVZIPMask(M, VT, WhichResult) ||
5479           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5480           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5481           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5482           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5483 }
5484
5485 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5486 /// the specified operations to build the shuffle.
5487 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5488                                       SDValue RHS, SelectionDAG &DAG,
5489                                       SDLoc dl) {
5490   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5491   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5492   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5493
5494   enum {
5495     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5496     OP_VREV,
5497     OP_VDUP0,
5498     OP_VDUP1,
5499     OP_VDUP2,
5500     OP_VDUP3,
5501     OP_VEXT1,
5502     OP_VEXT2,
5503     OP_VEXT3,
5504     OP_VUZPL, // VUZP, left result
5505     OP_VUZPR, // VUZP, right result
5506     OP_VZIPL, // VZIP, left result
5507     OP_VZIPR, // VZIP, right result
5508     OP_VTRNL, // VTRN, left result
5509     OP_VTRNR  // VTRN, right result
5510   };
5511
5512   if (OpNum == OP_COPY) {
5513     if (LHSID == (1*9+2)*9+3) return LHS;
5514     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5515     return RHS;
5516   }
5517
5518   SDValue OpLHS, OpRHS;
5519   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5520   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5521   EVT VT = OpLHS.getValueType();
5522
5523   switch (OpNum) {
5524   default: llvm_unreachable("Unknown shuffle opcode!");
5525   case OP_VREV:
5526     // VREV divides the vector in half and swaps within the half.
5527     if (VT.getVectorElementType() == MVT::i32 ||
5528         VT.getVectorElementType() == MVT::f32)
5529       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5530     // vrev <4 x i16> -> VREV32
5531     if (VT.getVectorElementType() == MVT::i16)
5532       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5533     // vrev <4 x i8> -> VREV16
5534     assert(VT.getVectorElementType() == MVT::i8);
5535     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5536   case OP_VDUP0:
5537   case OP_VDUP1:
5538   case OP_VDUP2:
5539   case OP_VDUP3:
5540     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5541                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5542   case OP_VEXT1:
5543   case OP_VEXT2:
5544   case OP_VEXT3:
5545     return DAG.getNode(ARMISD::VEXT, dl, VT,
5546                        OpLHS, OpRHS,
5547                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5548   case OP_VUZPL:
5549   case OP_VUZPR:
5550     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5551                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5552   case OP_VZIPL:
5553   case OP_VZIPR:
5554     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5555                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5556   case OP_VTRNL:
5557   case OP_VTRNR:
5558     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5559                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5560   }
5561 }
5562
5563 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5564                                        ArrayRef<int> ShuffleMask,
5565                                        SelectionDAG &DAG) {
5566   // Check to see if we can use the VTBL instruction.
5567   SDValue V1 = Op.getOperand(0);
5568   SDValue V2 = Op.getOperand(1);
5569   SDLoc DL(Op);
5570
5571   SmallVector<SDValue, 8> VTBLMask;
5572   for (ArrayRef<int>::iterator
5573          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5574     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5575
5576   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5577     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5578                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5579
5580   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5581                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5582 }
5583
5584 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5585                                                       SelectionDAG &DAG) {
5586   SDLoc DL(Op);
5587   SDValue OpLHS = Op.getOperand(0);
5588   EVT VT = OpLHS.getValueType();
5589
5590   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5591          "Expect an v8i16/v16i8 type");
5592   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5593   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5594   // extract the first 8 bytes into the top double word and the last 8 bytes
5595   // into the bottom double word. The v8i16 case is similar.
5596   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5597   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5598                      DAG.getConstant(ExtractNum, MVT::i32));
5599 }
5600
5601 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5602   SDValue V1 = Op.getOperand(0);
5603   SDValue V2 = Op.getOperand(1);
5604   SDLoc dl(Op);
5605   EVT VT = Op.getValueType();
5606   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5607
5608   // Convert shuffles that are directly supported on NEON to target-specific
5609   // DAG nodes, instead of keeping them as shuffles and matching them again
5610   // during code selection.  This is more efficient and avoids the possibility
5611   // of inconsistencies between legalization and selection.
5612   // FIXME: floating-point vectors should be canonicalized to integer vectors
5613   // of the same time so that they get CSEd properly.
5614   ArrayRef<int> ShuffleMask = SVN->getMask();
5615
5616   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5617   if (EltSize <= 32) {
5618     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5619       int Lane = SVN->getSplatIndex();
5620       // If this is undef splat, generate it via "just" vdup, if possible.
5621       if (Lane == -1) Lane = 0;
5622
5623       // Test if V1 is a SCALAR_TO_VECTOR.
5624       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5625         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5626       }
5627       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5628       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5629       // reaches it).
5630       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5631           !isa<ConstantSDNode>(V1.getOperand(0))) {
5632         bool IsScalarToVector = true;
5633         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5634           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5635             IsScalarToVector = false;
5636             break;
5637           }
5638         if (IsScalarToVector)
5639           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5640       }
5641       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5642                          DAG.getConstant(Lane, MVT::i32));
5643     }
5644
5645     bool ReverseVEXT;
5646     unsigned Imm;
5647     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5648       if (ReverseVEXT)
5649         std::swap(V1, V2);
5650       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5651                          DAG.getConstant(Imm, MVT::i32));
5652     }
5653
5654     if (isVREVMask(ShuffleMask, VT, 64))
5655       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5656     if (isVREVMask(ShuffleMask, VT, 32))
5657       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5658     if (isVREVMask(ShuffleMask, VT, 16))
5659       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5660
5661     if (V2->getOpcode() == ISD::UNDEF &&
5662         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5663       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5664                          DAG.getConstant(Imm, MVT::i32));
5665     }
5666
5667     // Check for Neon shuffles that modify both input vectors in place.
5668     // If both results are used, i.e., if there are two shuffles with the same
5669     // source operands and with masks corresponding to both results of one of
5670     // these operations, DAG memoization will ensure that a single node is
5671     // used for both shuffles.
5672     unsigned WhichResult;
5673     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5674       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5675                          V1, V2).getValue(WhichResult);
5676     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5677       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5678                          V1, V2).getValue(WhichResult);
5679     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5680       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5681                          V1, V2).getValue(WhichResult);
5682
5683     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5684       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5685                          V1, V1).getValue(WhichResult);
5686     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5687       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5688                          V1, V1).getValue(WhichResult);
5689     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5690       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5691                          V1, V1).getValue(WhichResult);
5692   }
5693
5694   // If the shuffle is not directly supported and it has 4 elements, use
5695   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5696   unsigned NumElts = VT.getVectorNumElements();
5697   if (NumElts == 4) {
5698     unsigned PFIndexes[4];
5699     for (unsigned i = 0; i != 4; ++i) {
5700       if (ShuffleMask[i] < 0)
5701         PFIndexes[i] = 8;
5702       else
5703         PFIndexes[i] = ShuffleMask[i];
5704     }
5705
5706     // Compute the index in the perfect shuffle table.
5707     unsigned PFTableIndex =
5708       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5709     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5710     unsigned Cost = (PFEntry >> 30);
5711
5712     if (Cost <= 4)
5713       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5714   }
5715
5716   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5717   if (EltSize >= 32) {
5718     // Do the expansion with floating-point types, since that is what the VFP
5719     // registers are defined to use, and since i64 is not legal.
5720     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5721     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5722     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5723     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5724     SmallVector<SDValue, 8> Ops;
5725     for (unsigned i = 0; i < NumElts; ++i) {
5726       if (ShuffleMask[i] < 0)
5727         Ops.push_back(DAG.getUNDEF(EltVT));
5728       else
5729         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5730                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5731                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5732                                                   MVT::i32)));
5733     }
5734     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5735     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5736   }
5737
5738   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5739     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5740
5741   if (VT == MVT::v8i8) {
5742     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5743     if (NewOp.getNode())
5744       return NewOp;
5745   }
5746
5747   return SDValue();
5748 }
5749
5750 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5751   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5752   SDValue Lane = Op.getOperand(2);
5753   if (!isa<ConstantSDNode>(Lane))
5754     return SDValue();
5755
5756   return Op;
5757 }
5758
5759 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5760   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5761   SDValue Lane = Op.getOperand(1);
5762   if (!isa<ConstantSDNode>(Lane))
5763     return SDValue();
5764
5765   SDValue Vec = Op.getOperand(0);
5766   if (Op.getValueType() == MVT::i32 &&
5767       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5768     SDLoc dl(Op);
5769     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5770   }
5771
5772   return Op;
5773 }
5774
5775 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5776   // The only time a CONCAT_VECTORS operation can have legal types is when
5777   // two 64-bit vectors are concatenated to a 128-bit vector.
5778   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5779          "unexpected CONCAT_VECTORS");
5780   SDLoc dl(Op);
5781   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5782   SDValue Op0 = Op.getOperand(0);
5783   SDValue Op1 = Op.getOperand(1);
5784   if (Op0.getOpcode() != ISD::UNDEF)
5785     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5786                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5787                       DAG.getIntPtrConstant(0));
5788   if (Op1.getOpcode() != ISD::UNDEF)
5789     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5790                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5791                       DAG.getIntPtrConstant(1));
5792   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5793 }
5794
5795 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5796 /// element has been zero/sign-extended, depending on the isSigned parameter,
5797 /// from an integer type half its size.
5798 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5799                                    bool isSigned) {
5800   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5801   EVT VT = N->getValueType(0);
5802   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5803     SDNode *BVN = N->getOperand(0).getNode();
5804     if (BVN->getValueType(0) != MVT::v4i32 ||
5805         BVN->getOpcode() != ISD::BUILD_VECTOR)
5806       return false;
5807     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5808     unsigned HiElt = 1 - LoElt;
5809     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5810     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5811     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5812     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5813     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5814       return false;
5815     if (isSigned) {
5816       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5817           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5818         return true;
5819     } else {
5820       if (Hi0->isNullValue() && Hi1->isNullValue())
5821         return true;
5822     }
5823     return false;
5824   }
5825
5826   if (N->getOpcode() != ISD::BUILD_VECTOR)
5827     return false;
5828
5829   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5830     SDNode *Elt = N->getOperand(i).getNode();
5831     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5832       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5833       unsigned HalfSize = EltSize / 2;
5834       if (isSigned) {
5835         if (!isIntN(HalfSize, C->getSExtValue()))
5836           return false;
5837       } else {
5838         if (!isUIntN(HalfSize, C->getZExtValue()))
5839           return false;
5840       }
5841       continue;
5842     }
5843     return false;
5844   }
5845
5846   return true;
5847 }
5848
5849 /// isSignExtended - Check if a node is a vector value that is sign-extended
5850 /// or a constant BUILD_VECTOR with sign-extended elements.
5851 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5852   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5853     return true;
5854   if (isExtendedBUILD_VECTOR(N, DAG, true))
5855     return true;
5856   return false;
5857 }
5858
5859 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5860 /// or a constant BUILD_VECTOR with zero-extended elements.
5861 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5862   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5863     return true;
5864   if (isExtendedBUILD_VECTOR(N, DAG, false))
5865     return true;
5866   return false;
5867 }
5868
5869 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5870   if (OrigVT.getSizeInBits() >= 64)
5871     return OrigVT;
5872
5873   assert(OrigVT.isSimple() && "Expecting a simple value type");
5874
5875   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5876   switch (OrigSimpleTy) {
5877   default: llvm_unreachable("Unexpected Vector Type");
5878   case MVT::v2i8:
5879   case MVT::v2i16:
5880      return MVT::v2i32;
5881   case MVT::v4i8:
5882     return  MVT::v4i16;
5883   }
5884 }
5885
5886 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5887 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5888 /// We insert the required extension here to get the vector to fill a D register.
5889 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5890                                             const EVT &OrigTy,
5891                                             const EVT &ExtTy,
5892                                             unsigned ExtOpcode) {
5893   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5894   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5895   // 64-bits we need to insert a new extension so that it will be 64-bits.
5896   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5897   if (OrigTy.getSizeInBits() >= 64)
5898     return N;
5899
5900   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5901   EVT NewVT = getExtensionTo64Bits(OrigTy);
5902
5903   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5904 }
5905
5906 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5907 /// does not do any sign/zero extension. If the original vector is less
5908 /// than 64 bits, an appropriate extension will be added after the load to
5909 /// reach a total size of 64 bits. We have to add the extension separately
5910 /// because ARM does not have a sign/zero extending load for vectors.
5911 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5912   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5913
5914   // The load already has the right type.
5915   if (ExtendedTy == LD->getMemoryVT())
5916     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5917                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5918                 LD->isNonTemporal(), LD->isInvariant(),
5919                 LD->getAlignment());
5920
5921   // We need to create a zextload/sextload. We cannot just create a load
5922   // followed by a zext/zext node because LowerMUL is also run during normal
5923   // operation legalization where we can't create illegal types.
5924   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5925                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5926                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5927                         LD->isNonTemporal(), LD->getAlignment());
5928 }
5929
5930 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5931 /// extending load, or BUILD_VECTOR with extended elements, return the
5932 /// unextended value. The unextended vector should be 64 bits so that it can
5933 /// be used as an operand to a VMULL instruction. If the original vector size
5934 /// before extension is less than 64 bits we add a an extension to resize
5935 /// the vector to 64 bits.
5936 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5937   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5938     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5939                                         N->getOperand(0)->getValueType(0),
5940                                         N->getValueType(0),
5941                                         N->getOpcode());
5942
5943   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5944     return SkipLoadExtensionForVMULL(LD, DAG);
5945
5946   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5947   // have been legalized as a BITCAST from v4i32.
5948   if (N->getOpcode() == ISD::BITCAST) {
5949     SDNode *BVN = N->getOperand(0).getNode();
5950     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5951            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5952     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5953     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5954                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5955   }
5956   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5957   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5958   EVT VT = N->getValueType(0);
5959   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5960   unsigned NumElts = VT.getVectorNumElements();
5961   MVT TruncVT = MVT::getIntegerVT(EltSize);
5962   SmallVector<SDValue, 8> Ops;
5963   for (unsigned i = 0; i != NumElts; ++i) {
5964     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5965     const APInt &CInt = C->getAPIntValue();
5966     // Element types smaller than 32 bits are not legal, so use i32 elements.
5967     // The values are implicitly truncated so sext vs. zext doesn't matter.
5968     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5969   }
5970   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5971                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5972 }
5973
5974 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5975   unsigned Opcode = N->getOpcode();
5976   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5977     SDNode *N0 = N->getOperand(0).getNode();
5978     SDNode *N1 = N->getOperand(1).getNode();
5979     return N0->hasOneUse() && N1->hasOneUse() &&
5980       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5981   }
5982   return false;
5983 }
5984
5985 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5986   unsigned Opcode = N->getOpcode();
5987   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5988     SDNode *N0 = N->getOperand(0).getNode();
5989     SDNode *N1 = N->getOperand(1).getNode();
5990     return N0->hasOneUse() && N1->hasOneUse() &&
5991       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5992   }
5993   return false;
5994 }
5995
5996 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5997   // Multiplications are only custom-lowered for 128-bit vectors so that
5998   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5999   EVT VT = Op.getValueType();
6000   assert(VT.is128BitVector() && VT.isInteger() &&
6001          "unexpected type for custom-lowering ISD::MUL");
6002   SDNode *N0 = Op.getOperand(0).getNode();
6003   SDNode *N1 = Op.getOperand(1).getNode();
6004   unsigned NewOpc = 0;
6005   bool isMLA = false;
6006   bool isN0SExt = isSignExtended(N0, DAG);
6007   bool isN1SExt = isSignExtended(N1, DAG);
6008   if (isN0SExt && isN1SExt)
6009     NewOpc = ARMISD::VMULLs;
6010   else {
6011     bool isN0ZExt = isZeroExtended(N0, DAG);
6012     bool isN1ZExt = isZeroExtended(N1, DAG);
6013     if (isN0ZExt && isN1ZExt)
6014       NewOpc = ARMISD::VMULLu;
6015     else if (isN1SExt || isN1ZExt) {
6016       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6017       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6018       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6019         NewOpc = ARMISD::VMULLs;
6020         isMLA = true;
6021       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6022         NewOpc = ARMISD::VMULLu;
6023         isMLA = true;
6024       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6025         std::swap(N0, N1);
6026         NewOpc = ARMISD::VMULLu;
6027         isMLA = true;
6028       }
6029     }
6030
6031     if (!NewOpc) {
6032       if (VT == MVT::v2i64)
6033         // Fall through to expand this.  It is not legal.
6034         return SDValue();
6035       else
6036         // Other vector multiplications are legal.
6037         return Op;
6038     }
6039   }
6040
6041   // Legalize to a VMULL instruction.
6042   SDLoc DL(Op);
6043   SDValue Op0;
6044   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6045   if (!isMLA) {
6046     Op0 = SkipExtensionForVMULL(N0, DAG);
6047     assert(Op0.getValueType().is64BitVector() &&
6048            Op1.getValueType().is64BitVector() &&
6049            "unexpected types for extended operands to VMULL");
6050     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6051   }
6052
6053   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6054   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6055   //   vmull q0, d4, d6
6056   //   vmlal q0, d5, d6
6057   // is faster than
6058   //   vaddl q0, d4, d5
6059   //   vmovl q1, d6
6060   //   vmul  q0, q0, q1
6061   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6062   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6063   EVT Op1VT = Op1.getValueType();
6064   return DAG.getNode(N0->getOpcode(), DL, VT,
6065                      DAG.getNode(NewOpc, DL, VT,
6066                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6067                      DAG.getNode(NewOpc, DL, VT,
6068                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6069 }
6070
6071 static SDValue
6072 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6073   // Convert to float
6074   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6075   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6076   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6077   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6078   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6079   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6080   // Get reciprocal estimate.
6081   // float4 recip = vrecpeq_f32(yf);
6082   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6083                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6084   // Because char has a smaller range than uchar, we can actually get away
6085   // without any newton steps.  This requires that we use a weird bias
6086   // of 0xb000, however (again, this has been exhaustively tested).
6087   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6088   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6089   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6090   Y = DAG.getConstant(0xb000, MVT::i32);
6091   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6092   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6093   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6094   // Convert back to short.
6095   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6096   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6097   return X;
6098 }
6099
6100 static SDValue
6101 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6102   SDValue N2;
6103   // Convert to float.
6104   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6105   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6106   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6107   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6108   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6109   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6110
6111   // Use reciprocal estimate and one refinement step.
6112   // float4 recip = vrecpeq_f32(yf);
6113   // recip *= vrecpsq_f32(yf, recip);
6114   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6115                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6116   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6117                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6118                    N1, N2);
6119   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6120   // Because short has a smaller range than ushort, we can actually get away
6121   // with only a single newton step.  This requires that we use a weird bias
6122   // of 89, however (again, this has been exhaustively tested).
6123   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6124   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6125   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6126   N1 = DAG.getConstant(0x89, MVT::i32);
6127   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6128   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6129   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6130   // Convert back to integer and return.
6131   // return vmovn_s32(vcvt_s32_f32(result));
6132   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6133   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6134   return N0;
6135 }
6136
6137 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6138   EVT VT = Op.getValueType();
6139   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6140          "unexpected type for custom-lowering ISD::SDIV");
6141
6142   SDLoc dl(Op);
6143   SDValue N0 = Op.getOperand(0);
6144   SDValue N1 = Op.getOperand(1);
6145   SDValue N2, N3;
6146
6147   if (VT == MVT::v8i8) {
6148     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6149     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6150
6151     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6152                      DAG.getIntPtrConstant(4));
6153     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6154                      DAG.getIntPtrConstant(4));
6155     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6156                      DAG.getIntPtrConstant(0));
6157     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6158                      DAG.getIntPtrConstant(0));
6159
6160     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6161     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6162
6163     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6164     N0 = LowerCONCAT_VECTORS(N0, DAG);
6165
6166     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6167     return N0;
6168   }
6169   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6170 }
6171
6172 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6173   EVT VT = Op.getValueType();
6174   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6175          "unexpected type for custom-lowering ISD::UDIV");
6176
6177   SDLoc dl(Op);
6178   SDValue N0 = Op.getOperand(0);
6179   SDValue N1 = Op.getOperand(1);
6180   SDValue N2, N3;
6181
6182   if (VT == MVT::v8i8) {
6183     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6184     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6185
6186     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6187                      DAG.getIntPtrConstant(4));
6188     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6189                      DAG.getIntPtrConstant(4));
6190     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6191                      DAG.getIntPtrConstant(0));
6192     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6193                      DAG.getIntPtrConstant(0));
6194
6195     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6196     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6197
6198     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6199     N0 = LowerCONCAT_VECTORS(N0, DAG);
6200
6201     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6202                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6203                      N0);
6204     return N0;
6205   }
6206
6207   // v4i16 sdiv ... Convert to float.
6208   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6209   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6210   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6211   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6212   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6213   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6214
6215   // Use reciprocal estimate and two refinement steps.
6216   // float4 recip = vrecpeq_f32(yf);
6217   // recip *= vrecpsq_f32(yf, recip);
6218   // recip *= vrecpsq_f32(yf, recip);
6219   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6220                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6221   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6222                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6223                    BN1, N2);
6224   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6225   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6226                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6227                    BN1, N2);
6228   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6229   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6230   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6231   // and that it will never cause us to return an answer too large).
6232   // float4 result = as_float4(as_int4(xf*recip) + 2);
6233   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6234   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6235   N1 = DAG.getConstant(2, MVT::i32);
6236   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6237   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6238   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6239   // Convert back to integer and return.
6240   // return vmovn_u32(vcvt_s32_f32(result));
6241   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6242   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6243   return N0;
6244 }
6245
6246 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6247   EVT VT = Op.getNode()->getValueType(0);
6248   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6249
6250   unsigned Opc;
6251   bool ExtraOp = false;
6252   switch (Op.getOpcode()) {
6253   default: llvm_unreachable("Invalid code");
6254   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6255   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6256   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6257   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6258   }
6259
6260   if (!ExtraOp)
6261     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6262                        Op.getOperand(1));
6263   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6264                      Op.getOperand(1), Op.getOperand(2));
6265 }
6266
6267 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6268   assert(Subtarget->isTargetDarwin());
6269
6270   // For iOS, we want to call an alternative entry point: __sincos_stret,
6271   // return values are passed via sret.
6272   SDLoc dl(Op);
6273   SDValue Arg = Op.getOperand(0);
6274   EVT ArgVT = Arg.getValueType();
6275   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6276
6277   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6279
6280   // Pair of floats / doubles used to pass the result.
6281   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6282
6283   // Create stack object for sret.
6284   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6285   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6286   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6287   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6288
6289   ArgListTy Args;
6290   ArgListEntry Entry;
6291
6292   Entry.Node = SRet;
6293   Entry.Ty = RetTy->getPointerTo();
6294   Entry.isSExt = false;
6295   Entry.isZExt = false;
6296   Entry.isSRet = true;
6297   Args.push_back(Entry);
6298
6299   Entry.Node = Arg;
6300   Entry.Ty = ArgTy;
6301   Entry.isSExt = false;
6302   Entry.isZExt = false;
6303   Args.push_back(Entry);
6304
6305   const char *LibcallName  = (ArgVT == MVT::f64)
6306   ? "__sincos_stret" : "__sincosf_stret";
6307   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6308
6309   TargetLowering::CallLoweringInfo CLI(DAG);
6310   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6311     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6312                std::move(Args), 0)
6313     .setDiscardResult();
6314
6315   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6316
6317   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6318                                 MachinePointerInfo(), false, false, false, 0);
6319
6320   // Address of cos field.
6321   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6322                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6323   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6324                                 MachinePointerInfo(), false, false, false, 0);
6325
6326   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6327   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6328                      LoadSin.getValue(0), LoadCos.getValue(0));
6329 }
6330
6331 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6332   // Monotonic load/store is legal for all targets
6333   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6334     return Op;
6335
6336   // Acquire/Release load/store is not legal for targets without a
6337   // dmb or equivalent available.
6338   return SDValue();
6339 }
6340
6341 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6342                                     SmallVectorImpl<SDValue> &Results,
6343                                     SelectionDAG &DAG,
6344                                     const ARMSubtarget *Subtarget) {
6345   SDLoc DL(N);
6346   SDValue Cycles32, OutChain;
6347
6348   if (Subtarget->hasPerfMon()) {
6349     // Under Power Management extensions, the cycle-count is:
6350     //    mrc p15, #0, <Rt>, c9, c13, #0
6351     SDValue Ops[] = { N->getOperand(0), // Chain
6352                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6353                       DAG.getConstant(15, MVT::i32),
6354                       DAG.getConstant(0, MVT::i32),
6355                       DAG.getConstant(9, MVT::i32),
6356                       DAG.getConstant(13, MVT::i32),
6357                       DAG.getConstant(0, MVT::i32)
6358     };
6359
6360     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6361                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6362     OutChain = Cycles32.getValue(1);
6363   } else {
6364     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6365     // there are older ARM CPUs that have implementation-specific ways of
6366     // obtaining this information (FIXME!).
6367     Cycles32 = DAG.getConstant(0, MVT::i32);
6368     OutChain = DAG.getEntryNode();
6369   }
6370
6371
6372   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6373                                  Cycles32, DAG.getConstant(0, MVT::i32));
6374   Results.push_back(Cycles64);
6375   Results.push_back(OutChain);
6376 }
6377
6378 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6379   switch (Op.getOpcode()) {
6380   default: llvm_unreachable("Don't know how to custom lower this!");
6381   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6382   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6383   case ISD::GlobalAddress:
6384     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6385     default: llvm_unreachable("unknown object format");
6386     case Triple::COFF:
6387       return LowerGlobalAddressWindows(Op, DAG);
6388     case Triple::ELF:
6389       return LowerGlobalAddressELF(Op, DAG);
6390     case Triple::MachO:
6391       return LowerGlobalAddressDarwin(Op, DAG);
6392     }
6393   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6394   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6395   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6396   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6397   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6398   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6399   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6400   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6401   case ISD::SINT_TO_FP:
6402   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6403   case ISD::FP_TO_SINT:
6404   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6405   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6406   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6407   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6408   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6409   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6410   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6411   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6412                                                                Subtarget);
6413   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6414   case ISD::SHL:
6415   case ISD::SRL:
6416   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6417   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6418   case ISD::SRL_PARTS:
6419   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6420   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6421   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6422   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6423   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6424   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6425   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6426   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6427   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6428   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6429   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6430   case ISD::MUL:           return LowerMUL(Op, DAG);
6431   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6432   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6433   case ISD::ADDC:
6434   case ISD::ADDE:
6435   case ISD::SUBC:
6436   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6437   case ISD::SADDO:
6438   case ISD::UADDO:
6439   case ISD::SSUBO:
6440   case ISD::USUBO:
6441     return LowerXALUO(Op, DAG);
6442   case ISD::ATOMIC_LOAD:
6443   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6444   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6445   case ISD::SDIVREM:
6446   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6447   case ISD::DYNAMIC_STACKALLOC:
6448     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6449       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6450     llvm_unreachable("Don't know how to custom lower this!");
6451   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6452   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6453   }
6454 }
6455
6456 /// ReplaceNodeResults - Replace the results of node with an illegal result
6457 /// type with new values built out of custom code.
6458 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6459                                            SmallVectorImpl<SDValue>&Results,
6460                                            SelectionDAG &DAG) const {
6461   SDValue Res;
6462   switch (N->getOpcode()) {
6463   default:
6464     llvm_unreachable("Don't know how to custom expand this!");
6465   case ISD::BITCAST:
6466     Res = ExpandBITCAST(N, DAG);
6467     break;
6468   case ISD::SRL:
6469   case ISD::SRA:
6470     Res = Expand64BitShift(N, DAG, Subtarget);
6471     break;
6472   case ISD::READCYCLECOUNTER:
6473     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6474     return;
6475   }
6476   if (Res.getNode())
6477     Results.push_back(Res);
6478 }
6479
6480 //===----------------------------------------------------------------------===//
6481 //                           ARM Scheduler Hooks
6482 //===----------------------------------------------------------------------===//
6483
6484 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6485 /// registers the function context.
6486 void ARMTargetLowering::
6487 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6488                        MachineBasicBlock *DispatchBB, int FI) const {
6489   const TargetInstrInfo *TII =
6490       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6491   DebugLoc dl = MI->getDebugLoc();
6492   MachineFunction *MF = MBB->getParent();
6493   MachineRegisterInfo *MRI = &MF->getRegInfo();
6494   MachineConstantPool *MCP = MF->getConstantPool();
6495   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6496   const Function *F = MF->getFunction();
6497
6498   bool isThumb = Subtarget->isThumb();
6499   bool isThumb2 = Subtarget->isThumb2();
6500
6501   unsigned PCLabelId = AFI->createPICLabelUId();
6502   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6503   ARMConstantPoolValue *CPV =
6504     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6505   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6506
6507   const TargetRegisterClass *TRC = isThumb ?
6508     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6509     (const TargetRegisterClass*)&ARM::GPRRegClass;
6510
6511   // Grab constant pool and fixed stack memory operands.
6512   MachineMemOperand *CPMMO =
6513     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6514                              MachineMemOperand::MOLoad, 4, 4);
6515
6516   MachineMemOperand *FIMMOSt =
6517     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6518                              MachineMemOperand::MOStore, 4, 4);
6519
6520   // Load the address of the dispatch MBB into the jump buffer.
6521   if (isThumb2) {
6522     // Incoming value: jbuf
6523     //   ldr.n  r5, LCPI1_1
6524     //   orr    r5, r5, #1
6525     //   add    r5, pc
6526     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6527     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6528     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6529                    .addConstantPoolIndex(CPI)
6530                    .addMemOperand(CPMMO));
6531     // Set the low bit because of thumb mode.
6532     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6533     AddDefaultCC(
6534       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6535                      .addReg(NewVReg1, RegState::Kill)
6536                      .addImm(0x01)));
6537     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6538     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6539       .addReg(NewVReg2, RegState::Kill)
6540       .addImm(PCLabelId);
6541     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6542                    .addReg(NewVReg3, RegState::Kill)
6543                    .addFrameIndex(FI)
6544                    .addImm(36)  // &jbuf[1] :: pc
6545                    .addMemOperand(FIMMOSt));
6546   } else if (isThumb) {
6547     // Incoming value: jbuf
6548     //   ldr.n  r1, LCPI1_4
6549     //   add    r1, pc
6550     //   mov    r2, #1
6551     //   orrs   r1, r2
6552     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6553     //   str    r1, [r2]
6554     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6555     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6556                    .addConstantPoolIndex(CPI)
6557                    .addMemOperand(CPMMO));
6558     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6559     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6560       .addReg(NewVReg1, RegState::Kill)
6561       .addImm(PCLabelId);
6562     // Set the low bit because of thumb mode.
6563     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6564     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6565                    .addReg(ARM::CPSR, RegState::Define)
6566                    .addImm(1));
6567     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6568     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6569                    .addReg(ARM::CPSR, RegState::Define)
6570                    .addReg(NewVReg2, RegState::Kill)
6571                    .addReg(NewVReg3, RegState::Kill));
6572     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6573     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6574                    .addFrameIndex(FI)
6575                    .addImm(36)); // &jbuf[1] :: pc
6576     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6577                    .addReg(NewVReg4, RegState::Kill)
6578                    .addReg(NewVReg5, RegState::Kill)
6579                    .addImm(0)
6580                    .addMemOperand(FIMMOSt));
6581   } else {
6582     // Incoming value: jbuf
6583     //   ldr  r1, LCPI1_1
6584     //   add  r1, pc, r1
6585     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6586     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6587     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6588                    .addConstantPoolIndex(CPI)
6589                    .addImm(0)
6590                    .addMemOperand(CPMMO));
6591     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6592     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6593                    .addReg(NewVReg1, RegState::Kill)
6594                    .addImm(PCLabelId));
6595     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6596                    .addReg(NewVReg2, RegState::Kill)
6597                    .addFrameIndex(FI)
6598                    .addImm(36)  // &jbuf[1] :: pc
6599                    .addMemOperand(FIMMOSt));
6600   }
6601 }
6602
6603 MachineBasicBlock *ARMTargetLowering::
6604 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6605   const TargetInstrInfo *TII =
6606       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6607   DebugLoc dl = MI->getDebugLoc();
6608   MachineFunction *MF = MBB->getParent();
6609   MachineRegisterInfo *MRI = &MF->getRegInfo();
6610   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6611   MachineFrameInfo *MFI = MF->getFrameInfo();
6612   int FI = MFI->getFunctionContextIndex();
6613
6614   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6615     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6616     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6617
6618   // Get a mapping of the call site numbers to all of the landing pads they're
6619   // associated with.
6620   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6621   unsigned MaxCSNum = 0;
6622   MachineModuleInfo &MMI = MF->getMMI();
6623   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6624        ++BB) {
6625     if (!BB->isLandingPad()) continue;
6626
6627     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6628     // pad.
6629     for (MachineBasicBlock::iterator
6630            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6631       if (!II->isEHLabel()) continue;
6632
6633       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6634       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6635
6636       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6637       for (SmallVectorImpl<unsigned>::iterator
6638              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6639            CSI != CSE; ++CSI) {
6640         CallSiteNumToLPad[*CSI].push_back(BB);
6641         MaxCSNum = std::max(MaxCSNum, *CSI);
6642       }
6643       break;
6644     }
6645   }
6646
6647   // Get an ordered list of the machine basic blocks for the jump table.
6648   std::vector<MachineBasicBlock*> LPadList;
6649   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6650   LPadList.reserve(CallSiteNumToLPad.size());
6651   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6652     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6653     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6654            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6655       LPadList.push_back(*II);
6656       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6657     }
6658   }
6659
6660   assert(!LPadList.empty() &&
6661          "No landing pad destinations for the dispatch jump table!");
6662
6663   // Create the jump table and associated information.
6664   MachineJumpTableInfo *JTI =
6665     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6666   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6667   unsigned UId = AFI->createJumpTableUId();
6668   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6669
6670   // Create the MBBs for the dispatch code.
6671
6672   // Shove the dispatch's address into the return slot in the function context.
6673   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6674   DispatchBB->setIsLandingPad();
6675
6676   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6677   unsigned trap_opcode;
6678   if (Subtarget->isThumb())
6679     trap_opcode = ARM::tTRAP;
6680   else
6681     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6682
6683   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6684   DispatchBB->addSuccessor(TrapBB);
6685
6686   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6687   DispatchBB->addSuccessor(DispContBB);
6688
6689   // Insert and MBBs.
6690   MF->insert(MF->end(), DispatchBB);
6691   MF->insert(MF->end(), DispContBB);
6692   MF->insert(MF->end(), TrapBB);
6693
6694   // Insert code into the entry block that creates and registers the function
6695   // context.
6696   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6697
6698   MachineMemOperand *FIMMOLd =
6699     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6700                              MachineMemOperand::MOLoad |
6701                              MachineMemOperand::MOVolatile, 4, 4);
6702
6703   MachineInstrBuilder MIB;
6704   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6705
6706   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6707   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6708
6709   // Add a register mask with no preserved registers.  This results in all
6710   // registers being marked as clobbered.
6711   MIB.addRegMask(RI.getNoPreservedMask());
6712
6713   unsigned NumLPads = LPadList.size();
6714   if (Subtarget->isThumb2()) {
6715     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6716     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6717                    .addFrameIndex(FI)
6718                    .addImm(4)
6719                    .addMemOperand(FIMMOLd));
6720
6721     if (NumLPads < 256) {
6722       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6723                      .addReg(NewVReg1)
6724                      .addImm(LPadList.size()));
6725     } else {
6726       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6727       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6728                      .addImm(NumLPads & 0xFFFF));
6729
6730       unsigned VReg2 = VReg1;
6731       if ((NumLPads & 0xFFFF0000) != 0) {
6732         VReg2 = MRI->createVirtualRegister(TRC);
6733         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6734                        .addReg(VReg1)
6735                        .addImm(NumLPads >> 16));
6736       }
6737
6738       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6739                      .addReg(NewVReg1)
6740                      .addReg(VReg2));
6741     }
6742
6743     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6744       .addMBB(TrapBB)
6745       .addImm(ARMCC::HI)
6746       .addReg(ARM::CPSR);
6747
6748     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6749     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6750                    .addJumpTableIndex(MJTI)
6751                    .addImm(UId));
6752
6753     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6754     AddDefaultCC(
6755       AddDefaultPred(
6756         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6757         .addReg(NewVReg3, RegState::Kill)
6758         .addReg(NewVReg1)
6759         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6760
6761     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6762       .addReg(NewVReg4, RegState::Kill)
6763       .addReg(NewVReg1)
6764       .addJumpTableIndex(MJTI)
6765       .addImm(UId);
6766   } else if (Subtarget->isThumb()) {
6767     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6768     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6769                    .addFrameIndex(FI)
6770                    .addImm(1)
6771                    .addMemOperand(FIMMOLd));
6772
6773     if (NumLPads < 256) {
6774       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6775                      .addReg(NewVReg1)
6776                      .addImm(NumLPads));
6777     } else {
6778       MachineConstantPool *ConstantPool = MF->getConstantPool();
6779       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6780       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6781
6782       // MachineConstantPool wants an explicit alignment.
6783       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6784       if (Align == 0)
6785         Align = getDataLayout()->getTypeAllocSize(C->getType());
6786       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6787
6788       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6789       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6790                      .addReg(VReg1, RegState::Define)
6791                      .addConstantPoolIndex(Idx));
6792       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6793                      .addReg(NewVReg1)
6794                      .addReg(VReg1));
6795     }
6796
6797     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6798       .addMBB(TrapBB)
6799       .addImm(ARMCC::HI)
6800       .addReg(ARM::CPSR);
6801
6802     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6803     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6804                    .addReg(ARM::CPSR, RegState::Define)
6805                    .addReg(NewVReg1)
6806                    .addImm(2));
6807
6808     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6809     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6810                    .addJumpTableIndex(MJTI)
6811                    .addImm(UId));
6812
6813     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6814     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6815                    .addReg(ARM::CPSR, RegState::Define)
6816                    .addReg(NewVReg2, RegState::Kill)
6817                    .addReg(NewVReg3));
6818
6819     MachineMemOperand *JTMMOLd =
6820       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6821                                MachineMemOperand::MOLoad, 4, 4);
6822
6823     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6824     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6825                    .addReg(NewVReg4, RegState::Kill)
6826                    .addImm(0)
6827                    .addMemOperand(JTMMOLd));
6828
6829     unsigned NewVReg6 = NewVReg5;
6830     if (RelocM == Reloc::PIC_) {
6831       NewVReg6 = MRI->createVirtualRegister(TRC);
6832       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6833                      .addReg(ARM::CPSR, RegState::Define)
6834                      .addReg(NewVReg5, RegState::Kill)
6835                      .addReg(NewVReg3));
6836     }
6837
6838     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6839       .addReg(NewVReg6, RegState::Kill)
6840       .addJumpTableIndex(MJTI)
6841       .addImm(UId);
6842   } else {
6843     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6844     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6845                    .addFrameIndex(FI)
6846                    .addImm(4)
6847                    .addMemOperand(FIMMOLd));
6848
6849     if (NumLPads < 256) {
6850       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6851                      .addReg(NewVReg1)
6852                      .addImm(NumLPads));
6853     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6854       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6855       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6856                      .addImm(NumLPads & 0xFFFF));
6857
6858       unsigned VReg2 = VReg1;
6859       if ((NumLPads & 0xFFFF0000) != 0) {
6860         VReg2 = MRI->createVirtualRegister(TRC);
6861         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6862                        .addReg(VReg1)
6863                        .addImm(NumLPads >> 16));
6864       }
6865
6866       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6867                      .addReg(NewVReg1)
6868                      .addReg(VReg2));
6869     } else {
6870       MachineConstantPool *ConstantPool = MF->getConstantPool();
6871       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6872       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6873
6874       // MachineConstantPool wants an explicit alignment.
6875       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6876       if (Align == 0)
6877         Align = getDataLayout()->getTypeAllocSize(C->getType());
6878       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6879
6880       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6881       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6882                      .addReg(VReg1, RegState::Define)
6883                      .addConstantPoolIndex(Idx)
6884                      .addImm(0));
6885       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6886                      .addReg(NewVReg1)
6887                      .addReg(VReg1, RegState::Kill));
6888     }
6889
6890     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6891       .addMBB(TrapBB)
6892       .addImm(ARMCC::HI)
6893       .addReg(ARM::CPSR);
6894
6895     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6896     AddDefaultCC(
6897       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6898                      .addReg(NewVReg1)
6899                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6900     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6901     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6902                    .addJumpTableIndex(MJTI)
6903                    .addImm(UId));
6904
6905     MachineMemOperand *JTMMOLd =
6906       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6907                                MachineMemOperand::MOLoad, 4, 4);
6908     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6909     AddDefaultPred(
6910       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6911       .addReg(NewVReg3, RegState::Kill)
6912       .addReg(NewVReg4)
6913       .addImm(0)
6914       .addMemOperand(JTMMOLd));
6915
6916     if (RelocM == Reloc::PIC_) {
6917       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6918         .addReg(NewVReg5, RegState::Kill)
6919         .addReg(NewVReg4)
6920         .addJumpTableIndex(MJTI)
6921         .addImm(UId);
6922     } else {
6923       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6924         .addReg(NewVReg5, RegState::Kill)
6925         .addJumpTableIndex(MJTI)
6926         .addImm(UId);
6927     }
6928   }
6929
6930   // Add the jump table entries as successors to the MBB.
6931   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6932   for (std::vector<MachineBasicBlock*>::iterator
6933          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6934     MachineBasicBlock *CurMBB = *I;
6935     if (SeenMBBs.insert(CurMBB))
6936       DispContBB->addSuccessor(CurMBB);
6937   }
6938
6939   // N.B. the order the invoke BBs are processed in doesn't matter here.
6940   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6941   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6942   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6943          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6944     MachineBasicBlock *BB = *I;
6945
6946     // Remove the landing pad successor from the invoke block and replace it
6947     // with the new dispatch block.
6948     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6949                                                   BB->succ_end());
6950     while (!Successors.empty()) {
6951       MachineBasicBlock *SMBB = Successors.pop_back_val();
6952       if (SMBB->isLandingPad()) {
6953         BB->removeSuccessor(SMBB);
6954         MBBLPads.push_back(SMBB);
6955       }
6956     }
6957
6958     BB->addSuccessor(DispatchBB);
6959
6960     // Find the invoke call and mark all of the callee-saved registers as
6961     // 'implicit defined' so that they're spilled. This prevents code from
6962     // moving instructions to before the EH block, where they will never be
6963     // executed.
6964     for (MachineBasicBlock::reverse_iterator
6965            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6966       if (!II->isCall()) continue;
6967
6968       DenseMap<unsigned, bool> DefRegs;
6969       for (MachineInstr::mop_iterator
6970              OI = II->operands_begin(), OE = II->operands_end();
6971            OI != OE; ++OI) {
6972         if (!OI->isReg()) continue;
6973         DefRegs[OI->getReg()] = true;
6974       }
6975
6976       MachineInstrBuilder MIB(*MF, &*II);
6977
6978       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6979         unsigned Reg = SavedRegs[i];
6980         if (Subtarget->isThumb2() &&
6981             !ARM::tGPRRegClass.contains(Reg) &&
6982             !ARM::hGPRRegClass.contains(Reg))
6983           continue;
6984         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6985           continue;
6986         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6987           continue;
6988         if (!DefRegs[Reg])
6989           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6990       }
6991
6992       break;
6993     }
6994   }
6995
6996   // Mark all former landing pads as non-landing pads. The dispatch is the only
6997   // landing pad now.
6998   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6999          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7000     (*I)->setIsLandingPad(false);
7001
7002   // The instruction is gone now.
7003   MI->eraseFromParent();
7004
7005   return MBB;
7006 }
7007
7008 static
7009 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7010   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7011        E = MBB->succ_end(); I != E; ++I)
7012     if (*I != Succ)
7013       return *I;
7014   llvm_unreachable("Expecting a BB with two successors!");
7015 }
7016
7017 /// Return the load opcode for a given load size. If load size >= 8,
7018 /// neon opcode will be returned.
7019 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7020   if (LdSize >= 8)
7021     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7022                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7023   if (IsThumb1)
7024     return LdSize == 4 ? ARM::tLDRi
7025                        : LdSize == 2 ? ARM::tLDRHi
7026                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7027   if (IsThumb2)
7028     return LdSize == 4 ? ARM::t2LDR_POST
7029                        : LdSize == 2 ? ARM::t2LDRH_POST
7030                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7031   return LdSize == 4 ? ARM::LDR_POST_IMM
7032                      : LdSize == 2 ? ARM::LDRH_POST
7033                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7034 }
7035
7036 /// Return the store opcode for a given store size. If store size >= 8,
7037 /// neon opcode will be returned.
7038 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7039   if (StSize >= 8)
7040     return StSize == 16 ? ARM::VST1q32wb_fixed
7041                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7042   if (IsThumb1)
7043     return StSize == 4 ? ARM::tSTRi
7044                        : StSize == 2 ? ARM::tSTRHi
7045                                      : StSize == 1 ? ARM::tSTRBi : 0;
7046   if (IsThumb2)
7047     return StSize == 4 ? ARM::t2STR_POST
7048                        : StSize == 2 ? ARM::t2STRH_POST
7049                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7050   return StSize == 4 ? ARM::STR_POST_IMM
7051                      : StSize == 2 ? ARM::STRH_POST
7052                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7053 }
7054
7055 /// Emit a post-increment load operation with given size. The instructions
7056 /// will be added to BB at Pos.
7057 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7058                        const TargetInstrInfo *TII, DebugLoc dl,
7059                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7060                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7061   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7062   assert(LdOpc != 0 && "Should have a load opcode");
7063   if (LdSize >= 8) {
7064     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7065                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7066                        .addImm(0));
7067   } else if (IsThumb1) {
7068     // load + update AddrIn
7069     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7070                        .addReg(AddrIn).addImm(0));
7071     MachineInstrBuilder MIB =
7072         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7073     MIB = AddDefaultT1CC(MIB);
7074     MIB.addReg(AddrIn).addImm(LdSize);
7075     AddDefaultPred(MIB);
7076   } else if (IsThumb2) {
7077     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7078                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7079                        .addImm(LdSize));
7080   } else { // arm
7081     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7082                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7083                        .addReg(0).addImm(LdSize));
7084   }
7085 }
7086
7087 /// Emit a post-increment store operation with given size. The instructions
7088 /// will be added to BB at Pos.
7089 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7090                        const TargetInstrInfo *TII, DebugLoc dl,
7091                        unsigned StSize, unsigned Data, unsigned AddrIn,
7092                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7093   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7094   assert(StOpc != 0 && "Should have a store opcode");
7095   if (StSize >= 8) {
7096     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7097                        .addReg(AddrIn).addImm(0).addReg(Data));
7098   } else if (IsThumb1) {
7099     // store + update AddrIn
7100     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7101                        .addReg(AddrIn).addImm(0));
7102     MachineInstrBuilder MIB =
7103         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7104     MIB = AddDefaultT1CC(MIB);
7105     MIB.addReg(AddrIn).addImm(StSize);
7106     AddDefaultPred(MIB);
7107   } else if (IsThumb2) {
7108     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7109                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7110   } else { // arm
7111     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7112                        .addReg(Data).addReg(AddrIn).addReg(0)
7113                        .addImm(StSize));
7114   }
7115 }
7116
7117 MachineBasicBlock *
7118 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7119                                    MachineBasicBlock *BB) const {
7120   // This pseudo instruction has 3 operands: dst, src, size
7121   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7122   // Otherwise, we will generate unrolled scalar copies.
7123   const TargetInstrInfo *TII =
7124       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7125   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7126   MachineFunction::iterator It = BB;
7127   ++It;
7128
7129   unsigned dest = MI->getOperand(0).getReg();
7130   unsigned src = MI->getOperand(1).getReg();
7131   unsigned SizeVal = MI->getOperand(2).getImm();
7132   unsigned Align = MI->getOperand(3).getImm();
7133   DebugLoc dl = MI->getDebugLoc();
7134
7135   MachineFunction *MF = BB->getParent();
7136   MachineRegisterInfo &MRI = MF->getRegInfo();
7137   unsigned UnitSize = 0;
7138   const TargetRegisterClass *TRC = nullptr;
7139   const TargetRegisterClass *VecTRC = nullptr;
7140
7141   bool IsThumb1 = Subtarget->isThumb1Only();
7142   bool IsThumb2 = Subtarget->isThumb2();
7143
7144   if (Align & 1) {
7145     UnitSize = 1;
7146   } else if (Align & 2) {
7147     UnitSize = 2;
7148   } else {
7149     // Check whether we can use NEON instructions.
7150     if (!MF->getFunction()->getAttributes().
7151           hasAttribute(AttributeSet::FunctionIndex,
7152                        Attribute::NoImplicitFloat) &&
7153         Subtarget->hasNEON()) {
7154       if ((Align % 16 == 0) && SizeVal >= 16)
7155         UnitSize = 16;
7156       else if ((Align % 8 == 0) && SizeVal >= 8)
7157         UnitSize = 8;
7158     }
7159     // Can't use NEON instructions.
7160     if (UnitSize == 0)
7161       UnitSize = 4;
7162   }
7163
7164   // Select the correct opcode and register class for unit size load/store
7165   bool IsNeon = UnitSize >= 8;
7166   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7167                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7168   if (IsNeon)
7169     VecTRC = UnitSize == 16
7170                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7171                  : UnitSize == 8
7172                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7173                        : nullptr;
7174
7175   unsigned BytesLeft = SizeVal % UnitSize;
7176   unsigned LoopSize = SizeVal - BytesLeft;
7177
7178   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7179     // Use LDR and STR to copy.
7180     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7181     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7182     unsigned srcIn = src;
7183     unsigned destIn = dest;
7184     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7185       unsigned srcOut = MRI.createVirtualRegister(TRC);
7186       unsigned destOut = MRI.createVirtualRegister(TRC);
7187       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7188       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7189                  IsThumb1, IsThumb2);
7190       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7191                  IsThumb1, IsThumb2);
7192       srcIn = srcOut;
7193       destIn = destOut;
7194     }
7195
7196     // Handle the leftover bytes with LDRB and STRB.
7197     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7198     // [destOut] = STRB_POST(scratch, destIn, 1)
7199     for (unsigned i = 0; i < BytesLeft; i++) {
7200       unsigned srcOut = MRI.createVirtualRegister(TRC);
7201       unsigned destOut = MRI.createVirtualRegister(TRC);
7202       unsigned scratch = MRI.createVirtualRegister(TRC);
7203       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7204                  IsThumb1, IsThumb2);
7205       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7206                  IsThumb1, IsThumb2);
7207       srcIn = srcOut;
7208       destIn = destOut;
7209     }
7210     MI->eraseFromParent();   // The instruction is gone now.
7211     return BB;
7212   }
7213
7214   // Expand the pseudo op to a loop.
7215   // thisMBB:
7216   //   ...
7217   //   movw varEnd, # --> with thumb2
7218   //   movt varEnd, #
7219   //   ldrcp varEnd, idx --> without thumb2
7220   //   fallthrough --> loopMBB
7221   // loopMBB:
7222   //   PHI varPhi, varEnd, varLoop
7223   //   PHI srcPhi, src, srcLoop
7224   //   PHI destPhi, dst, destLoop
7225   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7226   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7227   //   subs varLoop, varPhi, #UnitSize
7228   //   bne loopMBB
7229   //   fallthrough --> exitMBB
7230   // exitMBB:
7231   //   epilogue to handle left-over bytes
7232   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7233   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7234   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7235   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7236   MF->insert(It, loopMBB);
7237   MF->insert(It, exitMBB);
7238
7239   // Transfer the remainder of BB and its successor edges to exitMBB.
7240   exitMBB->splice(exitMBB->begin(), BB,
7241                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7242   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7243
7244   // Load an immediate to varEnd.
7245   unsigned varEnd = MRI.createVirtualRegister(TRC);
7246   if (IsThumb2) {
7247     unsigned Vtmp = varEnd;
7248     if ((LoopSize & 0xFFFF0000) != 0)
7249       Vtmp = MRI.createVirtualRegister(TRC);
7250     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7251                        .addImm(LoopSize & 0xFFFF));
7252
7253     if ((LoopSize & 0xFFFF0000) != 0)
7254       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7255                          .addReg(Vtmp).addImm(LoopSize >> 16));
7256   } else {
7257     MachineConstantPool *ConstantPool = MF->getConstantPool();
7258     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7259     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7260
7261     // MachineConstantPool wants an explicit alignment.
7262     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7263     if (Align == 0)
7264       Align = getDataLayout()->getTypeAllocSize(C->getType());
7265     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7266
7267     if (IsThumb1)
7268       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7269           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7270     else
7271       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7272           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7273   }
7274   BB->addSuccessor(loopMBB);
7275
7276   // Generate the loop body:
7277   //   varPhi = PHI(varLoop, varEnd)
7278   //   srcPhi = PHI(srcLoop, src)
7279   //   destPhi = PHI(destLoop, dst)
7280   MachineBasicBlock *entryBB = BB;
7281   BB = loopMBB;
7282   unsigned varLoop = MRI.createVirtualRegister(TRC);
7283   unsigned varPhi = MRI.createVirtualRegister(TRC);
7284   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7285   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7286   unsigned destLoop = MRI.createVirtualRegister(TRC);
7287   unsigned destPhi = MRI.createVirtualRegister(TRC);
7288
7289   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7290     .addReg(varLoop).addMBB(loopMBB)
7291     .addReg(varEnd).addMBB(entryBB);
7292   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7293     .addReg(srcLoop).addMBB(loopMBB)
7294     .addReg(src).addMBB(entryBB);
7295   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7296     .addReg(destLoop).addMBB(loopMBB)
7297     .addReg(dest).addMBB(entryBB);
7298
7299   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7300   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7301   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7302   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7303              IsThumb1, IsThumb2);
7304   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7305              IsThumb1, IsThumb2);
7306
7307   // Decrement loop variable by UnitSize.
7308   if (IsThumb1) {
7309     MachineInstrBuilder MIB =
7310         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7311     MIB = AddDefaultT1CC(MIB);
7312     MIB.addReg(varPhi).addImm(UnitSize);
7313     AddDefaultPred(MIB);
7314   } else {
7315     MachineInstrBuilder MIB =
7316         BuildMI(*BB, BB->end(), dl,
7317                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7318     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7319     MIB->getOperand(5).setReg(ARM::CPSR);
7320     MIB->getOperand(5).setIsDef(true);
7321   }
7322   BuildMI(*BB, BB->end(), dl,
7323           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7324       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7325
7326   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7327   BB->addSuccessor(loopMBB);
7328   BB->addSuccessor(exitMBB);
7329
7330   // Add epilogue to handle BytesLeft.
7331   BB = exitMBB;
7332   MachineInstr *StartOfExit = exitMBB->begin();
7333
7334   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7335   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7336   unsigned srcIn = srcLoop;
7337   unsigned destIn = destLoop;
7338   for (unsigned i = 0; i < BytesLeft; i++) {
7339     unsigned srcOut = MRI.createVirtualRegister(TRC);
7340     unsigned destOut = MRI.createVirtualRegister(TRC);
7341     unsigned scratch = MRI.createVirtualRegister(TRC);
7342     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7343                IsThumb1, IsThumb2);
7344     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7345                IsThumb1, IsThumb2);
7346     srcIn = srcOut;
7347     destIn = destOut;
7348   }
7349
7350   MI->eraseFromParent();   // The instruction is gone now.
7351   return BB;
7352 }
7353
7354 MachineBasicBlock *
7355 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7356                                        MachineBasicBlock *MBB) const {
7357   const TargetMachine &TM = getTargetMachine();
7358   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7359   DebugLoc DL = MI->getDebugLoc();
7360
7361   assert(Subtarget->isTargetWindows() &&
7362          "__chkstk is only supported on Windows");
7363   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7364
7365   // __chkstk takes the number of words to allocate on the stack in R4, and
7366   // returns the stack adjustment in number of bytes in R4.  This will not
7367   // clober any other registers (other than the obvious lr).
7368   //
7369   // Although, technically, IP should be considered a register which may be
7370   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7371   // thumb-2 environment, so there is no interworking required.  As a result, we
7372   // do not expect a veneer to be emitted by the linker, clobbering IP.
7373   //
7374   // Each module receives its own copy of __chkstk, so no import thunk is
7375   // required, again, ensuring that IP is not clobbered.
7376   //
7377   // Finally, although some linkers may theoretically provide a trampoline for
7378   // out of range calls (which is quite common due to a 32M range limitation of
7379   // branches for Thumb), we can generate the long-call version via
7380   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7381   // IP.
7382
7383   switch (TM.getCodeModel()) {
7384   case CodeModel::Small:
7385   case CodeModel::Medium:
7386   case CodeModel::Default:
7387   case CodeModel::Kernel:
7388     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7389       .addImm((unsigned)ARMCC::AL).addReg(0)
7390       .addExternalSymbol("__chkstk")
7391       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7392       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7393       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7394     break;
7395   case CodeModel::Large:
7396   case CodeModel::JITDefault: {
7397     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7398     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7399
7400     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7401       .addExternalSymbol("__chkstk");
7402     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7403       .addImm((unsigned)ARMCC::AL).addReg(0)
7404       .addReg(Reg, RegState::Kill)
7405       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7406       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7407       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7408     break;
7409   }
7410   }
7411
7412   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7413                                       ARM::SP)
7414                               .addReg(ARM::SP).addReg(ARM::R4)));
7415
7416   MI->eraseFromParent();
7417   return MBB;
7418 }
7419
7420 MachineBasicBlock *
7421 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7422                                                MachineBasicBlock *BB) const {
7423   const TargetInstrInfo *TII =
7424       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7425   DebugLoc dl = MI->getDebugLoc();
7426   bool isThumb2 = Subtarget->isThumb2();
7427   switch (MI->getOpcode()) {
7428   default: {
7429     MI->dump();
7430     llvm_unreachable("Unexpected instr type to insert");
7431   }
7432   // The Thumb2 pre-indexed stores have the same MI operands, they just
7433   // define them differently in the .td files from the isel patterns, so
7434   // they need pseudos.
7435   case ARM::t2STR_preidx:
7436     MI->setDesc(TII->get(ARM::t2STR_PRE));
7437     return BB;
7438   case ARM::t2STRB_preidx:
7439     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7440     return BB;
7441   case ARM::t2STRH_preidx:
7442     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7443     return BB;
7444
7445   case ARM::STRi_preidx:
7446   case ARM::STRBi_preidx: {
7447     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7448       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7449     // Decode the offset.
7450     unsigned Offset = MI->getOperand(4).getImm();
7451     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7452     Offset = ARM_AM::getAM2Offset(Offset);
7453     if (isSub)
7454       Offset = -Offset;
7455
7456     MachineMemOperand *MMO = *MI->memoperands_begin();
7457     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7458       .addOperand(MI->getOperand(0))  // Rn_wb
7459       .addOperand(MI->getOperand(1))  // Rt
7460       .addOperand(MI->getOperand(2))  // Rn
7461       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7462       .addOperand(MI->getOperand(5))  // pred
7463       .addOperand(MI->getOperand(6))
7464       .addMemOperand(MMO);
7465     MI->eraseFromParent();
7466     return BB;
7467   }
7468   case ARM::STRr_preidx:
7469   case ARM::STRBr_preidx:
7470   case ARM::STRH_preidx: {
7471     unsigned NewOpc;
7472     switch (MI->getOpcode()) {
7473     default: llvm_unreachable("unexpected opcode!");
7474     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7475     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7476     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7477     }
7478     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7479     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7480       MIB.addOperand(MI->getOperand(i));
7481     MI->eraseFromParent();
7482     return BB;
7483   }
7484
7485   case ARM::tMOVCCr_pseudo: {
7486     // To "insert" a SELECT_CC instruction, we actually have to insert the
7487     // diamond control-flow pattern.  The incoming instruction knows the
7488     // destination vreg to set, the condition code register to branch on, the
7489     // true/false values to select between, and a branch opcode to use.
7490     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7491     MachineFunction::iterator It = BB;
7492     ++It;
7493
7494     //  thisMBB:
7495     //  ...
7496     //   TrueVal = ...
7497     //   cmpTY ccX, r1, r2
7498     //   bCC copy1MBB
7499     //   fallthrough --> copy0MBB
7500     MachineBasicBlock *thisMBB  = BB;
7501     MachineFunction *F = BB->getParent();
7502     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7503     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7504     F->insert(It, copy0MBB);
7505     F->insert(It, sinkMBB);
7506
7507     // Transfer the remainder of BB and its successor edges to sinkMBB.
7508     sinkMBB->splice(sinkMBB->begin(), BB,
7509                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7510     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7511
7512     BB->addSuccessor(copy0MBB);
7513     BB->addSuccessor(sinkMBB);
7514
7515     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7516       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7517
7518     //  copy0MBB:
7519     //   %FalseValue = ...
7520     //   # fallthrough to sinkMBB
7521     BB = copy0MBB;
7522
7523     // Update machine-CFG edges
7524     BB->addSuccessor(sinkMBB);
7525
7526     //  sinkMBB:
7527     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7528     //  ...
7529     BB = sinkMBB;
7530     BuildMI(*BB, BB->begin(), dl,
7531             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7532       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7533       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7534
7535     MI->eraseFromParent();   // The pseudo instruction is gone now.
7536     return BB;
7537   }
7538
7539   case ARM::BCCi64:
7540   case ARM::BCCZi64: {
7541     // If there is an unconditional branch to the other successor, remove it.
7542     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7543
7544     // Compare both parts that make up the double comparison separately for
7545     // equality.
7546     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7547
7548     unsigned LHS1 = MI->getOperand(1).getReg();
7549     unsigned LHS2 = MI->getOperand(2).getReg();
7550     if (RHSisZero) {
7551       AddDefaultPred(BuildMI(BB, dl,
7552                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7553                      .addReg(LHS1).addImm(0));
7554       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7555         .addReg(LHS2).addImm(0)
7556         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7557     } else {
7558       unsigned RHS1 = MI->getOperand(3).getReg();
7559       unsigned RHS2 = MI->getOperand(4).getReg();
7560       AddDefaultPred(BuildMI(BB, dl,
7561                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7562                      .addReg(LHS1).addReg(RHS1));
7563       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7564         .addReg(LHS2).addReg(RHS2)
7565         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7566     }
7567
7568     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7569     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7570     if (MI->getOperand(0).getImm() == ARMCC::NE)
7571       std::swap(destMBB, exitMBB);
7572
7573     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7574       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7575     if (isThumb2)
7576       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7577     else
7578       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7579
7580     MI->eraseFromParent();   // The pseudo instruction is gone now.
7581     return BB;
7582   }
7583
7584   case ARM::Int_eh_sjlj_setjmp:
7585   case ARM::Int_eh_sjlj_setjmp_nofp:
7586   case ARM::tInt_eh_sjlj_setjmp:
7587   case ARM::t2Int_eh_sjlj_setjmp:
7588   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7589     EmitSjLjDispatchBlock(MI, BB);
7590     return BB;
7591
7592   case ARM::ABS:
7593   case ARM::t2ABS: {
7594     // To insert an ABS instruction, we have to insert the
7595     // diamond control-flow pattern.  The incoming instruction knows the
7596     // source vreg to test against 0, the destination vreg to set,
7597     // the condition code register to branch on, the
7598     // true/false values to select between, and a branch opcode to use.
7599     // It transforms
7600     //     V1 = ABS V0
7601     // into
7602     //     V2 = MOVS V0
7603     //     BCC                      (branch to SinkBB if V0 >= 0)
7604     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7605     //     SinkBB: V1 = PHI(V2, V3)
7606     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7607     MachineFunction::iterator BBI = BB;
7608     ++BBI;
7609     MachineFunction *Fn = BB->getParent();
7610     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7611     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7612     Fn->insert(BBI, RSBBB);
7613     Fn->insert(BBI, SinkBB);
7614
7615     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7616     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7617     bool isThumb2 = Subtarget->isThumb2();
7618     MachineRegisterInfo &MRI = Fn->getRegInfo();
7619     // In Thumb mode S must not be specified if source register is the SP or
7620     // PC and if destination register is the SP, so restrict register class
7621     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7622       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7623       (const TargetRegisterClass*)&ARM::GPRRegClass);
7624
7625     // Transfer the remainder of BB and its successor edges to sinkMBB.
7626     SinkBB->splice(SinkBB->begin(), BB,
7627                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7628     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7629
7630     BB->addSuccessor(RSBBB);
7631     BB->addSuccessor(SinkBB);
7632
7633     // fall through to SinkMBB
7634     RSBBB->addSuccessor(SinkBB);
7635
7636     // insert a cmp at the end of BB
7637     AddDefaultPred(BuildMI(BB, dl,
7638                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7639                    .addReg(ABSSrcReg).addImm(0));
7640
7641     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7642     BuildMI(BB, dl,
7643       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7644       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7645
7646     // insert rsbri in RSBBB
7647     // Note: BCC and rsbri will be converted into predicated rsbmi
7648     // by if-conversion pass
7649     BuildMI(*RSBBB, RSBBB->begin(), dl,
7650       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7651       .addReg(ABSSrcReg, RegState::Kill)
7652       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7653
7654     // insert PHI in SinkBB,
7655     // reuse ABSDstReg to not change uses of ABS instruction
7656     BuildMI(*SinkBB, SinkBB->begin(), dl,
7657       TII->get(ARM::PHI), ABSDstReg)
7658       .addReg(NewRsbDstReg).addMBB(RSBBB)
7659       .addReg(ABSSrcReg).addMBB(BB);
7660
7661     // remove ABS instruction
7662     MI->eraseFromParent();
7663
7664     // return last added BB
7665     return SinkBB;
7666   }
7667   case ARM::COPY_STRUCT_BYVAL_I32:
7668     ++NumLoopByVals;
7669     return EmitStructByval(MI, BB);
7670   case ARM::WIN__CHKSTK:
7671     return EmitLowered__chkstk(MI, BB);
7672   }
7673 }
7674
7675 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7676                                                       SDNode *Node) const {
7677   if (!MI->hasPostISelHook()) {
7678     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7679            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7680     return;
7681   }
7682
7683   const MCInstrDesc *MCID = &MI->getDesc();
7684   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7685   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7686   // operand is still set to noreg. If needed, set the optional operand's
7687   // register to CPSR, and remove the redundant implicit def.
7688   //
7689   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7690
7691   // Rename pseudo opcodes.
7692   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7693   if (NewOpc) {
7694     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7695         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7696     MCID = &TII->get(NewOpc);
7697
7698     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7699            "converted opcode should be the same except for cc_out");
7700
7701     MI->setDesc(*MCID);
7702
7703     // Add the optional cc_out operand
7704     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7705   }
7706   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7707
7708   // Any ARM instruction that sets the 's' bit should specify an optional
7709   // "cc_out" operand in the last operand position.
7710   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7711     assert(!NewOpc && "Optional cc_out operand required");
7712     return;
7713   }
7714   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7715   // since we already have an optional CPSR def.
7716   bool definesCPSR = false;
7717   bool deadCPSR = false;
7718   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7719        i != e; ++i) {
7720     const MachineOperand &MO = MI->getOperand(i);
7721     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7722       definesCPSR = true;
7723       if (MO.isDead())
7724         deadCPSR = true;
7725       MI->RemoveOperand(i);
7726       break;
7727     }
7728   }
7729   if (!definesCPSR) {
7730     assert(!NewOpc && "Optional cc_out operand required");
7731     return;
7732   }
7733   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7734   if (deadCPSR) {
7735     assert(!MI->getOperand(ccOutIdx).getReg() &&
7736            "expect uninitialized optional cc_out operand");
7737     return;
7738   }
7739
7740   // If this instruction was defined with an optional CPSR def and its dag node
7741   // had a live implicit CPSR def, then activate the optional CPSR def.
7742   MachineOperand &MO = MI->getOperand(ccOutIdx);
7743   MO.setReg(ARM::CPSR);
7744   MO.setIsDef(true);
7745 }
7746
7747 //===----------------------------------------------------------------------===//
7748 //                           ARM Optimization Hooks
7749 //===----------------------------------------------------------------------===//
7750
7751 // Helper function that checks if N is a null or all ones constant.
7752 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7753   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7754   if (!C)
7755     return false;
7756   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7757 }
7758
7759 // Return true if N is conditionally 0 or all ones.
7760 // Detects these expressions where cc is an i1 value:
7761 //
7762 //   (select cc 0, y)   [AllOnes=0]
7763 //   (select cc y, 0)   [AllOnes=0]
7764 //   (zext cc)          [AllOnes=0]
7765 //   (sext cc)          [AllOnes=0/1]
7766 //   (select cc -1, y)  [AllOnes=1]
7767 //   (select cc y, -1)  [AllOnes=1]
7768 //
7769 // Invert is set when N is the null/all ones constant when CC is false.
7770 // OtherOp is set to the alternative value of N.
7771 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7772                                        SDValue &CC, bool &Invert,
7773                                        SDValue &OtherOp,
7774                                        SelectionDAG &DAG) {
7775   switch (N->getOpcode()) {
7776   default: return false;
7777   case ISD::SELECT: {
7778     CC = N->getOperand(0);
7779     SDValue N1 = N->getOperand(1);
7780     SDValue N2 = N->getOperand(2);
7781     if (isZeroOrAllOnes(N1, AllOnes)) {
7782       Invert = false;
7783       OtherOp = N2;
7784       return true;
7785     }
7786     if (isZeroOrAllOnes(N2, AllOnes)) {
7787       Invert = true;
7788       OtherOp = N1;
7789       return true;
7790     }
7791     return false;
7792   }
7793   case ISD::ZERO_EXTEND:
7794     // (zext cc) can never be the all ones value.
7795     if (AllOnes)
7796       return false;
7797     // Fall through.
7798   case ISD::SIGN_EXTEND: {
7799     EVT VT = N->getValueType(0);
7800     CC = N->getOperand(0);
7801     if (CC.getValueType() != MVT::i1)
7802       return false;
7803     Invert = !AllOnes;
7804     if (AllOnes)
7805       // When looking for an AllOnes constant, N is an sext, and the 'other'
7806       // value is 0.
7807       OtherOp = DAG.getConstant(0, VT);
7808     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7809       // When looking for a 0 constant, N can be zext or sext.
7810       OtherOp = DAG.getConstant(1, VT);
7811     else
7812       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7813     return true;
7814   }
7815   }
7816 }
7817
7818 // Combine a constant select operand into its use:
7819 //
7820 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7821 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7822 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7823 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7824 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7825 //
7826 // The transform is rejected if the select doesn't have a constant operand that
7827 // is null, or all ones when AllOnes is set.
7828 //
7829 // Also recognize sext/zext from i1:
7830 //
7831 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7832 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7833 //
7834 // These transformations eventually create predicated instructions.
7835 //
7836 // @param N       The node to transform.
7837 // @param Slct    The N operand that is a select.
7838 // @param OtherOp The other N operand (x above).
7839 // @param DCI     Context.
7840 // @param AllOnes Require the select constant to be all ones instead of null.
7841 // @returns The new node, or SDValue() on failure.
7842 static
7843 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7844                             TargetLowering::DAGCombinerInfo &DCI,
7845                             bool AllOnes = false) {
7846   SelectionDAG &DAG = DCI.DAG;
7847   EVT VT = N->getValueType(0);
7848   SDValue NonConstantVal;
7849   SDValue CCOp;
7850   bool SwapSelectOps;
7851   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7852                                   NonConstantVal, DAG))
7853     return SDValue();
7854
7855   // Slct is now know to be the desired identity constant when CC is true.
7856   SDValue TrueVal = OtherOp;
7857   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7858                                  OtherOp, NonConstantVal);
7859   // Unless SwapSelectOps says CC should be false.
7860   if (SwapSelectOps)
7861     std::swap(TrueVal, FalseVal);
7862
7863   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7864                      CCOp, TrueVal, FalseVal);
7865 }
7866
7867 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7868 static
7869 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7870                                        TargetLowering::DAGCombinerInfo &DCI) {
7871   SDValue N0 = N->getOperand(0);
7872   SDValue N1 = N->getOperand(1);
7873   if (N0.getNode()->hasOneUse()) {
7874     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7875     if (Result.getNode())
7876       return Result;
7877   }
7878   if (N1.getNode()->hasOneUse()) {
7879     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7880     if (Result.getNode())
7881       return Result;
7882   }
7883   return SDValue();
7884 }
7885
7886 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7887 // (only after legalization).
7888 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7889                                  TargetLowering::DAGCombinerInfo &DCI,
7890                                  const ARMSubtarget *Subtarget) {
7891
7892   // Only perform optimization if after legalize, and if NEON is available. We
7893   // also expected both operands to be BUILD_VECTORs.
7894   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7895       || N0.getOpcode() != ISD::BUILD_VECTOR
7896       || N1.getOpcode() != ISD::BUILD_VECTOR)
7897     return SDValue();
7898
7899   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7900   EVT VT = N->getValueType(0);
7901   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7902     return SDValue();
7903
7904   // Check that the vector operands are of the right form.
7905   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7906   // operands, where N is the size of the formed vector.
7907   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7908   // index such that we have a pair wise add pattern.
7909
7910   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7911   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7912     return SDValue();
7913   SDValue Vec = N0->getOperand(0)->getOperand(0);
7914   SDNode *V = Vec.getNode();
7915   unsigned nextIndex = 0;
7916
7917   // For each operands to the ADD which are BUILD_VECTORs,
7918   // check to see if each of their operands are an EXTRACT_VECTOR with
7919   // the same vector and appropriate index.
7920   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7921     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7922         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7923
7924       SDValue ExtVec0 = N0->getOperand(i);
7925       SDValue ExtVec1 = N1->getOperand(i);
7926
7927       // First operand is the vector, verify its the same.
7928       if (V != ExtVec0->getOperand(0).getNode() ||
7929           V != ExtVec1->getOperand(0).getNode())
7930         return SDValue();
7931
7932       // Second is the constant, verify its correct.
7933       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7934       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7935
7936       // For the constant, we want to see all the even or all the odd.
7937       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7938           || C1->getZExtValue() != nextIndex+1)
7939         return SDValue();
7940
7941       // Increment index.
7942       nextIndex+=2;
7943     } else
7944       return SDValue();
7945   }
7946
7947   // Create VPADDL node.
7948   SelectionDAG &DAG = DCI.DAG;
7949   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7950
7951   // Build operand list.
7952   SmallVector<SDValue, 8> Ops;
7953   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7954                                 TLI.getPointerTy()));
7955
7956   // Input is the vector.
7957   Ops.push_back(Vec);
7958
7959   // Get widened type and narrowed type.
7960   MVT widenType;
7961   unsigned numElem = VT.getVectorNumElements();
7962   
7963   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7964   switch (inputLaneType.getSimpleVT().SimpleTy) {
7965     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7966     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7967     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7968     default:
7969       llvm_unreachable("Invalid vector element type for padd optimization.");
7970   }
7971
7972   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7973   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7974   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7975 }
7976
7977 static SDValue findMUL_LOHI(SDValue V) {
7978   if (V->getOpcode() == ISD::UMUL_LOHI ||
7979       V->getOpcode() == ISD::SMUL_LOHI)
7980     return V;
7981   return SDValue();
7982 }
7983
7984 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7985                                      TargetLowering::DAGCombinerInfo &DCI,
7986                                      const ARMSubtarget *Subtarget) {
7987
7988   if (Subtarget->isThumb1Only()) return SDValue();
7989
7990   // Only perform the checks after legalize when the pattern is available.
7991   if (DCI.isBeforeLegalize()) return SDValue();
7992
7993   // Look for multiply add opportunities.
7994   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7995   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7996   // a glue link from the first add to the second add.
7997   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7998   // a S/UMLAL instruction.
7999   //          loAdd   UMUL_LOHI
8000   //            \    / :lo    \ :hi
8001   //             \  /          \          [no multiline comment]
8002   //              ADDC         |  hiAdd
8003   //                 \ :glue  /  /
8004   //                  \      /  /
8005   //                    ADDE
8006   //
8007   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8008   SDValue AddcOp0 = AddcNode->getOperand(0);
8009   SDValue AddcOp1 = AddcNode->getOperand(1);
8010
8011   // Check if the two operands are from the same mul_lohi node.
8012   if (AddcOp0.getNode() == AddcOp1.getNode())
8013     return SDValue();
8014
8015   assert(AddcNode->getNumValues() == 2 &&
8016          AddcNode->getValueType(0) == MVT::i32 &&
8017          "Expect ADDC with two result values. First: i32");
8018
8019   // Check that we have a glued ADDC node.
8020   if (AddcNode->getValueType(1) != MVT::Glue)
8021     return SDValue();
8022
8023   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8024   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8025       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8026       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8027       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8028     return SDValue();
8029
8030   // Look for the glued ADDE.
8031   SDNode* AddeNode = AddcNode->getGluedUser();
8032   if (!AddeNode)
8033     return SDValue();
8034
8035   // Make sure it is really an ADDE.
8036   if (AddeNode->getOpcode() != ISD::ADDE)
8037     return SDValue();
8038
8039   assert(AddeNode->getNumOperands() == 3 &&
8040          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8041          "ADDE node has the wrong inputs");
8042
8043   // Check for the triangle shape.
8044   SDValue AddeOp0 = AddeNode->getOperand(0);
8045   SDValue AddeOp1 = AddeNode->getOperand(1);
8046
8047   // Make sure that the ADDE operands are not coming from the same node.
8048   if (AddeOp0.getNode() == AddeOp1.getNode())
8049     return SDValue();
8050
8051   // Find the MUL_LOHI node walking up ADDE's operands.
8052   bool IsLeftOperandMUL = false;
8053   SDValue MULOp = findMUL_LOHI(AddeOp0);
8054   if (MULOp == SDValue())
8055    MULOp = findMUL_LOHI(AddeOp1);
8056   else
8057     IsLeftOperandMUL = true;
8058   if (MULOp == SDValue())
8059      return SDValue();
8060
8061   // Figure out the right opcode.
8062   unsigned Opc = MULOp->getOpcode();
8063   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8064
8065   // Figure out the high and low input values to the MLAL node.
8066   SDValue* HiMul = &MULOp;
8067   SDValue* HiAdd = nullptr;
8068   SDValue* LoMul = nullptr;
8069   SDValue* LowAdd = nullptr;
8070
8071   if (IsLeftOperandMUL)
8072     HiAdd = &AddeOp1;
8073   else
8074     HiAdd = &AddeOp0;
8075
8076
8077   if (AddcOp0->getOpcode() == Opc) {
8078     LoMul = &AddcOp0;
8079     LowAdd = &AddcOp1;
8080   }
8081   if (AddcOp1->getOpcode() == Opc) {
8082     LoMul = &AddcOp1;
8083     LowAdd = &AddcOp0;
8084   }
8085
8086   if (!LoMul)
8087     return SDValue();
8088
8089   if (LoMul->getNode() != HiMul->getNode())
8090     return SDValue();
8091
8092   // Create the merged node.
8093   SelectionDAG &DAG = DCI.DAG;
8094
8095   // Build operand list.
8096   SmallVector<SDValue, 8> Ops;
8097   Ops.push_back(LoMul->getOperand(0));
8098   Ops.push_back(LoMul->getOperand(1));
8099   Ops.push_back(*LowAdd);
8100   Ops.push_back(*HiAdd);
8101
8102   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8103                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8104
8105   // Replace the ADDs' nodes uses by the MLA node's values.
8106   SDValue HiMLALResult(MLALNode.getNode(), 1);
8107   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8108
8109   SDValue LoMLALResult(MLALNode.getNode(), 0);
8110   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8111
8112   // Return original node to notify the driver to stop replacing.
8113   SDValue resNode(AddcNode, 0);
8114   return resNode;
8115 }
8116
8117 /// PerformADDCCombine - Target-specific dag combine transform from
8118 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8119 static SDValue PerformADDCCombine(SDNode *N,
8120                                  TargetLowering::DAGCombinerInfo &DCI,
8121                                  const ARMSubtarget *Subtarget) {
8122
8123   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8124
8125 }
8126
8127 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8128 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8129 /// called with the default operands, and if that fails, with commuted
8130 /// operands.
8131 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8132                                           TargetLowering::DAGCombinerInfo &DCI,
8133                                           const ARMSubtarget *Subtarget){
8134
8135   // Attempt to create vpaddl for this add.
8136   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8137   if (Result.getNode())
8138     return Result;
8139
8140   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8141   if (N0.getNode()->hasOneUse()) {
8142     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8143     if (Result.getNode()) return Result;
8144   }
8145   return SDValue();
8146 }
8147
8148 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8149 ///
8150 static SDValue PerformADDCombine(SDNode *N,
8151                                  TargetLowering::DAGCombinerInfo &DCI,
8152                                  const ARMSubtarget *Subtarget) {
8153   SDValue N0 = N->getOperand(0);
8154   SDValue N1 = N->getOperand(1);
8155
8156   // First try with the default operand order.
8157   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8158   if (Result.getNode())
8159     return Result;
8160
8161   // If that didn't work, try again with the operands commuted.
8162   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8163 }
8164
8165 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8166 ///
8167 static SDValue PerformSUBCombine(SDNode *N,
8168                                  TargetLowering::DAGCombinerInfo &DCI) {
8169   SDValue N0 = N->getOperand(0);
8170   SDValue N1 = N->getOperand(1);
8171
8172   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8173   if (N1.getNode()->hasOneUse()) {
8174     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8175     if (Result.getNode()) return Result;
8176   }
8177
8178   return SDValue();
8179 }
8180
8181 /// PerformVMULCombine
8182 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8183 /// special multiplier accumulator forwarding.
8184 ///   vmul d3, d0, d2
8185 ///   vmla d3, d1, d2
8186 /// is faster than
8187 ///   vadd d3, d0, d1
8188 ///   vmul d3, d3, d2
8189 //  However, for (A + B) * (A + B),
8190 //    vadd d2, d0, d1
8191 //    vmul d3, d0, d2
8192 //    vmla d3, d1, d2
8193 //  is slower than
8194 //    vadd d2, d0, d1
8195 //    vmul d3, d2, d2
8196 static SDValue PerformVMULCombine(SDNode *N,
8197                                   TargetLowering::DAGCombinerInfo &DCI,
8198                                   const ARMSubtarget *Subtarget) {
8199   if (!Subtarget->hasVMLxForwarding())
8200     return SDValue();
8201
8202   SelectionDAG &DAG = DCI.DAG;
8203   SDValue N0 = N->getOperand(0);
8204   SDValue N1 = N->getOperand(1);
8205   unsigned Opcode = N0.getOpcode();
8206   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8207       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8208     Opcode = N1.getOpcode();
8209     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8210         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8211       return SDValue();
8212     std::swap(N0, N1);
8213   }
8214
8215   if (N0 == N1)
8216     return SDValue();
8217
8218   EVT VT = N->getValueType(0);
8219   SDLoc DL(N);
8220   SDValue N00 = N0->getOperand(0);
8221   SDValue N01 = N0->getOperand(1);
8222   return DAG.getNode(Opcode, DL, VT,
8223                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8224                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8225 }
8226
8227 static SDValue PerformMULCombine(SDNode *N,
8228                                  TargetLowering::DAGCombinerInfo &DCI,
8229                                  const ARMSubtarget *Subtarget) {
8230   SelectionDAG &DAG = DCI.DAG;
8231
8232   if (Subtarget->isThumb1Only())
8233     return SDValue();
8234
8235   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8236     return SDValue();
8237
8238   EVT VT = N->getValueType(0);
8239   if (VT.is64BitVector() || VT.is128BitVector())
8240     return PerformVMULCombine(N, DCI, Subtarget);
8241   if (VT != MVT::i32)
8242     return SDValue();
8243
8244   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8245   if (!C)
8246     return SDValue();
8247
8248   int64_t MulAmt = C->getSExtValue();
8249   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8250
8251   ShiftAmt = ShiftAmt & (32 - 1);
8252   SDValue V = N->getOperand(0);
8253   SDLoc DL(N);
8254
8255   SDValue Res;
8256   MulAmt >>= ShiftAmt;
8257
8258   if (MulAmt >= 0) {
8259     if (isPowerOf2_32(MulAmt - 1)) {
8260       // (mul x, 2^N + 1) => (add (shl x, N), x)
8261       Res = DAG.getNode(ISD::ADD, DL, VT,
8262                         V,
8263                         DAG.getNode(ISD::SHL, DL, VT,
8264                                     V,
8265                                     DAG.getConstant(Log2_32(MulAmt - 1),
8266                                                     MVT::i32)));
8267     } else if (isPowerOf2_32(MulAmt + 1)) {
8268       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8269       Res = DAG.getNode(ISD::SUB, DL, VT,
8270                         DAG.getNode(ISD::SHL, DL, VT,
8271                                     V,
8272                                     DAG.getConstant(Log2_32(MulAmt + 1),
8273                                                     MVT::i32)),
8274                         V);
8275     } else
8276       return SDValue();
8277   } else {
8278     uint64_t MulAmtAbs = -MulAmt;
8279     if (isPowerOf2_32(MulAmtAbs + 1)) {
8280       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8281       Res = DAG.getNode(ISD::SUB, DL, VT,
8282                         V,
8283                         DAG.getNode(ISD::SHL, DL, VT,
8284                                     V,
8285                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8286                                                     MVT::i32)));
8287     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8288       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8289       Res = DAG.getNode(ISD::ADD, DL, VT,
8290                         V,
8291                         DAG.getNode(ISD::SHL, DL, VT,
8292                                     V,
8293                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8294                                                     MVT::i32)));
8295       Res = DAG.getNode(ISD::SUB, DL, VT,
8296                         DAG.getConstant(0, MVT::i32),Res);
8297
8298     } else
8299       return SDValue();
8300   }
8301
8302   if (ShiftAmt != 0)
8303     Res = DAG.getNode(ISD::SHL, DL, VT,
8304                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8305
8306   // Do not add new nodes to DAG combiner worklist.
8307   DCI.CombineTo(N, Res, false);
8308   return SDValue();
8309 }
8310
8311 static SDValue PerformANDCombine(SDNode *N,
8312                                  TargetLowering::DAGCombinerInfo &DCI,
8313                                  const ARMSubtarget *Subtarget) {
8314
8315   // Attempt to use immediate-form VBIC
8316   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8317   SDLoc dl(N);
8318   EVT VT = N->getValueType(0);
8319   SelectionDAG &DAG = DCI.DAG;
8320
8321   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8322     return SDValue();
8323
8324   APInt SplatBits, SplatUndef;
8325   unsigned SplatBitSize;
8326   bool HasAnyUndefs;
8327   if (BVN &&
8328       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8329     if (SplatBitSize <= 64) {
8330       EVT VbicVT;
8331       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8332                                       SplatUndef.getZExtValue(), SplatBitSize,
8333                                       DAG, VbicVT, VT.is128BitVector(),
8334                                       OtherModImm);
8335       if (Val.getNode()) {
8336         SDValue Input =
8337           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8338         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8339         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8340       }
8341     }
8342   }
8343
8344   if (!Subtarget->isThumb1Only()) {
8345     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8346     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8347     if (Result.getNode())
8348       return Result;
8349   }
8350
8351   return SDValue();
8352 }
8353
8354 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8355 static SDValue PerformORCombine(SDNode *N,
8356                                 TargetLowering::DAGCombinerInfo &DCI,
8357                                 const ARMSubtarget *Subtarget) {
8358   // Attempt to use immediate-form VORR
8359   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8360   SDLoc dl(N);
8361   EVT VT = N->getValueType(0);
8362   SelectionDAG &DAG = DCI.DAG;
8363
8364   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8365     return SDValue();
8366
8367   APInt SplatBits, SplatUndef;
8368   unsigned SplatBitSize;
8369   bool HasAnyUndefs;
8370   if (BVN && Subtarget->hasNEON() &&
8371       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8372     if (SplatBitSize <= 64) {
8373       EVT VorrVT;
8374       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8375                                       SplatUndef.getZExtValue(), SplatBitSize,
8376                                       DAG, VorrVT, VT.is128BitVector(),
8377                                       OtherModImm);
8378       if (Val.getNode()) {
8379         SDValue Input =
8380           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8381         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8382         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8383       }
8384     }
8385   }
8386
8387   if (!Subtarget->isThumb1Only()) {
8388     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8389     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8390     if (Result.getNode())
8391       return Result;
8392   }
8393
8394   // The code below optimizes (or (and X, Y), Z).
8395   // The AND operand needs to have a single user to make these optimizations
8396   // profitable.
8397   SDValue N0 = N->getOperand(0);
8398   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8399     return SDValue();
8400   SDValue N1 = N->getOperand(1);
8401
8402   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8403   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8404       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8405     APInt SplatUndef;
8406     unsigned SplatBitSize;
8407     bool HasAnyUndefs;
8408
8409     APInt SplatBits0, SplatBits1;
8410     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8411     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8412     // Ensure that the second operand of both ands are constants
8413     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8414                                       HasAnyUndefs) && !HasAnyUndefs) {
8415         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8416                                           HasAnyUndefs) && !HasAnyUndefs) {
8417             // Ensure that the bit width of the constants are the same and that
8418             // the splat arguments are logical inverses as per the pattern we
8419             // are trying to simplify.
8420             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8421                 SplatBits0 == ~SplatBits1) {
8422                 // Canonicalize the vector type to make instruction selection
8423                 // simpler.
8424                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8425                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8426                                              N0->getOperand(1),
8427                                              N0->getOperand(0),
8428                                              N1->getOperand(0));
8429                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8430             }
8431         }
8432     }
8433   }
8434
8435   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8436   // reasonable.
8437
8438   // BFI is only available on V6T2+
8439   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8440     return SDValue();
8441
8442   SDLoc DL(N);
8443   // 1) or (and A, mask), val => ARMbfi A, val, mask
8444   //      iff (val & mask) == val
8445   //
8446   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8447   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8448   //          && mask == ~mask2
8449   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8450   //          && ~mask == mask2
8451   //  (i.e., copy a bitfield value into another bitfield of the same width)
8452
8453   if (VT != MVT::i32)
8454     return SDValue();
8455
8456   SDValue N00 = N0.getOperand(0);
8457
8458   // The value and the mask need to be constants so we can verify this is
8459   // actually a bitfield set. If the mask is 0xffff, we can do better
8460   // via a movt instruction, so don't use BFI in that case.
8461   SDValue MaskOp = N0.getOperand(1);
8462   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8463   if (!MaskC)
8464     return SDValue();
8465   unsigned Mask = MaskC->getZExtValue();
8466   if (Mask == 0xffff)
8467     return SDValue();
8468   SDValue Res;
8469   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8470   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8471   if (N1C) {
8472     unsigned Val = N1C->getZExtValue();
8473     if ((Val & ~Mask) != Val)
8474       return SDValue();
8475
8476     if (ARM::isBitFieldInvertedMask(Mask)) {
8477       Val >>= countTrailingZeros(~Mask);
8478
8479       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8480                         DAG.getConstant(Val, MVT::i32),
8481                         DAG.getConstant(Mask, MVT::i32));
8482
8483       // Do not add new nodes to DAG combiner worklist.
8484       DCI.CombineTo(N, Res, false);
8485       return SDValue();
8486     }
8487   } else if (N1.getOpcode() == ISD::AND) {
8488     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8489     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8490     if (!N11C)
8491       return SDValue();
8492     unsigned Mask2 = N11C->getZExtValue();
8493
8494     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8495     // as is to match.
8496     if (ARM::isBitFieldInvertedMask(Mask) &&
8497         (Mask == ~Mask2)) {
8498       // The pack halfword instruction works better for masks that fit it,
8499       // so use that when it's available.
8500       if (Subtarget->hasT2ExtractPack() &&
8501           (Mask == 0xffff || Mask == 0xffff0000))
8502         return SDValue();
8503       // 2a
8504       unsigned amt = countTrailingZeros(Mask2);
8505       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8506                         DAG.getConstant(amt, MVT::i32));
8507       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8508                         DAG.getConstant(Mask, MVT::i32));
8509       // Do not add new nodes to DAG combiner worklist.
8510       DCI.CombineTo(N, Res, false);
8511       return SDValue();
8512     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8513                (~Mask == Mask2)) {
8514       // The pack halfword instruction works better for masks that fit it,
8515       // so use that when it's available.
8516       if (Subtarget->hasT2ExtractPack() &&
8517           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8518         return SDValue();
8519       // 2b
8520       unsigned lsb = countTrailingZeros(Mask);
8521       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8522                         DAG.getConstant(lsb, MVT::i32));
8523       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8524                         DAG.getConstant(Mask2, MVT::i32));
8525       // Do not add new nodes to DAG combiner worklist.
8526       DCI.CombineTo(N, Res, false);
8527       return SDValue();
8528     }
8529   }
8530
8531   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8532       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8533       ARM::isBitFieldInvertedMask(~Mask)) {
8534     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8535     // where lsb(mask) == #shamt and masked bits of B are known zero.
8536     SDValue ShAmt = N00.getOperand(1);
8537     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8538     unsigned LSB = countTrailingZeros(Mask);
8539     if (ShAmtC != LSB)
8540       return SDValue();
8541
8542     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8543                       DAG.getConstant(~Mask, MVT::i32));
8544
8545     // Do not add new nodes to DAG combiner worklist.
8546     DCI.CombineTo(N, Res, false);
8547   }
8548
8549   return SDValue();
8550 }
8551
8552 static SDValue PerformXORCombine(SDNode *N,
8553                                  TargetLowering::DAGCombinerInfo &DCI,
8554                                  const ARMSubtarget *Subtarget) {
8555   EVT VT = N->getValueType(0);
8556   SelectionDAG &DAG = DCI.DAG;
8557
8558   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8559     return SDValue();
8560
8561   if (!Subtarget->isThumb1Only()) {
8562     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8563     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8564     if (Result.getNode())
8565       return Result;
8566   }
8567
8568   return SDValue();
8569 }
8570
8571 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8572 /// the bits being cleared by the AND are not demanded by the BFI.
8573 static SDValue PerformBFICombine(SDNode *N,
8574                                  TargetLowering::DAGCombinerInfo &DCI) {
8575   SDValue N1 = N->getOperand(1);
8576   if (N1.getOpcode() == ISD::AND) {
8577     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8578     if (!N11C)
8579       return SDValue();
8580     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8581     unsigned LSB = countTrailingZeros(~InvMask);
8582     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8583     unsigned Mask = (1 << Width)-1;
8584     unsigned Mask2 = N11C->getZExtValue();
8585     if ((Mask & (~Mask2)) == 0)
8586       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8587                              N->getOperand(0), N1.getOperand(0),
8588                              N->getOperand(2));
8589   }
8590   return SDValue();
8591 }
8592
8593 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8594 /// ARMISD::VMOVRRD.
8595 static SDValue PerformVMOVRRDCombine(SDNode *N,
8596                                      TargetLowering::DAGCombinerInfo &DCI,
8597                                      const ARMSubtarget *Subtarget) {
8598   // vmovrrd(vmovdrr x, y) -> x,y
8599   SDValue InDouble = N->getOperand(0);
8600   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8601     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8602
8603   // vmovrrd(load f64) -> (load i32), (load i32)
8604   SDNode *InNode = InDouble.getNode();
8605   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8606       InNode->getValueType(0) == MVT::f64 &&
8607       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8608       !cast<LoadSDNode>(InNode)->isVolatile()) {
8609     // TODO: Should this be done for non-FrameIndex operands?
8610     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8611
8612     SelectionDAG &DAG = DCI.DAG;
8613     SDLoc DL(LD);
8614     SDValue BasePtr = LD->getBasePtr();
8615     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8616                                  LD->getPointerInfo(), LD->isVolatile(),
8617                                  LD->isNonTemporal(), LD->isInvariant(),
8618                                  LD->getAlignment());
8619
8620     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8621                                     DAG.getConstant(4, MVT::i32));
8622     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8623                                  LD->getPointerInfo(), LD->isVolatile(),
8624                                  LD->isNonTemporal(), LD->isInvariant(),
8625                                  std::min(4U, LD->getAlignment() / 2));
8626
8627     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8628     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8629       std::swap (NewLD1, NewLD2);
8630     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8631     return Result;
8632   }
8633
8634   return SDValue();
8635 }
8636
8637 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8638 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8639 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8640   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8641   SDValue Op0 = N->getOperand(0);
8642   SDValue Op1 = N->getOperand(1);
8643   if (Op0.getOpcode() == ISD::BITCAST)
8644     Op0 = Op0.getOperand(0);
8645   if (Op1.getOpcode() == ISD::BITCAST)
8646     Op1 = Op1.getOperand(0);
8647   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8648       Op0.getNode() == Op1.getNode() &&
8649       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8650     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8651                        N->getValueType(0), Op0.getOperand(0));
8652   return SDValue();
8653 }
8654
8655 /// PerformSTORECombine - Target-specific dag combine xforms for
8656 /// ISD::STORE.
8657 static SDValue PerformSTORECombine(SDNode *N,
8658                                    TargetLowering::DAGCombinerInfo &DCI) {
8659   StoreSDNode *St = cast<StoreSDNode>(N);
8660   if (St->isVolatile())
8661     return SDValue();
8662
8663   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8664   // pack all of the elements in one place.  Next, store to memory in fewer
8665   // chunks.
8666   SDValue StVal = St->getValue();
8667   EVT VT = StVal.getValueType();
8668   if (St->isTruncatingStore() && VT.isVector()) {
8669     SelectionDAG &DAG = DCI.DAG;
8670     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8671     EVT StVT = St->getMemoryVT();
8672     unsigned NumElems = VT.getVectorNumElements();
8673     assert(StVT != VT && "Cannot truncate to the same type");
8674     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8675     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8676
8677     // From, To sizes and ElemCount must be pow of two
8678     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8679
8680     // We are going to use the original vector elt for storing.
8681     // Accumulated smaller vector elements must be a multiple of the store size.
8682     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8683
8684     unsigned SizeRatio  = FromEltSz / ToEltSz;
8685     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8686
8687     // Create a type on which we perform the shuffle.
8688     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8689                                      NumElems*SizeRatio);
8690     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8691
8692     SDLoc DL(St);
8693     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8694     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8695     for (unsigned i = 0; i < NumElems; ++i)
8696       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8697
8698     // Can't shuffle using an illegal type.
8699     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8700
8701     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8702                                 DAG.getUNDEF(WideVec.getValueType()),
8703                                 ShuffleVec.data());
8704     // At this point all of the data is stored at the bottom of the
8705     // register. We now need to save it to mem.
8706
8707     // Find the largest store unit
8708     MVT StoreType = MVT::i8;
8709     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8710          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8711       MVT Tp = (MVT::SimpleValueType)tp;
8712       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8713         StoreType = Tp;
8714     }
8715     // Didn't find a legal store type.
8716     if (!TLI.isTypeLegal(StoreType))
8717       return SDValue();
8718
8719     // Bitcast the original vector into a vector of store-size units
8720     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8721             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8722     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8723     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8724     SmallVector<SDValue, 8> Chains;
8725     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8726                                         TLI.getPointerTy());
8727     SDValue BasePtr = St->getBasePtr();
8728
8729     // Perform one or more big stores into memory.
8730     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8731     for (unsigned I = 0; I < E; I++) {
8732       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8733                                    StoreType, ShuffWide,
8734                                    DAG.getIntPtrConstant(I));
8735       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8736                                 St->getPointerInfo(), St->isVolatile(),
8737                                 St->isNonTemporal(), St->getAlignment());
8738       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8739                             Increment);
8740       Chains.push_back(Ch);
8741     }
8742     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8743   }
8744
8745   if (!ISD::isNormalStore(St))
8746     return SDValue();
8747
8748   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8749   // ARM stores of arguments in the same cache line.
8750   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8751       StVal.getNode()->hasOneUse()) {
8752     SelectionDAG  &DAG = DCI.DAG;
8753     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8754     SDLoc DL(St);
8755     SDValue BasePtr = St->getBasePtr();
8756     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8757                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8758                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8759                                   St->isNonTemporal(), St->getAlignment());
8760
8761     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8762                                     DAG.getConstant(4, MVT::i32));
8763     return DAG.getStore(NewST1.getValue(0), DL,
8764                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8765                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8766                         St->isNonTemporal(),
8767                         std::min(4U, St->getAlignment() / 2));
8768   }
8769
8770   if (StVal.getValueType() != MVT::i64 ||
8771       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8772     return SDValue();
8773
8774   // Bitcast an i64 store extracted from a vector to f64.
8775   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8776   SelectionDAG &DAG = DCI.DAG;
8777   SDLoc dl(StVal);
8778   SDValue IntVec = StVal.getOperand(0);
8779   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8780                                  IntVec.getValueType().getVectorNumElements());
8781   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8782   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8783                                Vec, StVal.getOperand(1));
8784   dl = SDLoc(N);
8785   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8786   // Make the DAGCombiner fold the bitcasts.
8787   DCI.AddToWorklist(Vec.getNode());
8788   DCI.AddToWorklist(ExtElt.getNode());
8789   DCI.AddToWorklist(V.getNode());
8790   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8791                       St->getPointerInfo(), St->isVolatile(),
8792                       St->isNonTemporal(), St->getAlignment(),
8793                       St->getAAInfo());
8794 }
8795
8796 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8797 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8798 /// i64 vector to have f64 elements, since the value can then be loaded
8799 /// directly into a VFP register.
8800 static bool hasNormalLoadOperand(SDNode *N) {
8801   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8802   for (unsigned i = 0; i < NumElts; ++i) {
8803     SDNode *Elt = N->getOperand(i).getNode();
8804     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8805       return true;
8806   }
8807   return false;
8808 }
8809
8810 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8811 /// ISD::BUILD_VECTOR.
8812 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8813                                           TargetLowering::DAGCombinerInfo &DCI,
8814                                           const ARMSubtarget *Subtarget) {
8815   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8816   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8817   // into a pair of GPRs, which is fine when the value is used as a scalar,
8818   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8819   SelectionDAG &DAG = DCI.DAG;
8820   if (N->getNumOperands() == 2) {
8821     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8822     if (RV.getNode())
8823       return RV;
8824   }
8825
8826   // Load i64 elements as f64 values so that type legalization does not split
8827   // them up into i32 values.
8828   EVT VT = N->getValueType(0);
8829   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8830     return SDValue();
8831   SDLoc dl(N);
8832   SmallVector<SDValue, 8> Ops;
8833   unsigned NumElts = VT.getVectorNumElements();
8834   for (unsigned i = 0; i < NumElts; ++i) {
8835     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8836     Ops.push_back(V);
8837     // Make the DAGCombiner fold the bitcast.
8838     DCI.AddToWorklist(V.getNode());
8839   }
8840   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8841   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8842   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8843 }
8844
8845 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8846 static SDValue
8847 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8848   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8849   // At that time, we may have inserted bitcasts from integer to float.
8850   // If these bitcasts have survived DAGCombine, change the lowering of this
8851   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8852   // force to use floating point types.
8853
8854   // Make sure we can change the type of the vector.
8855   // This is possible iff:
8856   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8857   //    1.1. Vector is used only once.
8858   //    1.2. Use is a bit convert to an integer type.
8859   // 2. The size of its operands are 32-bits (64-bits are not legal).
8860   EVT VT = N->getValueType(0);
8861   EVT EltVT = VT.getVectorElementType();
8862
8863   // Check 1.1. and 2.
8864   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8865     return SDValue();
8866
8867   // By construction, the input type must be float.
8868   assert(EltVT == MVT::f32 && "Unexpected type!");
8869
8870   // Check 1.2.
8871   SDNode *Use = *N->use_begin();
8872   if (Use->getOpcode() != ISD::BITCAST ||
8873       Use->getValueType(0).isFloatingPoint())
8874     return SDValue();
8875
8876   // Check profitability.
8877   // Model is, if more than half of the relevant operands are bitcast from
8878   // i32, turn the build_vector into a sequence of insert_vector_elt.
8879   // Relevant operands are everything that is not statically
8880   // (i.e., at compile time) bitcasted.
8881   unsigned NumOfBitCastedElts = 0;
8882   unsigned NumElts = VT.getVectorNumElements();
8883   unsigned NumOfRelevantElts = NumElts;
8884   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8885     SDValue Elt = N->getOperand(Idx);
8886     if (Elt->getOpcode() == ISD::BITCAST) {
8887       // Assume only bit cast to i32 will go away.
8888       if (Elt->getOperand(0).getValueType() == MVT::i32)
8889         ++NumOfBitCastedElts;
8890     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8891       // Constants are statically casted, thus do not count them as
8892       // relevant operands.
8893       --NumOfRelevantElts;
8894   }
8895
8896   // Check if more than half of the elements require a non-free bitcast.
8897   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8898     return SDValue();
8899
8900   SelectionDAG &DAG = DCI.DAG;
8901   // Create the new vector type.
8902   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8903   // Check if the type is legal.
8904   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8905   if (!TLI.isTypeLegal(VecVT))
8906     return SDValue();
8907
8908   // Combine:
8909   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8910   // => BITCAST INSERT_VECTOR_ELT
8911   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8912   //                      (BITCAST EN), N.
8913   SDValue Vec = DAG.getUNDEF(VecVT);
8914   SDLoc dl(N);
8915   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8916     SDValue V = N->getOperand(Idx);
8917     if (V.getOpcode() == ISD::UNDEF)
8918       continue;
8919     if (V.getOpcode() == ISD::BITCAST &&
8920         V->getOperand(0).getValueType() == MVT::i32)
8921       // Fold obvious case.
8922       V = V.getOperand(0);
8923     else {
8924       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8925       // Make the DAGCombiner fold the bitcasts.
8926       DCI.AddToWorklist(V.getNode());
8927     }
8928     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8929     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8930   }
8931   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8932   // Make the DAGCombiner fold the bitcasts.
8933   DCI.AddToWorklist(Vec.getNode());
8934   return Vec;
8935 }
8936
8937 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8938 /// ISD::INSERT_VECTOR_ELT.
8939 static SDValue PerformInsertEltCombine(SDNode *N,
8940                                        TargetLowering::DAGCombinerInfo &DCI) {
8941   // Bitcast an i64 load inserted into a vector to f64.
8942   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8943   EVT VT = N->getValueType(0);
8944   SDNode *Elt = N->getOperand(1).getNode();
8945   if (VT.getVectorElementType() != MVT::i64 ||
8946       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8947     return SDValue();
8948
8949   SelectionDAG &DAG = DCI.DAG;
8950   SDLoc dl(N);
8951   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8952                                  VT.getVectorNumElements());
8953   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8954   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8955   // Make the DAGCombiner fold the bitcasts.
8956   DCI.AddToWorklist(Vec.getNode());
8957   DCI.AddToWorklist(V.getNode());
8958   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8959                                Vec, V, N->getOperand(2));
8960   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8961 }
8962
8963 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8964 /// ISD::VECTOR_SHUFFLE.
8965 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8966   // The LLVM shufflevector instruction does not require the shuffle mask
8967   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8968   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8969   // operands do not match the mask length, they are extended by concatenating
8970   // them with undef vectors.  That is probably the right thing for other
8971   // targets, but for NEON it is better to concatenate two double-register
8972   // size vector operands into a single quad-register size vector.  Do that
8973   // transformation here:
8974   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8975   //   shuffle(concat(v1, v2), undef)
8976   SDValue Op0 = N->getOperand(0);
8977   SDValue Op1 = N->getOperand(1);
8978   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8979       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8980       Op0.getNumOperands() != 2 ||
8981       Op1.getNumOperands() != 2)
8982     return SDValue();
8983   SDValue Concat0Op1 = Op0.getOperand(1);
8984   SDValue Concat1Op1 = Op1.getOperand(1);
8985   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8986       Concat1Op1.getOpcode() != ISD::UNDEF)
8987     return SDValue();
8988   // Skip the transformation if any of the types are illegal.
8989   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8990   EVT VT = N->getValueType(0);
8991   if (!TLI.isTypeLegal(VT) ||
8992       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8993       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8994     return SDValue();
8995
8996   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8997                                   Op0.getOperand(0), Op1.getOperand(0));
8998   // Translate the shuffle mask.
8999   SmallVector<int, 16> NewMask;
9000   unsigned NumElts = VT.getVectorNumElements();
9001   unsigned HalfElts = NumElts/2;
9002   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9003   for (unsigned n = 0; n < NumElts; ++n) {
9004     int MaskElt = SVN->getMaskElt(n);
9005     int NewElt = -1;
9006     if (MaskElt < (int)HalfElts)
9007       NewElt = MaskElt;
9008     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9009       NewElt = HalfElts + MaskElt - NumElts;
9010     NewMask.push_back(NewElt);
9011   }
9012   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9013                               DAG.getUNDEF(VT), NewMask.data());
9014 }
9015
9016 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9017 /// NEON load/store intrinsics to merge base address updates.
9018 static SDValue CombineBaseUpdate(SDNode *N,
9019                                  TargetLowering::DAGCombinerInfo &DCI) {
9020   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9021     return SDValue();
9022
9023   SelectionDAG &DAG = DCI.DAG;
9024   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9025                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9026   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9027   SDValue Addr = N->getOperand(AddrOpIdx);
9028
9029   // Search for a use of the address operand that is an increment.
9030   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9031          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9032     SDNode *User = *UI;
9033     if (User->getOpcode() != ISD::ADD ||
9034         UI.getUse().getResNo() != Addr.getResNo())
9035       continue;
9036
9037     // Check that the add is independent of the load/store.  Otherwise, folding
9038     // it would create a cycle.
9039     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9040       continue;
9041
9042     // Find the new opcode for the updating load/store.
9043     bool isLoad = true;
9044     bool isLaneOp = false;
9045     unsigned NewOpc = 0;
9046     unsigned NumVecs = 0;
9047     if (isIntrinsic) {
9048       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9049       switch (IntNo) {
9050       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9051       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9052         NumVecs = 1; break;
9053       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9054         NumVecs = 2; break;
9055       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9056         NumVecs = 3; break;
9057       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9058         NumVecs = 4; break;
9059       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9060         NumVecs = 2; isLaneOp = true; break;
9061       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9062         NumVecs = 3; isLaneOp = true; break;
9063       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9064         NumVecs = 4; isLaneOp = true; break;
9065       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9066         NumVecs = 1; isLoad = false; break;
9067       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9068         NumVecs = 2; isLoad = false; break;
9069       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9070         NumVecs = 3; isLoad = false; break;
9071       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9072         NumVecs = 4; isLoad = false; break;
9073       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9074         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9075       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9076         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9077       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9078         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9079       }
9080     } else {
9081       isLaneOp = true;
9082       switch (N->getOpcode()) {
9083       default: llvm_unreachable("unexpected opcode for Neon base update");
9084       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9085       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9086       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9087       }
9088     }
9089
9090     // Find the size of memory referenced by the load/store.
9091     EVT VecTy;
9092     if (isLoad)
9093       VecTy = N->getValueType(0);
9094     else
9095       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9096     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9097     if (isLaneOp)
9098       NumBytes /= VecTy.getVectorNumElements();
9099
9100     // If the increment is a constant, it must match the memory ref size.
9101     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9102     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9103       uint64_t IncVal = CInc->getZExtValue();
9104       if (IncVal != NumBytes)
9105         continue;
9106     } else if (NumBytes >= 3 * 16) {
9107       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9108       // separate instructions that make it harder to use a non-constant update.
9109       continue;
9110     }
9111
9112     // Create the new updating load/store node.
9113     EVT Tys[6];
9114     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9115     unsigned n;
9116     for (n = 0; n < NumResultVecs; ++n)
9117       Tys[n] = VecTy;
9118     Tys[n++] = MVT::i32;
9119     Tys[n] = MVT::Other;
9120     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
9121     SmallVector<SDValue, 8> Ops;
9122     Ops.push_back(N->getOperand(0)); // incoming chain
9123     Ops.push_back(N->getOperand(AddrOpIdx));
9124     Ops.push_back(Inc);
9125     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9126       Ops.push_back(N->getOperand(i));
9127     }
9128     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9129     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9130                                            Ops, MemInt->getMemoryVT(),
9131                                            MemInt->getMemOperand());
9132
9133     // Update the uses.
9134     std::vector<SDValue> NewResults;
9135     for (unsigned i = 0; i < NumResultVecs; ++i) {
9136       NewResults.push_back(SDValue(UpdN.getNode(), i));
9137     }
9138     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9139     DCI.CombineTo(N, NewResults);
9140     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9141
9142     break;
9143   }
9144   return SDValue();
9145 }
9146
9147 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9148 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9149 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9150 /// return true.
9151 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9152   SelectionDAG &DAG = DCI.DAG;
9153   EVT VT = N->getValueType(0);
9154   // vldN-dup instructions only support 64-bit vectors for N > 1.
9155   if (!VT.is64BitVector())
9156     return false;
9157
9158   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9159   SDNode *VLD = N->getOperand(0).getNode();
9160   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9161     return false;
9162   unsigned NumVecs = 0;
9163   unsigned NewOpc = 0;
9164   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9165   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9166     NumVecs = 2;
9167     NewOpc = ARMISD::VLD2DUP;
9168   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9169     NumVecs = 3;
9170     NewOpc = ARMISD::VLD3DUP;
9171   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9172     NumVecs = 4;
9173     NewOpc = ARMISD::VLD4DUP;
9174   } else {
9175     return false;
9176   }
9177
9178   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9179   // numbers match the load.
9180   unsigned VLDLaneNo =
9181     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9182   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9183        UI != UE; ++UI) {
9184     // Ignore uses of the chain result.
9185     if (UI.getUse().getResNo() == NumVecs)
9186       continue;
9187     SDNode *User = *UI;
9188     if (User->getOpcode() != ARMISD::VDUPLANE ||
9189         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9190       return false;
9191   }
9192
9193   // Create the vldN-dup node.
9194   EVT Tys[5];
9195   unsigned n;
9196   for (n = 0; n < NumVecs; ++n)
9197     Tys[n] = VT;
9198   Tys[n] = MVT::Other;
9199   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9200   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9201   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9202   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9203                                            Ops, VLDMemInt->getMemoryVT(),
9204                                            VLDMemInt->getMemOperand());
9205
9206   // Update the uses.
9207   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9208        UI != UE; ++UI) {
9209     unsigned ResNo = UI.getUse().getResNo();
9210     // Ignore uses of the chain result.
9211     if (ResNo == NumVecs)
9212       continue;
9213     SDNode *User = *UI;
9214     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9215   }
9216
9217   // Now the vldN-lane intrinsic is dead except for its chain result.
9218   // Update uses of the chain.
9219   std::vector<SDValue> VLDDupResults;
9220   for (unsigned n = 0; n < NumVecs; ++n)
9221     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9222   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9223   DCI.CombineTo(VLD, VLDDupResults);
9224
9225   return true;
9226 }
9227
9228 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9229 /// ARMISD::VDUPLANE.
9230 static SDValue PerformVDUPLANECombine(SDNode *N,
9231                                       TargetLowering::DAGCombinerInfo &DCI) {
9232   SDValue Op = N->getOperand(0);
9233
9234   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9235   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9236   if (CombineVLDDUP(N, DCI))
9237     return SDValue(N, 0);
9238
9239   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9240   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9241   while (Op.getOpcode() == ISD::BITCAST)
9242     Op = Op.getOperand(0);
9243   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9244     return SDValue();
9245
9246   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9247   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9248   // The canonical VMOV for a zero vector uses a 32-bit element size.
9249   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9250   unsigned EltBits;
9251   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9252     EltSize = 8;
9253   EVT VT = N->getValueType(0);
9254   if (EltSize > VT.getVectorElementType().getSizeInBits())
9255     return SDValue();
9256
9257   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9258 }
9259
9260 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9261 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9262 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9263 {
9264   integerPart cN;
9265   integerPart c0 = 0;
9266   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9267        I != E; I++) {
9268     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9269     if (!C)
9270       return false;
9271
9272     bool isExact;
9273     APFloat APF = C->getValueAPF();
9274     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9275         != APFloat::opOK || !isExact)
9276       return false;
9277
9278     c0 = (I == 0) ? cN : c0;
9279     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9280       return false;
9281   }
9282   C = c0;
9283   return true;
9284 }
9285
9286 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9287 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9288 /// when the VMUL has a constant operand that is a power of 2.
9289 ///
9290 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9291 ///  vmul.f32        d16, d17, d16
9292 ///  vcvt.s32.f32    d16, d16
9293 /// becomes:
9294 ///  vcvt.s32.f32    d16, d16, #3
9295 static SDValue PerformVCVTCombine(SDNode *N,
9296                                   TargetLowering::DAGCombinerInfo &DCI,
9297                                   const ARMSubtarget *Subtarget) {
9298   SelectionDAG &DAG = DCI.DAG;
9299   SDValue Op = N->getOperand(0);
9300
9301   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9302       Op.getOpcode() != ISD::FMUL)
9303     return SDValue();
9304
9305   uint64_t C;
9306   SDValue N0 = Op->getOperand(0);
9307   SDValue ConstVec = Op->getOperand(1);
9308   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9309
9310   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9311       !isConstVecPow2(ConstVec, isSigned, C))
9312     return SDValue();
9313
9314   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9315   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9316   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9317     // These instructions only exist converting from f32 to i32. We can handle
9318     // smaller integers by generating an extra truncate, but larger ones would
9319     // be lossy.
9320     return SDValue();
9321   }
9322
9323   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9324     Intrinsic::arm_neon_vcvtfp2fxu;
9325   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9326   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9327                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9328                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9329                                  DAG.getConstant(Log2_64(C), MVT::i32));
9330
9331   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9332     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9333
9334   return FixConv;
9335 }
9336
9337 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9338 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9339 /// when the VDIV has a constant operand that is a power of 2.
9340 ///
9341 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9342 ///  vcvt.f32.s32    d16, d16
9343 ///  vdiv.f32        d16, d17, d16
9344 /// becomes:
9345 ///  vcvt.f32.s32    d16, d16, #3
9346 static SDValue PerformVDIVCombine(SDNode *N,
9347                                   TargetLowering::DAGCombinerInfo &DCI,
9348                                   const ARMSubtarget *Subtarget) {
9349   SelectionDAG &DAG = DCI.DAG;
9350   SDValue Op = N->getOperand(0);
9351   unsigned OpOpcode = Op.getNode()->getOpcode();
9352
9353   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9354       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9355     return SDValue();
9356
9357   uint64_t C;
9358   SDValue ConstVec = N->getOperand(1);
9359   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9360
9361   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9362       !isConstVecPow2(ConstVec, isSigned, C))
9363     return SDValue();
9364
9365   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9366   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9367   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9368     // These instructions only exist converting from i32 to f32. We can handle
9369     // smaller integers by generating an extra extend, but larger ones would
9370     // be lossy.
9371     return SDValue();
9372   }
9373
9374   SDValue ConvInput = Op.getOperand(0);
9375   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9376   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9377     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9378                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9379                             ConvInput);
9380
9381   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9382     Intrinsic::arm_neon_vcvtfxu2fp;
9383   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9384                      Op.getValueType(),
9385                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9386                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9387 }
9388
9389 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9390 /// operand of a vector shift operation, where all the elements of the
9391 /// build_vector must have the same constant integer value.
9392 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9393   // Ignore bit_converts.
9394   while (Op.getOpcode() == ISD::BITCAST)
9395     Op = Op.getOperand(0);
9396   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9397   APInt SplatBits, SplatUndef;
9398   unsigned SplatBitSize;
9399   bool HasAnyUndefs;
9400   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9401                                       HasAnyUndefs, ElementBits) ||
9402       SplatBitSize > ElementBits)
9403     return false;
9404   Cnt = SplatBits.getSExtValue();
9405   return true;
9406 }
9407
9408 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9409 /// operand of a vector shift left operation.  That value must be in the range:
9410 ///   0 <= Value < ElementBits for a left shift; or
9411 ///   0 <= Value <= ElementBits for a long left shift.
9412 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9413   assert(VT.isVector() && "vector shift count is not a vector type");
9414   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9415   if (! getVShiftImm(Op, ElementBits, Cnt))
9416     return false;
9417   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9418 }
9419
9420 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9421 /// operand of a vector shift right operation.  For a shift opcode, the value
9422 /// is positive, but for an intrinsic the value count must be negative. The
9423 /// absolute value must be in the range:
9424 ///   1 <= |Value| <= ElementBits for a right shift; or
9425 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9426 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9427                          int64_t &Cnt) {
9428   assert(VT.isVector() && "vector shift count is not a vector type");
9429   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9430   if (! getVShiftImm(Op, ElementBits, Cnt))
9431     return false;
9432   if (isIntrinsic)
9433     Cnt = -Cnt;
9434   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9435 }
9436
9437 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9438 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9439   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9440   switch (IntNo) {
9441   default:
9442     // Don't do anything for most intrinsics.
9443     break;
9444
9445   // Vector shifts: check for immediate versions and lower them.
9446   // Note: This is done during DAG combining instead of DAG legalizing because
9447   // the build_vectors for 64-bit vector element shift counts are generally
9448   // not legal, and it is hard to see their values after they get legalized to
9449   // loads from a constant pool.
9450   case Intrinsic::arm_neon_vshifts:
9451   case Intrinsic::arm_neon_vshiftu:
9452   case Intrinsic::arm_neon_vrshifts:
9453   case Intrinsic::arm_neon_vrshiftu:
9454   case Intrinsic::arm_neon_vrshiftn:
9455   case Intrinsic::arm_neon_vqshifts:
9456   case Intrinsic::arm_neon_vqshiftu:
9457   case Intrinsic::arm_neon_vqshiftsu:
9458   case Intrinsic::arm_neon_vqshiftns:
9459   case Intrinsic::arm_neon_vqshiftnu:
9460   case Intrinsic::arm_neon_vqshiftnsu:
9461   case Intrinsic::arm_neon_vqrshiftns:
9462   case Intrinsic::arm_neon_vqrshiftnu:
9463   case Intrinsic::arm_neon_vqrshiftnsu: {
9464     EVT VT = N->getOperand(1).getValueType();
9465     int64_t Cnt;
9466     unsigned VShiftOpc = 0;
9467
9468     switch (IntNo) {
9469     case Intrinsic::arm_neon_vshifts:
9470     case Intrinsic::arm_neon_vshiftu:
9471       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9472         VShiftOpc = ARMISD::VSHL;
9473         break;
9474       }
9475       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9476         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9477                      ARMISD::VSHRs : ARMISD::VSHRu);
9478         break;
9479       }
9480       return SDValue();
9481
9482     case Intrinsic::arm_neon_vrshifts:
9483     case Intrinsic::arm_neon_vrshiftu:
9484       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9485         break;
9486       return SDValue();
9487
9488     case Intrinsic::arm_neon_vqshifts:
9489     case Intrinsic::arm_neon_vqshiftu:
9490       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9491         break;
9492       return SDValue();
9493
9494     case Intrinsic::arm_neon_vqshiftsu:
9495       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9496         break;
9497       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9498
9499     case Intrinsic::arm_neon_vrshiftn:
9500     case Intrinsic::arm_neon_vqshiftns:
9501     case Intrinsic::arm_neon_vqshiftnu:
9502     case Intrinsic::arm_neon_vqshiftnsu:
9503     case Intrinsic::arm_neon_vqrshiftns:
9504     case Intrinsic::arm_neon_vqrshiftnu:
9505     case Intrinsic::arm_neon_vqrshiftnsu:
9506       // Narrowing shifts require an immediate right shift.
9507       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9508         break;
9509       llvm_unreachable("invalid shift count for narrowing vector shift "
9510                        "intrinsic");
9511
9512     default:
9513       llvm_unreachable("unhandled vector shift");
9514     }
9515
9516     switch (IntNo) {
9517     case Intrinsic::arm_neon_vshifts:
9518     case Intrinsic::arm_neon_vshiftu:
9519       // Opcode already set above.
9520       break;
9521     case Intrinsic::arm_neon_vrshifts:
9522       VShiftOpc = ARMISD::VRSHRs; break;
9523     case Intrinsic::arm_neon_vrshiftu:
9524       VShiftOpc = ARMISD::VRSHRu; break;
9525     case Intrinsic::arm_neon_vrshiftn:
9526       VShiftOpc = ARMISD::VRSHRN; break;
9527     case Intrinsic::arm_neon_vqshifts:
9528       VShiftOpc = ARMISD::VQSHLs; break;
9529     case Intrinsic::arm_neon_vqshiftu:
9530       VShiftOpc = ARMISD::VQSHLu; break;
9531     case Intrinsic::arm_neon_vqshiftsu:
9532       VShiftOpc = ARMISD::VQSHLsu; break;
9533     case Intrinsic::arm_neon_vqshiftns:
9534       VShiftOpc = ARMISD::VQSHRNs; break;
9535     case Intrinsic::arm_neon_vqshiftnu:
9536       VShiftOpc = ARMISD::VQSHRNu; break;
9537     case Intrinsic::arm_neon_vqshiftnsu:
9538       VShiftOpc = ARMISD::VQSHRNsu; break;
9539     case Intrinsic::arm_neon_vqrshiftns:
9540       VShiftOpc = ARMISD::VQRSHRNs; break;
9541     case Intrinsic::arm_neon_vqrshiftnu:
9542       VShiftOpc = ARMISD::VQRSHRNu; break;
9543     case Intrinsic::arm_neon_vqrshiftnsu:
9544       VShiftOpc = ARMISD::VQRSHRNsu; break;
9545     }
9546
9547     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9548                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9549   }
9550
9551   case Intrinsic::arm_neon_vshiftins: {
9552     EVT VT = N->getOperand(1).getValueType();
9553     int64_t Cnt;
9554     unsigned VShiftOpc = 0;
9555
9556     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9557       VShiftOpc = ARMISD::VSLI;
9558     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9559       VShiftOpc = ARMISD::VSRI;
9560     else {
9561       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9562     }
9563
9564     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9565                        N->getOperand(1), N->getOperand(2),
9566                        DAG.getConstant(Cnt, MVT::i32));
9567   }
9568
9569   case Intrinsic::arm_neon_vqrshifts:
9570   case Intrinsic::arm_neon_vqrshiftu:
9571     // No immediate versions of these to check for.
9572     break;
9573   }
9574
9575   return SDValue();
9576 }
9577
9578 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9579 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9580 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9581 /// vector element shift counts are generally not legal, and it is hard to see
9582 /// their values after they get legalized to loads from a constant pool.
9583 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9584                                    const ARMSubtarget *ST) {
9585   EVT VT = N->getValueType(0);
9586   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9587     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9588     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9589     SDValue N1 = N->getOperand(1);
9590     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9591       SDValue N0 = N->getOperand(0);
9592       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9593           DAG.MaskedValueIsZero(N0.getOperand(0),
9594                                 APInt::getHighBitsSet(32, 16)))
9595         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9596     }
9597   }
9598
9599   // Nothing to be done for scalar shifts.
9600   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9601   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9602     return SDValue();
9603
9604   assert(ST->hasNEON() && "unexpected vector shift");
9605   int64_t Cnt;
9606
9607   switch (N->getOpcode()) {
9608   default: llvm_unreachable("unexpected shift opcode");
9609
9610   case ISD::SHL:
9611     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9612       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9613                          DAG.getConstant(Cnt, MVT::i32));
9614     break;
9615
9616   case ISD::SRA:
9617   case ISD::SRL:
9618     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9619       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9620                             ARMISD::VSHRs : ARMISD::VSHRu);
9621       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9622                          DAG.getConstant(Cnt, MVT::i32));
9623     }
9624   }
9625   return SDValue();
9626 }
9627
9628 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9629 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9630 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9631                                     const ARMSubtarget *ST) {
9632   SDValue N0 = N->getOperand(0);
9633
9634   // Check for sign- and zero-extensions of vector extract operations of 8-
9635   // and 16-bit vector elements.  NEON supports these directly.  They are
9636   // handled during DAG combining because type legalization will promote them
9637   // to 32-bit types and it is messy to recognize the operations after that.
9638   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9639     SDValue Vec = N0.getOperand(0);
9640     SDValue Lane = N0.getOperand(1);
9641     EVT VT = N->getValueType(0);
9642     EVT EltVT = N0.getValueType();
9643     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9644
9645     if (VT == MVT::i32 &&
9646         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9647         TLI.isTypeLegal(Vec.getValueType()) &&
9648         isa<ConstantSDNode>(Lane)) {
9649
9650       unsigned Opc = 0;
9651       switch (N->getOpcode()) {
9652       default: llvm_unreachable("unexpected opcode");
9653       case ISD::SIGN_EXTEND:
9654         Opc = ARMISD::VGETLANEs;
9655         break;
9656       case ISD::ZERO_EXTEND:
9657       case ISD::ANY_EXTEND:
9658         Opc = ARMISD::VGETLANEu;
9659         break;
9660       }
9661       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9662     }
9663   }
9664
9665   return SDValue();
9666 }
9667
9668 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9669 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9670 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9671                                        const ARMSubtarget *ST) {
9672   // If the target supports NEON, try to use vmax/vmin instructions for f32
9673   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9674   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9675   // a NaN; only do the transformation when it matches that behavior.
9676
9677   // For now only do this when using NEON for FP operations; if using VFP, it
9678   // is not obvious that the benefit outweighs the cost of switching to the
9679   // NEON pipeline.
9680   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9681       N->getValueType(0) != MVT::f32)
9682     return SDValue();
9683
9684   SDValue CondLHS = N->getOperand(0);
9685   SDValue CondRHS = N->getOperand(1);
9686   SDValue LHS = N->getOperand(2);
9687   SDValue RHS = N->getOperand(3);
9688   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9689
9690   unsigned Opcode = 0;
9691   bool IsReversed;
9692   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9693     IsReversed = false; // x CC y ? x : y
9694   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9695     IsReversed = true ; // x CC y ? y : x
9696   } else {
9697     return SDValue();
9698   }
9699
9700   bool IsUnordered;
9701   switch (CC) {
9702   default: break;
9703   case ISD::SETOLT:
9704   case ISD::SETOLE:
9705   case ISD::SETLT:
9706   case ISD::SETLE:
9707   case ISD::SETULT:
9708   case ISD::SETULE:
9709     // If LHS is NaN, an ordered comparison will be false and the result will
9710     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9711     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9712     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9713     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9714       break;
9715     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9716     // will return -0, so vmin can only be used for unsafe math or if one of
9717     // the operands is known to be nonzero.
9718     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9719         !DAG.getTarget().Options.UnsafeFPMath &&
9720         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9721       break;
9722     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9723     break;
9724
9725   case ISD::SETOGT:
9726   case ISD::SETOGE:
9727   case ISD::SETGT:
9728   case ISD::SETGE:
9729   case ISD::SETUGT:
9730   case ISD::SETUGE:
9731     // If LHS is NaN, an ordered comparison will be false and the result will
9732     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9733     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9734     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9735     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9736       break;
9737     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9738     // will return +0, so vmax can only be used for unsafe math or if one of
9739     // the operands is known to be nonzero.
9740     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9741         !DAG.getTarget().Options.UnsafeFPMath &&
9742         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9743       break;
9744     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9745     break;
9746   }
9747
9748   if (!Opcode)
9749     return SDValue();
9750   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9751 }
9752
9753 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9754 SDValue
9755 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9756   SDValue Cmp = N->getOperand(4);
9757   if (Cmp.getOpcode() != ARMISD::CMPZ)
9758     // Only looking at EQ and NE cases.
9759     return SDValue();
9760
9761   EVT VT = N->getValueType(0);
9762   SDLoc dl(N);
9763   SDValue LHS = Cmp.getOperand(0);
9764   SDValue RHS = Cmp.getOperand(1);
9765   SDValue FalseVal = N->getOperand(0);
9766   SDValue TrueVal = N->getOperand(1);
9767   SDValue ARMcc = N->getOperand(2);
9768   ARMCC::CondCodes CC =
9769     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9770
9771   // Simplify
9772   //   mov     r1, r0
9773   //   cmp     r1, x
9774   //   mov     r0, y
9775   //   moveq   r0, x
9776   // to
9777   //   cmp     r0, x
9778   //   movne   r0, y
9779   //
9780   //   mov     r1, r0
9781   //   cmp     r1, x
9782   //   mov     r0, x
9783   //   movne   r0, y
9784   // to
9785   //   cmp     r0, x
9786   //   movne   r0, y
9787   /// FIXME: Turn this into a target neutral optimization?
9788   SDValue Res;
9789   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9790     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9791                       N->getOperand(3), Cmp);
9792   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9793     SDValue ARMcc;
9794     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9795     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9796                       N->getOperand(3), NewCmp);
9797   }
9798
9799   if (Res.getNode()) {
9800     APInt KnownZero, KnownOne;
9801     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9802     // Capture demanded bits information that would be otherwise lost.
9803     if (KnownZero == 0xfffffffe)
9804       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9805                         DAG.getValueType(MVT::i1));
9806     else if (KnownZero == 0xffffff00)
9807       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9808                         DAG.getValueType(MVT::i8));
9809     else if (KnownZero == 0xffff0000)
9810       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9811                         DAG.getValueType(MVT::i16));
9812   }
9813
9814   return Res;
9815 }
9816
9817 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9818                                              DAGCombinerInfo &DCI) const {
9819   switch (N->getOpcode()) {
9820   default: break;
9821   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9822   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9823   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9824   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9825   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9826   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9827   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9828   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9829   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9830   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9831   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9832   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9833   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9834   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9835   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9836   case ISD::FP_TO_SINT:
9837   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9838   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9839   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9840   case ISD::SHL:
9841   case ISD::SRA:
9842   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9843   case ISD::SIGN_EXTEND:
9844   case ISD::ZERO_EXTEND:
9845   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9846   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9847   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9848   case ARMISD::VLD2DUP:
9849   case ARMISD::VLD3DUP:
9850   case ARMISD::VLD4DUP:
9851     return CombineBaseUpdate(N, DCI);
9852   case ARMISD::BUILD_VECTOR:
9853     return PerformARMBUILD_VECTORCombine(N, DCI);
9854   case ISD::INTRINSIC_VOID:
9855   case ISD::INTRINSIC_W_CHAIN:
9856     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9857     case Intrinsic::arm_neon_vld1:
9858     case Intrinsic::arm_neon_vld2:
9859     case Intrinsic::arm_neon_vld3:
9860     case Intrinsic::arm_neon_vld4:
9861     case Intrinsic::arm_neon_vld2lane:
9862     case Intrinsic::arm_neon_vld3lane:
9863     case Intrinsic::arm_neon_vld4lane:
9864     case Intrinsic::arm_neon_vst1:
9865     case Intrinsic::arm_neon_vst2:
9866     case Intrinsic::arm_neon_vst3:
9867     case Intrinsic::arm_neon_vst4:
9868     case Intrinsic::arm_neon_vst2lane:
9869     case Intrinsic::arm_neon_vst3lane:
9870     case Intrinsic::arm_neon_vst4lane:
9871       return CombineBaseUpdate(N, DCI);
9872     default: break;
9873     }
9874     break;
9875   }
9876   return SDValue();
9877 }
9878
9879 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9880                                                           EVT VT) const {
9881   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9882 }
9883
9884 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9885                                                        unsigned,
9886                                                        unsigned,
9887                                                        bool *Fast) const {
9888   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9889   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9890
9891   switch (VT.getSimpleVT().SimpleTy) {
9892   default:
9893     return false;
9894   case MVT::i8:
9895   case MVT::i16:
9896   case MVT::i32: {
9897     // Unaligned access can use (for example) LRDB, LRDH, LDR
9898     if (AllowsUnaligned) {
9899       if (Fast)
9900         *Fast = Subtarget->hasV7Ops();
9901       return true;
9902     }
9903     return false;
9904   }
9905   case MVT::f64:
9906   case MVT::v2f64: {
9907     // For any little-endian targets with neon, we can support unaligned ld/st
9908     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9909     // A big-endian target may also explicitly support unaligned accesses
9910     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9911       if (Fast)
9912         *Fast = true;
9913       return true;
9914     }
9915     return false;
9916   }
9917   }
9918 }
9919
9920 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9921                        unsigned AlignCheck) {
9922   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9923           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9924 }
9925
9926 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9927                                            unsigned DstAlign, unsigned SrcAlign,
9928                                            bool IsMemset, bool ZeroMemset,
9929                                            bool MemcpyStrSrc,
9930                                            MachineFunction &MF) const {
9931   const Function *F = MF.getFunction();
9932
9933   // See if we can use NEON instructions for this...
9934   if ((!IsMemset || ZeroMemset) &&
9935       Subtarget->hasNEON() &&
9936       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9937                                        Attribute::NoImplicitFloat)) {
9938     bool Fast;
9939     if (Size >= 16 &&
9940         (memOpAlign(SrcAlign, DstAlign, 16) ||
9941          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9942       return MVT::v2f64;
9943     } else if (Size >= 8 &&
9944                (memOpAlign(SrcAlign, DstAlign, 8) ||
9945                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9946                  Fast))) {
9947       return MVT::f64;
9948     }
9949   }
9950
9951   // Lowering to i32/i16 if the size permits.
9952   if (Size >= 4)
9953     return MVT::i32;
9954   else if (Size >= 2)
9955     return MVT::i16;
9956
9957   // Let the target-independent logic figure it out.
9958   return MVT::Other;
9959 }
9960
9961 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9962   if (Val.getOpcode() != ISD::LOAD)
9963     return false;
9964
9965   EVT VT1 = Val.getValueType();
9966   if (!VT1.isSimple() || !VT1.isInteger() ||
9967       !VT2.isSimple() || !VT2.isInteger())
9968     return false;
9969
9970   switch (VT1.getSimpleVT().SimpleTy) {
9971   default: break;
9972   case MVT::i1:
9973   case MVT::i8:
9974   case MVT::i16:
9975     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9976     return true;
9977   }
9978
9979   return false;
9980 }
9981
9982 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9983   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9984     return false;
9985
9986   if (!isTypeLegal(EVT::getEVT(Ty1)))
9987     return false;
9988
9989   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9990
9991   // Assuming the caller doesn't have a zeroext or signext return parameter,
9992   // truncation all the way down to i1 is valid.
9993   return true;
9994 }
9995
9996
9997 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9998   if (V < 0)
9999     return false;
10000
10001   unsigned Scale = 1;
10002   switch (VT.getSimpleVT().SimpleTy) {
10003   default: return false;
10004   case MVT::i1:
10005   case MVT::i8:
10006     // Scale == 1;
10007     break;
10008   case MVT::i16:
10009     // Scale == 2;
10010     Scale = 2;
10011     break;
10012   case MVT::i32:
10013     // Scale == 4;
10014     Scale = 4;
10015     break;
10016   }
10017
10018   if ((V & (Scale - 1)) != 0)
10019     return false;
10020   V /= Scale;
10021   return V == (V & ((1LL << 5) - 1));
10022 }
10023
10024 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10025                                       const ARMSubtarget *Subtarget) {
10026   bool isNeg = false;
10027   if (V < 0) {
10028     isNeg = true;
10029     V = - V;
10030   }
10031
10032   switch (VT.getSimpleVT().SimpleTy) {
10033   default: return false;
10034   case MVT::i1:
10035   case MVT::i8:
10036   case MVT::i16:
10037   case MVT::i32:
10038     // + imm12 or - imm8
10039     if (isNeg)
10040       return V == (V & ((1LL << 8) - 1));
10041     return V == (V & ((1LL << 12) - 1));
10042   case MVT::f32:
10043   case MVT::f64:
10044     // Same as ARM mode. FIXME: NEON?
10045     if (!Subtarget->hasVFP2())
10046       return false;
10047     if ((V & 3) != 0)
10048       return false;
10049     V >>= 2;
10050     return V == (V & ((1LL << 8) - 1));
10051   }
10052 }
10053
10054 /// isLegalAddressImmediate - Return true if the integer value can be used
10055 /// as the offset of the target addressing mode for load / store of the
10056 /// given type.
10057 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10058                                     const ARMSubtarget *Subtarget) {
10059   if (V == 0)
10060     return true;
10061
10062   if (!VT.isSimple())
10063     return false;
10064
10065   if (Subtarget->isThumb1Only())
10066     return isLegalT1AddressImmediate(V, VT);
10067   else if (Subtarget->isThumb2())
10068     return isLegalT2AddressImmediate(V, VT, Subtarget);
10069
10070   // ARM mode.
10071   if (V < 0)
10072     V = - V;
10073   switch (VT.getSimpleVT().SimpleTy) {
10074   default: return false;
10075   case MVT::i1:
10076   case MVT::i8:
10077   case MVT::i32:
10078     // +- imm12
10079     return V == (V & ((1LL << 12) - 1));
10080   case MVT::i16:
10081     // +- imm8
10082     return V == (V & ((1LL << 8) - 1));
10083   case MVT::f32:
10084   case MVT::f64:
10085     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10086       return false;
10087     if ((V & 3) != 0)
10088       return false;
10089     V >>= 2;
10090     return V == (V & ((1LL << 8) - 1));
10091   }
10092 }
10093
10094 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10095                                                       EVT VT) const {
10096   int Scale = AM.Scale;
10097   if (Scale < 0)
10098     return false;
10099
10100   switch (VT.getSimpleVT().SimpleTy) {
10101   default: return false;
10102   case MVT::i1:
10103   case MVT::i8:
10104   case MVT::i16:
10105   case MVT::i32:
10106     if (Scale == 1)
10107       return true;
10108     // r + r << imm
10109     Scale = Scale & ~1;
10110     return Scale == 2 || Scale == 4 || Scale == 8;
10111   case MVT::i64:
10112     // r + r
10113     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10114       return true;
10115     return false;
10116   case MVT::isVoid:
10117     // Note, we allow "void" uses (basically, uses that aren't loads or
10118     // stores), because arm allows folding a scale into many arithmetic
10119     // operations.  This should be made more precise and revisited later.
10120
10121     // Allow r << imm, but the imm has to be a multiple of two.
10122     if (Scale & 1) return false;
10123     return isPowerOf2_32(Scale);
10124   }
10125 }
10126
10127 /// isLegalAddressingMode - Return true if the addressing mode represented
10128 /// by AM is legal for this target, for a load/store of the specified type.
10129 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10130                                               Type *Ty) const {
10131   EVT VT = getValueType(Ty, true);
10132   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10133     return false;
10134
10135   // Can never fold addr of global into load/store.
10136   if (AM.BaseGV)
10137     return false;
10138
10139   switch (AM.Scale) {
10140   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10141     break;
10142   case 1:
10143     if (Subtarget->isThumb1Only())
10144       return false;
10145     // FALL THROUGH.
10146   default:
10147     // ARM doesn't support any R+R*scale+imm addr modes.
10148     if (AM.BaseOffs)
10149       return false;
10150
10151     if (!VT.isSimple())
10152       return false;
10153
10154     if (Subtarget->isThumb2())
10155       return isLegalT2ScaledAddressingMode(AM, VT);
10156
10157     int Scale = AM.Scale;
10158     switch (VT.getSimpleVT().SimpleTy) {
10159     default: return false;
10160     case MVT::i1:
10161     case MVT::i8:
10162     case MVT::i32:
10163       if (Scale < 0) Scale = -Scale;
10164       if (Scale == 1)
10165         return true;
10166       // r + r << imm
10167       return isPowerOf2_32(Scale & ~1);
10168     case MVT::i16:
10169     case MVT::i64:
10170       // r + r
10171       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10172         return true;
10173       return false;
10174
10175     case MVT::isVoid:
10176       // Note, we allow "void" uses (basically, uses that aren't loads or
10177       // stores), because arm allows folding a scale into many arithmetic
10178       // operations.  This should be made more precise and revisited later.
10179
10180       // Allow r << imm, but the imm has to be a multiple of two.
10181       if (Scale & 1) return false;
10182       return isPowerOf2_32(Scale);
10183     }
10184   }
10185   return true;
10186 }
10187
10188 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10189 /// icmp immediate, that is the target has icmp instructions which can compare
10190 /// a register against the immediate without having to materialize the
10191 /// immediate into a register.
10192 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10193   // Thumb2 and ARM modes can use cmn for negative immediates.
10194   if (!Subtarget->isThumb())
10195     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10196   if (Subtarget->isThumb2())
10197     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10198   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10199   return Imm >= 0 && Imm <= 255;
10200 }
10201
10202 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10203 /// *or sub* immediate, that is the target has add or sub instructions which can
10204 /// add a register with the immediate without having to materialize the
10205 /// immediate into a register.
10206 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10207   // Same encoding for add/sub, just flip the sign.
10208   int64_t AbsImm = llvm::abs64(Imm);
10209   if (!Subtarget->isThumb())
10210     return ARM_AM::getSOImmVal(AbsImm) != -1;
10211   if (Subtarget->isThumb2())
10212     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10213   // Thumb1 only has 8-bit unsigned immediate.
10214   return AbsImm >= 0 && AbsImm <= 255;
10215 }
10216
10217 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10218                                       bool isSEXTLoad, SDValue &Base,
10219                                       SDValue &Offset, bool &isInc,
10220                                       SelectionDAG &DAG) {
10221   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10222     return false;
10223
10224   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10225     // AddressingMode 3
10226     Base = Ptr->getOperand(0);
10227     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10228       int RHSC = (int)RHS->getZExtValue();
10229       if (RHSC < 0 && RHSC > -256) {
10230         assert(Ptr->getOpcode() == ISD::ADD);
10231         isInc = false;
10232         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10233         return true;
10234       }
10235     }
10236     isInc = (Ptr->getOpcode() == ISD::ADD);
10237     Offset = Ptr->getOperand(1);
10238     return true;
10239   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10240     // AddressingMode 2
10241     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10242       int RHSC = (int)RHS->getZExtValue();
10243       if (RHSC < 0 && RHSC > -0x1000) {
10244         assert(Ptr->getOpcode() == ISD::ADD);
10245         isInc = false;
10246         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10247         Base = Ptr->getOperand(0);
10248         return true;
10249       }
10250     }
10251
10252     if (Ptr->getOpcode() == ISD::ADD) {
10253       isInc = true;
10254       ARM_AM::ShiftOpc ShOpcVal=
10255         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10256       if (ShOpcVal != ARM_AM::no_shift) {
10257         Base = Ptr->getOperand(1);
10258         Offset = Ptr->getOperand(0);
10259       } else {
10260         Base = Ptr->getOperand(0);
10261         Offset = Ptr->getOperand(1);
10262       }
10263       return true;
10264     }
10265
10266     isInc = (Ptr->getOpcode() == ISD::ADD);
10267     Base = Ptr->getOperand(0);
10268     Offset = Ptr->getOperand(1);
10269     return true;
10270   }
10271
10272   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10273   return false;
10274 }
10275
10276 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10277                                      bool isSEXTLoad, SDValue &Base,
10278                                      SDValue &Offset, bool &isInc,
10279                                      SelectionDAG &DAG) {
10280   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10281     return false;
10282
10283   Base = Ptr->getOperand(0);
10284   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10285     int RHSC = (int)RHS->getZExtValue();
10286     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10287       assert(Ptr->getOpcode() == ISD::ADD);
10288       isInc = false;
10289       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10290       return true;
10291     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10292       isInc = Ptr->getOpcode() == ISD::ADD;
10293       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10294       return true;
10295     }
10296   }
10297
10298   return false;
10299 }
10300
10301 /// getPreIndexedAddressParts - returns true by value, base pointer and
10302 /// offset pointer and addressing mode by reference if the node's address
10303 /// can be legally represented as pre-indexed load / store address.
10304 bool
10305 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10306                                              SDValue &Offset,
10307                                              ISD::MemIndexedMode &AM,
10308                                              SelectionDAG &DAG) const {
10309   if (Subtarget->isThumb1Only())
10310     return false;
10311
10312   EVT VT;
10313   SDValue Ptr;
10314   bool isSEXTLoad = false;
10315   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10316     Ptr = LD->getBasePtr();
10317     VT  = LD->getMemoryVT();
10318     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10319   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10320     Ptr = ST->getBasePtr();
10321     VT  = ST->getMemoryVT();
10322   } else
10323     return false;
10324
10325   bool isInc;
10326   bool isLegal = false;
10327   if (Subtarget->isThumb2())
10328     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10329                                        Offset, isInc, DAG);
10330   else
10331     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10332                                         Offset, isInc, DAG);
10333   if (!isLegal)
10334     return false;
10335
10336   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10337   return true;
10338 }
10339
10340 /// getPostIndexedAddressParts - returns true by value, base pointer and
10341 /// offset pointer and addressing mode by reference if this node can be
10342 /// combined with a load / store to form a post-indexed load / store.
10343 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10344                                                    SDValue &Base,
10345                                                    SDValue &Offset,
10346                                                    ISD::MemIndexedMode &AM,
10347                                                    SelectionDAG &DAG) const {
10348   if (Subtarget->isThumb1Only())
10349     return false;
10350
10351   EVT VT;
10352   SDValue Ptr;
10353   bool isSEXTLoad = false;
10354   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10355     VT  = LD->getMemoryVT();
10356     Ptr = LD->getBasePtr();
10357     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10358   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10359     VT  = ST->getMemoryVT();
10360     Ptr = ST->getBasePtr();
10361   } else
10362     return false;
10363
10364   bool isInc;
10365   bool isLegal = false;
10366   if (Subtarget->isThumb2())
10367     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10368                                        isInc, DAG);
10369   else
10370     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10371                                         isInc, DAG);
10372   if (!isLegal)
10373     return false;
10374
10375   if (Ptr != Base) {
10376     // Swap base ptr and offset to catch more post-index load / store when
10377     // it's legal. In Thumb2 mode, offset must be an immediate.
10378     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10379         !Subtarget->isThumb2())
10380       std::swap(Base, Offset);
10381
10382     // Post-indexed load / store update the base pointer.
10383     if (Ptr != Base)
10384       return false;
10385   }
10386
10387   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10388   return true;
10389 }
10390
10391 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10392                                                       APInt &KnownZero,
10393                                                       APInt &KnownOne,
10394                                                       const SelectionDAG &DAG,
10395                                                       unsigned Depth) const {
10396   unsigned BitWidth = KnownOne.getBitWidth();
10397   KnownZero = KnownOne = APInt(BitWidth, 0);
10398   switch (Op.getOpcode()) {
10399   default: break;
10400   case ARMISD::ADDC:
10401   case ARMISD::ADDE:
10402   case ARMISD::SUBC:
10403   case ARMISD::SUBE:
10404     // These nodes' second result is a boolean
10405     if (Op.getResNo() == 0)
10406       break;
10407     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10408     break;
10409   case ARMISD::CMOV: {
10410     // Bits are known zero/one if known on the LHS and RHS.
10411     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10412     if (KnownZero == 0 && KnownOne == 0) return;
10413
10414     APInt KnownZeroRHS, KnownOneRHS;
10415     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10416     KnownZero &= KnownZeroRHS;
10417     KnownOne  &= KnownOneRHS;
10418     return;
10419   }
10420   case ISD::INTRINSIC_W_CHAIN: {
10421     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10422     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10423     switch (IntID) {
10424     default: return;
10425     case Intrinsic::arm_ldaex:
10426     case Intrinsic::arm_ldrex: {
10427       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10428       unsigned MemBits = VT.getScalarType().getSizeInBits();
10429       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10430       return;
10431     }
10432     }
10433   }
10434   }
10435 }
10436
10437 //===----------------------------------------------------------------------===//
10438 //                           ARM Inline Assembly Support
10439 //===----------------------------------------------------------------------===//
10440
10441 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10442   // Looking for "rev" which is V6+.
10443   if (!Subtarget->hasV6Ops())
10444     return false;
10445
10446   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10447   std::string AsmStr = IA->getAsmString();
10448   SmallVector<StringRef, 4> AsmPieces;
10449   SplitString(AsmStr, AsmPieces, ";\n");
10450
10451   switch (AsmPieces.size()) {
10452   default: return false;
10453   case 1:
10454     AsmStr = AsmPieces[0];
10455     AsmPieces.clear();
10456     SplitString(AsmStr, AsmPieces, " \t,");
10457
10458     // rev $0, $1
10459     if (AsmPieces.size() == 3 &&
10460         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10461         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10462       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10463       if (Ty && Ty->getBitWidth() == 32)
10464         return IntrinsicLowering::LowerToByteSwap(CI);
10465     }
10466     break;
10467   }
10468
10469   return false;
10470 }
10471
10472 /// getConstraintType - Given a constraint letter, return the type of
10473 /// constraint it is for this target.
10474 ARMTargetLowering::ConstraintType
10475 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10476   if (Constraint.size() == 1) {
10477     switch (Constraint[0]) {
10478     default:  break;
10479     case 'l': return C_RegisterClass;
10480     case 'w': return C_RegisterClass;
10481     case 'h': return C_RegisterClass;
10482     case 'x': return C_RegisterClass;
10483     case 't': return C_RegisterClass;
10484     case 'j': return C_Other; // Constant for movw.
10485       // An address with a single base register. Due to the way we
10486       // currently handle addresses it is the same as an 'r' memory constraint.
10487     case 'Q': return C_Memory;
10488     }
10489   } else if (Constraint.size() == 2) {
10490     switch (Constraint[0]) {
10491     default: break;
10492     // All 'U+' constraints are addresses.
10493     case 'U': return C_Memory;
10494     }
10495   }
10496   return TargetLowering::getConstraintType(Constraint);
10497 }
10498
10499 /// Examine constraint type and operand type and determine a weight value.
10500 /// This object must already have been set up with the operand type
10501 /// and the current alternative constraint selected.
10502 TargetLowering::ConstraintWeight
10503 ARMTargetLowering::getSingleConstraintMatchWeight(
10504     AsmOperandInfo &info, const char *constraint) const {
10505   ConstraintWeight weight = CW_Invalid;
10506   Value *CallOperandVal = info.CallOperandVal;
10507     // If we don't have a value, we can't do a match,
10508     // but allow it at the lowest weight.
10509   if (!CallOperandVal)
10510     return CW_Default;
10511   Type *type = CallOperandVal->getType();
10512   // Look at the constraint type.
10513   switch (*constraint) {
10514   default:
10515     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10516     break;
10517   case 'l':
10518     if (type->isIntegerTy()) {
10519       if (Subtarget->isThumb())
10520         weight = CW_SpecificReg;
10521       else
10522         weight = CW_Register;
10523     }
10524     break;
10525   case 'w':
10526     if (type->isFloatingPointTy())
10527       weight = CW_Register;
10528     break;
10529   }
10530   return weight;
10531 }
10532
10533 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10534 RCPair
10535 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10536                                                 MVT VT) const {
10537   if (Constraint.size() == 1) {
10538     // GCC ARM Constraint Letters
10539     switch (Constraint[0]) {
10540     case 'l': // Low regs or general regs.
10541       if (Subtarget->isThumb())
10542         return RCPair(0U, &ARM::tGPRRegClass);
10543       return RCPair(0U, &ARM::GPRRegClass);
10544     case 'h': // High regs or no regs.
10545       if (Subtarget->isThumb())
10546         return RCPair(0U, &ARM::hGPRRegClass);
10547       break;
10548     case 'r':
10549       return RCPair(0U, &ARM::GPRRegClass);
10550     case 'w':
10551       if (VT == MVT::Other)
10552         break;
10553       if (VT == MVT::f32)
10554         return RCPair(0U, &ARM::SPRRegClass);
10555       if (VT.getSizeInBits() == 64)
10556         return RCPair(0U, &ARM::DPRRegClass);
10557       if (VT.getSizeInBits() == 128)
10558         return RCPair(0U, &ARM::QPRRegClass);
10559       break;
10560     case 'x':
10561       if (VT == MVT::Other)
10562         break;
10563       if (VT == MVT::f32)
10564         return RCPair(0U, &ARM::SPR_8RegClass);
10565       if (VT.getSizeInBits() == 64)
10566         return RCPair(0U, &ARM::DPR_8RegClass);
10567       if (VT.getSizeInBits() == 128)
10568         return RCPair(0U, &ARM::QPR_8RegClass);
10569       break;
10570     case 't':
10571       if (VT == MVT::f32)
10572         return RCPair(0U, &ARM::SPRRegClass);
10573       break;
10574     }
10575   }
10576   if (StringRef("{cc}").equals_lower(Constraint))
10577     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10578
10579   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10580 }
10581
10582 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10583 /// vector.  If it is invalid, don't add anything to Ops.
10584 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10585                                                      std::string &Constraint,
10586                                                      std::vector<SDValue>&Ops,
10587                                                      SelectionDAG &DAG) const {
10588   SDValue Result;
10589
10590   // Currently only support length 1 constraints.
10591   if (Constraint.length() != 1) return;
10592
10593   char ConstraintLetter = Constraint[0];
10594   switch (ConstraintLetter) {
10595   default: break;
10596   case 'j':
10597   case 'I': case 'J': case 'K': case 'L':
10598   case 'M': case 'N': case 'O':
10599     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10600     if (!C)
10601       return;
10602
10603     int64_t CVal64 = C->getSExtValue();
10604     int CVal = (int) CVal64;
10605     // None of these constraints allow values larger than 32 bits.  Check
10606     // that the value fits in an int.
10607     if (CVal != CVal64)
10608       return;
10609
10610     switch (ConstraintLetter) {
10611       case 'j':
10612         // Constant suitable for movw, must be between 0 and
10613         // 65535.
10614         if (Subtarget->hasV6T2Ops())
10615           if (CVal >= 0 && CVal <= 65535)
10616             break;
10617         return;
10618       case 'I':
10619         if (Subtarget->isThumb1Only()) {
10620           // This must be a constant between 0 and 255, for ADD
10621           // immediates.
10622           if (CVal >= 0 && CVal <= 255)
10623             break;
10624         } else if (Subtarget->isThumb2()) {
10625           // A constant that can be used as an immediate value in a
10626           // data-processing instruction.
10627           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10628             break;
10629         } else {
10630           // A constant that can be used as an immediate value in a
10631           // data-processing instruction.
10632           if (ARM_AM::getSOImmVal(CVal) != -1)
10633             break;
10634         }
10635         return;
10636
10637       case 'J':
10638         if (Subtarget->isThumb()) {  // FIXME thumb2
10639           // This must be a constant between -255 and -1, for negated ADD
10640           // immediates. This can be used in GCC with an "n" modifier that
10641           // prints the negated value, for use with SUB instructions. It is
10642           // not useful otherwise but is implemented for compatibility.
10643           if (CVal >= -255 && CVal <= -1)
10644             break;
10645         } else {
10646           // This must be a constant between -4095 and 4095. It is not clear
10647           // what this constraint is intended for. Implemented for
10648           // compatibility with GCC.
10649           if (CVal >= -4095 && CVal <= 4095)
10650             break;
10651         }
10652         return;
10653
10654       case 'K':
10655         if (Subtarget->isThumb1Only()) {
10656           // A 32-bit value where only one byte has a nonzero value. Exclude
10657           // zero to match GCC. This constraint is used by GCC internally for
10658           // constants that can be loaded with a move/shift combination.
10659           // It is not useful otherwise but is implemented for compatibility.
10660           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10661             break;
10662         } else if (Subtarget->isThumb2()) {
10663           // A constant whose bitwise inverse can be used as an immediate
10664           // value in a data-processing instruction. This can be used in GCC
10665           // with a "B" modifier that prints the inverted value, for use with
10666           // BIC and MVN instructions. It is not useful otherwise but is
10667           // implemented for compatibility.
10668           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10669             break;
10670         } else {
10671           // A constant whose bitwise inverse can be used as an immediate
10672           // value in a data-processing instruction. This can be used in GCC
10673           // with a "B" modifier that prints the inverted value, for use with
10674           // BIC and MVN instructions. It is not useful otherwise but is
10675           // implemented for compatibility.
10676           if (ARM_AM::getSOImmVal(~CVal) != -1)
10677             break;
10678         }
10679         return;
10680
10681       case 'L':
10682         if (Subtarget->isThumb1Only()) {
10683           // This must be a constant between -7 and 7,
10684           // for 3-operand ADD/SUB immediate instructions.
10685           if (CVal >= -7 && CVal < 7)
10686             break;
10687         } else if (Subtarget->isThumb2()) {
10688           // A constant whose negation can be used as an immediate value in a
10689           // data-processing instruction. This can be used in GCC with an "n"
10690           // modifier that prints the negated value, for use with SUB
10691           // instructions. It is not useful otherwise but is implemented for
10692           // compatibility.
10693           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10694             break;
10695         } else {
10696           // A constant whose negation can be used as an immediate value in a
10697           // data-processing instruction. This can be used in GCC with an "n"
10698           // modifier that prints the negated value, for use with SUB
10699           // instructions. It is not useful otherwise but is implemented for
10700           // compatibility.
10701           if (ARM_AM::getSOImmVal(-CVal) != -1)
10702             break;
10703         }
10704         return;
10705
10706       case 'M':
10707         if (Subtarget->isThumb()) { // FIXME thumb2
10708           // This must be a multiple of 4 between 0 and 1020, for
10709           // ADD sp + immediate.
10710           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10711             break;
10712         } else {
10713           // A power of two or a constant between 0 and 32.  This is used in
10714           // GCC for the shift amount on shifted register operands, but it is
10715           // useful in general for any shift amounts.
10716           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10717             break;
10718         }
10719         return;
10720
10721       case 'N':
10722         if (Subtarget->isThumb()) {  // FIXME thumb2
10723           // This must be a constant between 0 and 31, for shift amounts.
10724           if (CVal >= 0 && CVal <= 31)
10725             break;
10726         }
10727         return;
10728
10729       case 'O':
10730         if (Subtarget->isThumb()) {  // FIXME thumb2
10731           // This must be a multiple of 4 between -508 and 508, for
10732           // ADD/SUB sp = sp + immediate.
10733           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10734             break;
10735         }
10736         return;
10737     }
10738     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10739     break;
10740   }
10741
10742   if (Result.getNode()) {
10743     Ops.push_back(Result);
10744     return;
10745   }
10746   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10747 }
10748
10749 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10750   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10751   unsigned Opcode = Op->getOpcode();
10752   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10753          "Invalid opcode for Div/Rem lowering");
10754   bool isSigned = (Opcode == ISD::SDIVREM);
10755   EVT VT = Op->getValueType(0);
10756   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10757
10758   RTLIB::Libcall LC;
10759   switch (VT.getSimpleVT().SimpleTy) {
10760   default: llvm_unreachable("Unexpected request for libcall!");
10761   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10762   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10763   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10764   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10765   }
10766
10767   SDValue InChain = DAG.getEntryNode();
10768
10769   TargetLowering::ArgListTy Args;
10770   TargetLowering::ArgListEntry Entry;
10771   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10772     EVT ArgVT = Op->getOperand(i).getValueType();
10773     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10774     Entry.Node = Op->getOperand(i);
10775     Entry.Ty = ArgTy;
10776     Entry.isSExt = isSigned;
10777     Entry.isZExt = !isSigned;
10778     Args.push_back(Entry);
10779   }
10780
10781   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10782                                          getPointerTy());
10783
10784   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10785
10786   SDLoc dl(Op);
10787   TargetLowering::CallLoweringInfo CLI(DAG);
10788   CLI.setDebugLoc(dl).setChain(InChain)
10789     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10790     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10791
10792   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10793   return CallInfo.first;
10794 }
10795
10796 SDValue
10797 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10798   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10799   SDLoc DL(Op);
10800
10801   // Get the inputs.
10802   SDValue Chain = Op.getOperand(0);
10803   SDValue Size  = Op.getOperand(1);
10804
10805   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10806                               DAG.getConstant(2, MVT::i32));
10807
10808   SDValue Flag;
10809   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10810   Flag = Chain.getValue(1);
10811
10812   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10813   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10814
10815   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10816   Chain = NewSP.getValue(1);
10817
10818   SDValue Ops[2] = { NewSP, Chain };
10819   return DAG.getMergeValues(Ops, DL);
10820 }
10821
10822 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10823   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10824          "Unexpected type for custom-lowering FP_EXTEND");
10825
10826   RTLIB::Libcall LC;
10827   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10828
10829   SDValue SrcVal = Op.getOperand(0);
10830   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10831                      /*isSigned*/ false, SDLoc(Op)).first;
10832 }
10833
10834 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10835   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10836          Subtarget->isFPOnlySP() &&
10837          "Unexpected type for custom-lowering FP_ROUND");
10838
10839   RTLIB::Libcall LC;
10840   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10841
10842   SDValue SrcVal = Op.getOperand(0);
10843   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10844                      /*isSigned*/ false, SDLoc(Op)).first;
10845 }
10846
10847 bool
10848 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10849   // The ARM target isn't yet aware of offsets.
10850   return false;
10851 }
10852
10853 bool ARM::isBitFieldInvertedMask(unsigned v) {
10854   if (v == 0xffffffff)
10855     return false;
10856
10857   // there can be 1's on either or both "outsides", all the "inside"
10858   // bits must be 0's
10859   unsigned TO = CountTrailingOnes_32(v);
10860   unsigned LO = CountLeadingOnes_32(v);
10861   v = (v >> TO) << TO;
10862   v = (v << LO) >> LO;
10863   return v == 0;
10864 }
10865
10866 /// isFPImmLegal - Returns true if the target can instruction select the
10867 /// specified FP immediate natively. If false, the legalizer will
10868 /// materialize the FP immediate as a load from a constant pool.
10869 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10870   if (!Subtarget->hasVFP3())
10871     return false;
10872   if (VT == MVT::f32)
10873     return ARM_AM::getFP32Imm(Imm) != -1;
10874   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10875     return ARM_AM::getFP64Imm(Imm) != -1;
10876   return false;
10877 }
10878
10879 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10880 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10881 /// specified in the intrinsic calls.
10882 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10883                                            const CallInst &I,
10884                                            unsigned Intrinsic) const {
10885   switch (Intrinsic) {
10886   case Intrinsic::arm_neon_vld1:
10887   case Intrinsic::arm_neon_vld2:
10888   case Intrinsic::arm_neon_vld3:
10889   case Intrinsic::arm_neon_vld4:
10890   case Intrinsic::arm_neon_vld2lane:
10891   case Intrinsic::arm_neon_vld3lane:
10892   case Intrinsic::arm_neon_vld4lane: {
10893     Info.opc = ISD::INTRINSIC_W_CHAIN;
10894     // Conservatively set memVT to the entire set of vectors loaded.
10895     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10896     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10897     Info.ptrVal = I.getArgOperand(0);
10898     Info.offset = 0;
10899     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10900     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10901     Info.vol = false; // volatile loads with NEON intrinsics not supported
10902     Info.readMem = true;
10903     Info.writeMem = false;
10904     return true;
10905   }
10906   case Intrinsic::arm_neon_vst1:
10907   case Intrinsic::arm_neon_vst2:
10908   case Intrinsic::arm_neon_vst3:
10909   case Intrinsic::arm_neon_vst4:
10910   case Intrinsic::arm_neon_vst2lane:
10911   case Intrinsic::arm_neon_vst3lane:
10912   case Intrinsic::arm_neon_vst4lane: {
10913     Info.opc = ISD::INTRINSIC_VOID;
10914     // Conservatively set memVT to the entire set of vectors stored.
10915     unsigned NumElts = 0;
10916     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10917       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10918       if (!ArgTy->isVectorTy())
10919         break;
10920       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10921     }
10922     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10923     Info.ptrVal = I.getArgOperand(0);
10924     Info.offset = 0;
10925     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10926     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10927     Info.vol = false; // volatile stores with NEON intrinsics not supported
10928     Info.readMem = false;
10929     Info.writeMem = true;
10930     return true;
10931   }
10932   case Intrinsic::arm_ldaex:
10933   case Intrinsic::arm_ldrex: {
10934     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10935     Info.opc = ISD::INTRINSIC_W_CHAIN;
10936     Info.memVT = MVT::getVT(PtrTy->getElementType());
10937     Info.ptrVal = I.getArgOperand(0);
10938     Info.offset = 0;
10939     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10940     Info.vol = true;
10941     Info.readMem = true;
10942     Info.writeMem = false;
10943     return true;
10944   }
10945   case Intrinsic::arm_stlex:
10946   case Intrinsic::arm_strex: {
10947     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10948     Info.opc = ISD::INTRINSIC_W_CHAIN;
10949     Info.memVT = MVT::getVT(PtrTy->getElementType());
10950     Info.ptrVal = I.getArgOperand(1);
10951     Info.offset = 0;
10952     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10953     Info.vol = true;
10954     Info.readMem = false;
10955     Info.writeMem = true;
10956     return true;
10957   }
10958   case Intrinsic::arm_stlexd:
10959   case Intrinsic::arm_strexd: {
10960     Info.opc = ISD::INTRINSIC_W_CHAIN;
10961     Info.memVT = MVT::i64;
10962     Info.ptrVal = I.getArgOperand(2);
10963     Info.offset = 0;
10964     Info.align = 8;
10965     Info.vol = true;
10966     Info.readMem = false;
10967     Info.writeMem = true;
10968     return true;
10969   }
10970   case Intrinsic::arm_ldaexd:
10971   case Intrinsic::arm_ldrexd: {
10972     Info.opc = ISD::INTRINSIC_W_CHAIN;
10973     Info.memVT = MVT::i64;
10974     Info.ptrVal = I.getArgOperand(0);
10975     Info.offset = 0;
10976     Info.align = 8;
10977     Info.vol = true;
10978     Info.readMem = true;
10979     Info.writeMem = false;
10980     return true;
10981   }
10982   default:
10983     break;
10984   }
10985
10986   return false;
10987 }
10988
10989 /// \brief Returns true if it is beneficial to convert a load of a constant
10990 /// to just the constant itself.
10991 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10992                                                           Type *Ty) const {
10993   assert(Ty->isIntegerTy());
10994
10995   unsigned Bits = Ty->getPrimitiveSizeInBits();
10996   if (Bits == 0 || Bits > 32)
10997     return false;
10998   return true;
10999 }
11000
11001 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
11002   // Loads and stores less than 64-bits are already atomic; ones above that
11003   // are doomed anyway, so defer to the default libcall and blame the OS when
11004   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11005   // anything for those.
11006   bool IsMClass = Subtarget->isMClass();
11007   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
11008     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11009     return Size == 64 && !IsMClass;
11010   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
11011     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
11012   }
11013
11014   // For the real atomic operations, we have ldrex/strex up to 32 bits,
11015   // and up to 64 bits on the non-M profiles
11016   unsigned AtomicLimit = IsMClass ? 32 : 64;
11017   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
11018 }
11019
11020 // This has so far only been implemented for MachO.
11021 bool ARMTargetLowering::useLoadStackGuardNode() const {
11022   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11023 }
11024
11025 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11026                                          AtomicOrdering Ord) const {
11027   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11028   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11029   bool IsAcquire = isAtLeastAcquire(Ord);
11030
11031   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11032   // intrinsic must return {i32, i32} and we have to recombine them into a
11033   // single i64 here.
11034   if (ValTy->getPrimitiveSizeInBits() == 64) {
11035     Intrinsic::ID Int =
11036         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11037     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11038
11039     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11040     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11041
11042     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11043     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11044     if (!Subtarget->isLittle())
11045       std::swap (Lo, Hi);
11046     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11047     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11048     return Builder.CreateOr(
11049         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11050   }
11051
11052   Type *Tys[] = { Addr->getType() };
11053   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11054   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11055
11056   return Builder.CreateTruncOrBitCast(
11057       Builder.CreateCall(Ldrex, Addr),
11058       cast<PointerType>(Addr->getType())->getElementType());
11059 }
11060
11061 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11062                                                Value *Addr,
11063                                                AtomicOrdering Ord) const {
11064   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11065   bool IsRelease = isAtLeastRelease(Ord);
11066
11067   // Since the intrinsics must have legal type, the i64 intrinsics take two
11068   // parameters: "i32, i32". We must marshal Val into the appropriate form
11069   // before the call.
11070   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11071     Intrinsic::ID Int =
11072         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11073     Function *Strex = Intrinsic::getDeclaration(M, Int);
11074     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11075
11076     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11077     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11078     if (!Subtarget->isLittle())
11079       std::swap (Lo, Hi);
11080     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11081     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11082   }
11083
11084   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11085   Type *Tys[] = { Addr->getType() };
11086   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11087
11088   return Builder.CreateCall2(
11089       Strex, Builder.CreateZExtOrBitCast(
11090                  Val, Strex->getFunctionType()->getParamType(0)),
11091       Addr);
11092 }
11093
11094 enum HABaseType {
11095   HA_UNKNOWN = 0,
11096   HA_FLOAT,
11097   HA_DOUBLE,
11098   HA_VECT64,
11099   HA_VECT128
11100 };
11101
11102 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11103                                    uint64_t &Members) {
11104   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11105     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11106       uint64_t SubMembers = 0;
11107       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11108         return false;
11109       Members += SubMembers;
11110     }
11111   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11112     uint64_t SubMembers = 0;
11113     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11114       return false;
11115     Members += SubMembers * AT->getNumElements();
11116   } else if (Ty->isFloatTy()) {
11117     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11118       return false;
11119     Members = 1;
11120     Base = HA_FLOAT;
11121   } else if (Ty->isDoubleTy()) {
11122     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11123       return false;
11124     Members = 1;
11125     Base = HA_DOUBLE;
11126   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11127     Members = 1;
11128     switch (Base) {
11129     case HA_FLOAT:
11130     case HA_DOUBLE:
11131       return false;
11132     case HA_VECT64:
11133       return VT->getBitWidth() == 64;
11134     case HA_VECT128:
11135       return VT->getBitWidth() == 128;
11136     case HA_UNKNOWN:
11137       switch (VT->getBitWidth()) {
11138       case 64:
11139         Base = HA_VECT64;
11140         return true;
11141       case 128:
11142         Base = HA_VECT128;
11143         return true;
11144       default:
11145         return false;
11146       }
11147     }
11148   }
11149
11150   return (Members > 0 && Members <= 4);
11151 }
11152
11153 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11154 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11155     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11156   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11157       CallingConv::ARM_AAPCS_VFP)
11158     return false;
11159
11160   HABaseType Base = HA_UNKNOWN;
11161   uint64_t Members = 0;
11162   bool result = isHomogeneousAggregate(Ty, Base, Members);
11163   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11164   return result;
11165 }