Revert "ARM: improve RTABI 4.2 conformance on Linux"
[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       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271
272       // Double-precision floating-point comparison helper functions
273       // RTABI chapter 4.1.2, Table 3
274       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
282
283       // Single-precision floating-point arithmetic helper functions
284       // RTABI chapter 4.1.2, Table 4
285       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289
290       // Single-precision floating-point comparison helper functions
291       // RTABI chapter 4.1.2, Table 5
292       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
300
301       // Floating-point to integer conversions.
302       // RTABI chapter 4.1.2, Table 6
303       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Conversions between floating types.
313       // RTABI chapter 4.1.2, Table 7
314       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317
318       // Integer to floating-point conversions.
319       // RTABI chapter 4.1.2, Table 8
320       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328
329       // Long long helper functions
330       // RTABI chapter 4.2, Table 9
331       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335
336       // Integer division functions
337       // RTABI chapter 4.3.1
338       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346
347       // Memory operations
348       // RTABI chapter 4.3.4
349       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352     };
353
354     for (const auto &LC : LibraryCalls) {
355       setLibcallName(LC.Op, LC.Name);
356       setLibcallCallingConv(LC.Op, LC.CC);
357       if (LC.Cond != ISD::SETCC_INVALID)
358         setCmpLibcallCC(LC.Op, LC.Cond);
359     }
360   }
361
362   if (Subtarget->isTargetWindows()) {
363     static const struct {
364       const RTLIB::Libcall Op;
365       const char * const Name;
366       const CallingConv::ID CC;
367     } LibraryCalls[] = {
368       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
376     };
377
378     for (const auto &LC : LibraryCalls) {
379       setLibcallName(LC.Op, LC.Name);
380       setLibcallCallingConv(LC.Op, LC.CC);
381     }
382   }
383
384   // Use divmod compiler-rt calls for iOS 5.0 and later.
385   if (Subtarget->getTargetTriple().isiOS() &&
386       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
389   }
390
391   // The half <-> float conversion functions are always soft-float, but are
392   // needed for some targets which use a hard-float calling convention by
393   // default.
394   if (Subtarget->isAAPCS_ABI()) {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
398   } else {
399     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
402   }
403
404   if (Subtarget->isThumb1Only())
405     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
406   else
407     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
409       !Subtarget->isThumb1Only()) {
410     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
412   }
413
414   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
415        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
416     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
417          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
418       setTruncStoreAction((MVT::SimpleValueType)VT,
419                           (MVT::SimpleValueType)InnerVT, Expand);
420     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
421     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
423
424     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
425     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
426     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
427     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
428
429     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
430   }
431
432   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
433   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
434
435   if (Subtarget->hasNEON()) {
436     addDRTypeForNEON(MVT::v2f32);
437     addDRTypeForNEON(MVT::v8i8);
438     addDRTypeForNEON(MVT::v4i16);
439     addDRTypeForNEON(MVT::v2i32);
440     addDRTypeForNEON(MVT::v1i64);
441
442     addQRTypeForNEON(MVT::v4f32);
443     addQRTypeForNEON(MVT::v2f64);
444     addQRTypeForNEON(MVT::v16i8);
445     addQRTypeForNEON(MVT::v8i16);
446     addQRTypeForNEON(MVT::v4i32);
447     addQRTypeForNEON(MVT::v2i64);
448
449     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
450     // neither Neon nor VFP support any arithmetic operations on it.
451     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
452     // supported for v4f32.
453     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
454     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
455     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
456     // FIXME: Code duplication: FDIV and FREM are expanded always, see
457     // ARMTargetLowering::addTypeForNEON method for details.
458     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
459     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
460     // FIXME: Create unittest.
461     // In another words, find a way when "copysign" appears in DAG with vector
462     // operands.
463     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
464     // FIXME: Code duplication: SETCC has custom operation action, see
465     // ARMTargetLowering::addTypeForNEON method for details.
466     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
467     // FIXME: Create unittest for FNEG and for FABS.
468     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
469     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
470     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
472     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
473     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
475     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
478     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
480     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
481     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
482     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
483     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
484     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
486     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
487
488     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
489     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
490     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
491     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
493     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
496     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
498     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
499     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
500     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
501     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
503
504     // Mark v2f32 intrinsics.
505     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
506     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
507     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
508     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
510     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
513     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
515     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
516     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
517     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
518     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
520
521     // Neon does not support some operations on v1i64 and v2i64 types.
522     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
523     // Custom handling for some quad-vector types to detect VMULL.
524     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
525     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
526     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
527     // Custom handling for some vector types to avoid expensive expansions
528     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
529     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
530     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
531     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
532     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
533     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
534     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
535     // a destination type that is wider than the source, and nor does
536     // it have a FP_TO_[SU]INT instruction with a narrower destination than
537     // source.
538     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
539     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
542
543     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
544     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
545
546     // NEON does not have single instruction CTPOP for vectors with element
547     // types wider than 8-bits.  However, custom lowering can leverage the
548     // v8i8/v16i8 vcnt instruction.
549     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
550     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
553
554     // NEON only has FMA instructions as of VFP4.
555     if (!Subtarget->hasVFP4()) {
556       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
557       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
558     }
559
560     setTargetDAGCombine(ISD::INTRINSIC_VOID);
561     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
562     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
563     setTargetDAGCombine(ISD::SHL);
564     setTargetDAGCombine(ISD::SRL);
565     setTargetDAGCombine(ISD::SRA);
566     setTargetDAGCombine(ISD::SIGN_EXTEND);
567     setTargetDAGCombine(ISD::ZERO_EXTEND);
568     setTargetDAGCombine(ISD::ANY_EXTEND);
569     setTargetDAGCombine(ISD::SELECT_CC);
570     setTargetDAGCombine(ISD::BUILD_VECTOR);
571     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
572     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
573     setTargetDAGCombine(ISD::STORE);
574     setTargetDAGCombine(ISD::FP_TO_SINT);
575     setTargetDAGCombine(ISD::FP_TO_UINT);
576     setTargetDAGCombine(ISD::FDIV);
577
578     // It is legal to extload from v4i8 to v4i16 or v4i32.
579     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
580                   MVT::v4i16, MVT::v2i16,
581                   MVT::v2i32};
582     for (unsigned i = 0; i < 6; ++i) {
583       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
584       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
585       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
586     }
587   }
588
589   // ARM and Thumb2 support UMLAL/SMLAL.
590   if (!Subtarget->isThumb1Only())
591     setTargetDAGCombine(ISD::ADDC);
592
593   if (Subtarget->isFPOnlySP()) {
594     // When targetting a floating-point unit with only single-precision
595     // operations, f64 is legal for the few double-precision instructions which
596     // are present However, no double-precision operations other than moves,
597     // loads and stores are provided by the hardware.
598     setOperationAction(ISD::FADD,       MVT::f64, Expand);
599     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
600     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
601     setOperationAction(ISD::FMA,        MVT::f64, Expand);
602     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
603     setOperationAction(ISD::FREM,       MVT::f64, Expand);
604     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
605     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
606     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
607     setOperationAction(ISD::FABS,       MVT::f64, Expand);
608     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
609     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
610     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
611     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
612     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
613     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
614     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
615     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
616     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
617     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
618     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
619     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
620     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
621     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
622     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
623     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
624     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
625   }
626
627   computeRegisterProperties();
628
629   // ARM does not have floating-point extending loads.
630   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
631   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
632
633   // ... or truncating stores
634   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
635   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
636   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
637
638   // ARM does not have i1 sign extending load.
639   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
640
641   // ARM supports all 4 flavors of integer indexed load / store.
642   if (!Subtarget->isThumb1Only()) {
643     for (unsigned im = (unsigned)ISD::PRE_INC;
644          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
645       setIndexedLoadAction(im,  MVT::i1,  Legal);
646       setIndexedLoadAction(im,  MVT::i8,  Legal);
647       setIndexedLoadAction(im,  MVT::i16, Legal);
648       setIndexedLoadAction(im,  MVT::i32, Legal);
649       setIndexedStoreAction(im, MVT::i1,  Legal);
650       setIndexedStoreAction(im, MVT::i8,  Legal);
651       setIndexedStoreAction(im, MVT::i16, Legal);
652       setIndexedStoreAction(im, MVT::i32, Legal);
653     }
654   }
655
656   setOperationAction(ISD::SADDO, MVT::i32, Custom);
657   setOperationAction(ISD::UADDO, MVT::i32, Custom);
658   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
659   setOperationAction(ISD::USUBO, MVT::i32, Custom);
660
661   // i64 operation support.
662   setOperationAction(ISD::MUL,     MVT::i64, Expand);
663   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
664   if (Subtarget->isThumb1Only()) {
665     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
666     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
667   }
668   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
669       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
670     setOperationAction(ISD::MULHS, MVT::i32, Expand);
671
672   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
673   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
674   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
675   setOperationAction(ISD::SRL,       MVT::i64, Custom);
676   setOperationAction(ISD::SRA,       MVT::i64, Custom);
677
678   if (!Subtarget->isThumb1Only()) {
679     // FIXME: We should do this for Thumb1 as well.
680     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
681     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
682     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
683     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
684   }
685
686   // ARM does not have ROTL.
687   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
688   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
689   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
690   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
691     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
692
693   // These just redirect to CTTZ and CTLZ on ARM.
694   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
695   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
696
697   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
698
699   // Only ARMv6 has BSWAP.
700   if (!Subtarget->hasV6Ops())
701     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
702
703   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
704       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
705     // These are expanded into libcalls if the cpu doesn't have HW divider.
706     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
707     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
708   }
709
710   // FIXME: Also set divmod for SREM on EABI
711   setOperationAction(ISD::SREM,  MVT::i32, Expand);
712   setOperationAction(ISD::UREM,  MVT::i32, Expand);
713   // Register based DivRem for AEABI (RTABI 4.2)
714   if (Subtarget->isTargetAEABI()) {
715     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
716     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
717     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
718     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
719     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
720     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
721     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
722     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
723
724     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
732
733     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
734     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
735   } else {
736     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
737     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
738   }
739
740   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
741   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
742   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
743   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
744   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
745
746   setOperationAction(ISD::TRAP, MVT::Other, Legal);
747
748   // Use the default implementation.
749   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
750   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
751   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
752   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
753   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
754   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
755
756   if (!Subtarget->isTargetMachO()) {
757     // Non-MachO platforms may return values in these registers via the
758     // personality function.
759     setExceptionPointerRegister(ARM::R0);
760     setExceptionSelectorRegister(ARM::R1);
761   }
762
763   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
764     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
765   else
766     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
767
768   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
769   // the default expansion. If we are targeting a single threaded system,
770   // then set them all for expand so we can lower them later into their
771   // non-atomic form.
772   if (TM.Options.ThreadModel == ThreadModel::Single)
773     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
774   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
775     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
776     // to ldrex/strex loops already.
777     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
778
779     // On v8, we have particularly efficient implementations of atomic fences
780     // if they can be combined with nearby atomic loads and stores.
781     if (!Subtarget->hasV8Ops()) {
782       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
783       setInsertFencesForAtomic(true);
784     }
785   } else {
786     // If there's anything we can use as a barrier, go through custom lowering
787     // for ATOMIC_FENCE.
788     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
789                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
790
791     // Set them all for expansion, which will force libcalls.
792     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
804     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
805     // Unordered/Monotonic case.
806     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
807     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
808   }
809
810   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
811
812   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
813   if (!Subtarget->hasV6Ops()) {
814     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
815     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
816   }
817   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
818
819   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
820       !Subtarget->isThumb1Only()) {
821     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
822     // iff target supports vfp2.
823     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
824     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
825   }
826
827   // We want to custom lower some of our intrinsics.
828   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
829   if (Subtarget->isTargetDarwin()) {
830     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
831     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
832     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
833   }
834
835   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
836   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
837   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
838   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
839   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
840   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
841   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
842   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
844
845   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
846   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
847   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
848   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
849   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
850
851   // We don't support sin/cos/fmod/copysign/pow
852   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
853   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
854   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
855   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
856   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
857   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
858   setOperationAction(ISD::FREM,      MVT::f64, Expand);
859   setOperationAction(ISD::FREM,      MVT::f32, Expand);
860   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
861       !Subtarget->isThumb1Only()) {
862     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
863     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
864   }
865   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
866   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
867
868   if (!Subtarget->hasVFP4()) {
869     setOperationAction(ISD::FMA, MVT::f64, Expand);
870     setOperationAction(ISD::FMA, MVT::f32, Expand);
871   }
872
873   // Various VFP goodness
874   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
875     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
876     if (Subtarget->hasVFP2()) {
877       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
878       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
879       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
880       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
881     }
882
883     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
884     if (!Subtarget->hasV8Ops()) {
885       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
886       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
887     }
888
889     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
890     if (!Subtarget->hasFP16()) {
891       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
892       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
893     }
894   }
895
896   // Combine sin / cos into one node or libcall if possible.
897   if (Subtarget->hasSinCos()) {
898     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
899     setLibcallName(RTLIB::SINCOS_F64, "sincos");
900     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
901       // For iOS, we don't want to the normal expansion of a libcall to
902       // sincos. We want to issue a libcall to __sincos_stret.
903       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
904       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
905     }
906   }
907
908   // ARMv8 implements a lot of rounding-like FP operations.
909   if (Subtarget->hasV8Ops()) {
910     static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
911     for (const auto Ty : RoundingTypes) {
912       setOperationAction(ISD::FFLOOR, Ty, Legal);
913       setOperationAction(ISD::FCEIL, Ty, Legal);
914       setOperationAction(ISD::FROUND, Ty, Legal);
915       setOperationAction(ISD::FTRUNC, Ty, Legal);
916       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
917       setOperationAction(ISD::FRINT, Ty, Legal);
918     }
919   }
920   // We have target-specific dag combine patterns for the following nodes:
921   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
922   setTargetDAGCombine(ISD::ADD);
923   setTargetDAGCombine(ISD::SUB);
924   setTargetDAGCombine(ISD::MUL);
925   setTargetDAGCombine(ISD::AND);
926   setTargetDAGCombine(ISD::OR);
927   setTargetDAGCombine(ISD::XOR);
928
929   if (Subtarget->hasV6Ops())
930     setTargetDAGCombine(ISD::SRL);
931
932   setStackPointerRegisterToSaveRestore(ARM::SP);
933
934   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
935       !Subtarget->hasVFP2())
936     setSchedulingPreference(Sched::RegPressure);
937   else
938     setSchedulingPreference(Sched::Hybrid);
939
940   //// temporary - rewrite interface to use type
941   MaxStoresPerMemset = 8;
942   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
943   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
944   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
945   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
946   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
947
948   // On ARM arguments smaller than 4 bytes are extended, so all arguments
949   // are at least 4 bytes aligned.
950   setMinStackArgumentAlignment(4);
951
952   // Prefer likely predicted branches to selects on out-of-order cores.
953   PredictableSelectIsExpensive = Subtarget->isLikeA9();
954
955   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
956 }
957
958 // FIXME: It might make sense to define the representative register class as the
959 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
960 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
961 // SPR's representative would be DPR_VFP2. This should work well if register
962 // pressure tracking were modified such that a register use would increment the
963 // pressure of the register class's representative and all of it's super
964 // classes' representatives transitively. We have not implemented this because
965 // of the difficulty prior to coalescing of modeling operand register classes
966 // due to the common occurrence of cross class copies and subregister insertions
967 // and extractions.
968 std::pair<const TargetRegisterClass*, uint8_t>
969 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
970   const TargetRegisterClass *RRC = nullptr;
971   uint8_t Cost = 1;
972   switch (VT.SimpleTy) {
973   default:
974     return TargetLowering::findRepresentativeClass(VT);
975   // Use DPR as representative register class for all floating point
976   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
977   // the cost is 1 for both f32 and f64.
978   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
979   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
980     RRC = &ARM::DPRRegClass;
981     // When NEON is used for SP, only half of the register file is available
982     // because operations that define both SP and DP results will be constrained
983     // to the VFP2 class (D0-D15). We currently model this constraint prior to
984     // coalescing by double-counting the SP regs. See the FIXME above.
985     if (Subtarget->useNEONForSinglePrecisionFP())
986       Cost = 2;
987     break;
988   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
989   case MVT::v4f32: case MVT::v2f64:
990     RRC = &ARM::DPRRegClass;
991     Cost = 2;
992     break;
993   case MVT::v4i64:
994     RRC = &ARM::DPRRegClass;
995     Cost = 4;
996     break;
997   case MVT::v8i64:
998     RRC = &ARM::DPRRegClass;
999     Cost = 8;
1000     break;
1001   }
1002   return std::make_pair(RRC, Cost);
1003 }
1004
1005 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1006   switch (Opcode) {
1007   default: return nullptr;
1008   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1009   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1010   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1011   case ARMISD::CALL:          return "ARMISD::CALL";
1012   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1013   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1014   case ARMISD::tCALL:         return "ARMISD::tCALL";
1015   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1016   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1017   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1018   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1019   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1020   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1021   case ARMISD::CMP:           return "ARMISD::CMP";
1022   case ARMISD::CMN:           return "ARMISD::CMN";
1023   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1024   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1025   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1026   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1027   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1028
1029   case ARMISD::CMOV:          return "ARMISD::CMOV";
1030
1031   case ARMISD::RBIT:          return "ARMISD::RBIT";
1032
1033   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1034   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1035   case ARMISD::SITOF:         return "ARMISD::SITOF";
1036   case ARMISD::UITOF:         return "ARMISD::UITOF";
1037
1038   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1039   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1040   case ARMISD::RRX:           return "ARMISD::RRX";
1041
1042   case ARMISD::ADDC:          return "ARMISD::ADDC";
1043   case ARMISD::ADDE:          return "ARMISD::ADDE";
1044   case ARMISD::SUBC:          return "ARMISD::SUBC";
1045   case ARMISD::SUBE:          return "ARMISD::SUBE";
1046
1047   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1048   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1049
1050   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1051   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1052
1053   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1054
1055   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1056
1057   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1058
1059   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1060
1061   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1062
1063   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1064
1065   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1066   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1067   case ARMISD::VCGE:          return "ARMISD::VCGE";
1068   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1069   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1070   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1071   case ARMISD::VCGT:          return "ARMISD::VCGT";
1072   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1073   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1074   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1075   case ARMISD::VTST:          return "ARMISD::VTST";
1076
1077   case ARMISD::VSHL:          return "ARMISD::VSHL";
1078   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1079   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1080   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1081   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1082   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1083   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1084   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1085   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1086   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1087   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1088   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1089   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1090   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1091   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1092   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1093   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1094   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1095   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1096   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1097   case ARMISD::VDUP:          return "ARMISD::VDUP";
1098   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1099   case ARMISD::VEXT:          return "ARMISD::VEXT";
1100   case ARMISD::VREV64:        return "ARMISD::VREV64";
1101   case ARMISD::VREV32:        return "ARMISD::VREV32";
1102   case ARMISD::VREV16:        return "ARMISD::VREV16";
1103   case ARMISD::VZIP:          return "ARMISD::VZIP";
1104   case ARMISD::VUZP:          return "ARMISD::VUZP";
1105   case ARMISD::VTRN:          return "ARMISD::VTRN";
1106   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1107   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1108   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1109   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1110   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1111   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1112   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1113   case ARMISD::FMAX:          return "ARMISD::FMAX";
1114   case ARMISD::FMIN:          return "ARMISD::FMIN";
1115   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1116   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1117   case ARMISD::BFI:           return "ARMISD::BFI";
1118   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1119   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1120   case ARMISD::VBSL:          return "ARMISD::VBSL";
1121   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1122   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1123   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1124   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1125   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1126   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1127   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1128   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1129   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1130   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1131   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1132   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1133   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1134   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1135   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1136   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1137   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1138   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1139   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1140   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1141   }
1142 }
1143
1144 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1145   if (!VT.isVector()) return getPointerTy();
1146   return VT.changeVectorElementTypeToInteger();
1147 }
1148
1149 /// getRegClassFor - Return the register class that should be used for the
1150 /// specified value type.
1151 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1152   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1153   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1154   // load / store 4 to 8 consecutive D registers.
1155   if (Subtarget->hasNEON()) {
1156     if (VT == MVT::v4i64)
1157       return &ARM::QQPRRegClass;
1158     if (VT == MVT::v8i64)
1159       return &ARM::QQQQPRRegClass;
1160   }
1161   return TargetLowering::getRegClassFor(VT);
1162 }
1163
1164 // Create a fast isel object.
1165 FastISel *
1166 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1167                                   const TargetLibraryInfo *libInfo) const {
1168   return ARM::createFastISel(funcInfo, libInfo);
1169 }
1170
1171 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1172 /// be used for loads / stores from the global.
1173 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1174   return (Subtarget->isThumb1Only() ? 127 : 4095);
1175 }
1176
1177 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1178   unsigned NumVals = N->getNumValues();
1179   if (!NumVals)
1180     return Sched::RegPressure;
1181
1182   for (unsigned i = 0; i != NumVals; ++i) {
1183     EVT VT = N->getValueType(i);
1184     if (VT == MVT::Glue || VT == MVT::Other)
1185       continue;
1186     if (VT.isFloatingPoint() || VT.isVector())
1187       return Sched::ILP;
1188   }
1189
1190   if (!N->isMachineOpcode())
1191     return Sched::RegPressure;
1192
1193   // Load are scheduled for latency even if there instruction itinerary
1194   // is not available.
1195   const TargetInstrInfo *TII =
1196       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1197   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1198
1199   if (MCID.getNumDefs() == 0)
1200     return Sched::RegPressure;
1201   if (!Itins->isEmpty() &&
1202       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1203     return Sched::ILP;
1204
1205   return Sched::RegPressure;
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Lowering Code
1210 //===----------------------------------------------------------------------===//
1211
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1214   switch (CC) {
1215   default: llvm_unreachable("Unknown condition code!");
1216   case ISD::SETNE:  return ARMCC::NE;
1217   case ISD::SETEQ:  return ARMCC::EQ;
1218   case ISD::SETGT:  return ARMCC::GT;
1219   case ISD::SETGE:  return ARMCC::GE;
1220   case ISD::SETLT:  return ARMCC::LT;
1221   case ISD::SETLE:  return ARMCC::LE;
1222   case ISD::SETUGT: return ARMCC::HI;
1223   case ISD::SETUGE: return ARMCC::HS;
1224   case ISD::SETULT: return ARMCC::LO;
1225   case ISD::SETULE: return ARMCC::LS;
1226   }
1227 }
1228
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231                         ARMCC::CondCodes &CondCode2) {
1232   CondCode2 = ARMCC::AL;
1233   switch (CC) {
1234   default: llvm_unreachable("Unknown FP condition!");
1235   case ISD::SETEQ:
1236   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1237   case ISD::SETGT:
1238   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1239   case ISD::SETGE:
1240   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244   case ISD::SETO:   CondCode = ARMCC::VC; break;
1245   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1246   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1249   case ISD::SETLT:
1250   case ISD::SETULT: CondCode = ARMCC::LT; break;
1251   case ISD::SETLE:
1252   case ISD::SETULE: CondCode = ARMCC::LE; break;
1253   case ISD::SETNE:
1254   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255   }
1256 }
1257
1258 //===----------------------------------------------------------------------===//
1259 //                      Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1261
1262 #include "ARMGenCallingConv.inc"
1263
1264 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1265 /// account presence of floating point hardware and calling convention
1266 /// limitations, such as support for variadic functions.
1267 CallingConv::ID
1268 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1269                                            bool isVarArg) const {
1270   switch (CC) {
1271   default:
1272     llvm_unreachable("Unsupported calling convention");
1273   case CallingConv::ARM_AAPCS:
1274   case CallingConv::ARM_APCS:
1275   case CallingConv::GHC:
1276     return CC;
1277   case CallingConv::ARM_AAPCS_VFP:
1278     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1279   case CallingConv::C:
1280     if (!Subtarget->isAAPCS_ABI())
1281       return CallingConv::ARM_APCS;
1282     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1283              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1284              !isVarArg)
1285       return CallingConv::ARM_AAPCS_VFP;
1286     else
1287       return CallingConv::ARM_AAPCS;
1288   case CallingConv::Fast:
1289     if (!Subtarget->isAAPCS_ABI()) {
1290       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1291         return CallingConv::Fast;
1292       return CallingConv::ARM_APCS;
1293     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1294       return CallingConv::ARM_AAPCS_VFP;
1295     else
1296       return CallingConv::ARM_AAPCS;
1297   }
1298 }
1299
1300 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1301 /// CallingConvention.
1302 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1303                                                  bool Return,
1304                                                  bool isVarArg) const {
1305   switch (getEffectiveCallingConv(CC, isVarArg)) {
1306   default:
1307     llvm_unreachable("Unsupported calling convention");
1308   case CallingConv::ARM_APCS:
1309     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1310   case CallingConv::ARM_AAPCS:
1311     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1312   case CallingConv::ARM_AAPCS_VFP:
1313     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1314   case CallingConv::Fast:
1315     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1316   case CallingConv::GHC:
1317     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1318   }
1319 }
1320
1321 /// LowerCallResult - Lower the result values of a call into the
1322 /// appropriate copies out of appropriate physical registers.
1323 SDValue
1324 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1325                                    CallingConv::ID CallConv, bool isVarArg,
1326                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1327                                    SDLoc dl, SelectionDAG &DAG,
1328                                    SmallVectorImpl<SDValue> &InVals,
1329                                    bool isThisReturn, SDValue ThisVal) const {
1330
1331   // Assign locations to each value returned by this call.
1332   SmallVector<CCValAssign, 16> RVLocs;
1333   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1334                     *DAG.getContext(), Call);
1335   CCInfo.AnalyzeCallResult(Ins,
1336                            CCAssignFnForNode(CallConv, /* Return*/ true,
1337                                              isVarArg));
1338
1339   // Copy all of the result registers out of their specified physreg.
1340   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1341     CCValAssign VA = RVLocs[i];
1342
1343     // Pass 'this' value directly from the argument to return value, to avoid
1344     // reg unit interference
1345     if (i == 0 && isThisReturn) {
1346       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1347              "unexpected return calling convention register assignment");
1348       InVals.push_back(ThisVal);
1349       continue;
1350     }
1351
1352     SDValue Val;
1353     if (VA.needsCustom()) {
1354       // Handle f64 or half of a v2f64.
1355       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1356                                       InFlag);
1357       Chain = Lo.getValue(1);
1358       InFlag = Lo.getValue(2);
1359       VA = RVLocs[++i]; // skip ahead to next loc
1360       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1361                                       InFlag);
1362       Chain = Hi.getValue(1);
1363       InFlag = Hi.getValue(2);
1364       if (!Subtarget->isLittle())
1365         std::swap (Lo, Hi);
1366       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1367
1368       if (VA.getLocVT() == MVT::v2f64) {
1369         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1370         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1371                           DAG.getConstant(0, MVT::i32));
1372
1373         VA = RVLocs[++i]; // skip ahead to next loc
1374         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1375         Chain = Lo.getValue(1);
1376         InFlag = Lo.getValue(2);
1377         VA = RVLocs[++i]; // skip ahead to next loc
1378         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379         Chain = Hi.getValue(1);
1380         InFlag = Hi.getValue(2);
1381         if (!Subtarget->isLittle())
1382           std::swap (Lo, Hi);
1383         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1384         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1385                           DAG.getConstant(1, MVT::i32));
1386       }
1387     } else {
1388       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1389                                InFlag);
1390       Chain = Val.getValue(1);
1391       InFlag = Val.getValue(2);
1392     }
1393
1394     switch (VA.getLocInfo()) {
1395     default: llvm_unreachable("Unknown loc info!");
1396     case CCValAssign::Full: break;
1397     case CCValAssign::BCvt:
1398       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1399       break;
1400     }
1401
1402     InVals.push_back(Val);
1403   }
1404
1405   return Chain;
1406 }
1407
1408 /// LowerMemOpCallTo - Store the argument to the stack.
1409 SDValue
1410 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1411                                     SDValue StackPtr, SDValue Arg,
1412                                     SDLoc dl, SelectionDAG &DAG,
1413                                     const CCValAssign &VA,
1414                                     ISD::ArgFlagsTy Flags) const {
1415   unsigned LocMemOffset = VA.getLocMemOffset();
1416   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1417   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1418   return DAG.getStore(Chain, dl, Arg, PtrOff,
1419                       MachinePointerInfo::getStack(LocMemOffset),
1420                       false, false, 0);
1421 }
1422
1423 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1424                                          SDValue Chain, SDValue &Arg,
1425                                          RegsToPassVector &RegsToPass,
1426                                          CCValAssign &VA, CCValAssign &NextVA,
1427                                          SDValue &StackPtr,
1428                                          SmallVectorImpl<SDValue> &MemOpChains,
1429                                          ISD::ArgFlagsTy Flags) const {
1430
1431   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1432                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1433   unsigned id = Subtarget->isLittle() ? 0 : 1;
1434   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1435
1436   if (NextVA.isRegLoc())
1437     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1438   else {
1439     assert(NextVA.isMemLoc());
1440     if (!StackPtr.getNode())
1441       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1442
1443     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1444                                            dl, DAG, NextVA,
1445                                            Flags));
1446   }
1447 }
1448
1449 /// LowerCall - Lowering a call into a callseq_start <-
1450 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1451 /// nodes.
1452 SDValue
1453 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1454                              SmallVectorImpl<SDValue> &InVals) const {
1455   SelectionDAG &DAG                     = CLI.DAG;
1456   SDLoc &dl                          = CLI.DL;
1457   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1458   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1459   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1460   SDValue Chain                         = CLI.Chain;
1461   SDValue Callee                        = CLI.Callee;
1462   bool &isTailCall                      = CLI.IsTailCall;
1463   CallingConv::ID CallConv              = CLI.CallConv;
1464   bool doesNotRet                       = CLI.DoesNotReturn;
1465   bool isVarArg                         = CLI.IsVarArg;
1466
1467   MachineFunction &MF = DAG.getMachineFunction();
1468   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1469   bool isThisReturn   = false;
1470   bool isSibCall      = false;
1471
1472   // Disable tail calls if they're not supported.
1473   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1474     isTailCall = false;
1475
1476   if (isTailCall) {
1477     // Check if it's really possible to do a tail call.
1478     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1479                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1480                                                    Outs, OutVals, Ins, DAG);
1481     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1482       report_fatal_error("failed to perform tail call elimination on a call "
1483                          "site marked musttail");
1484     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1485     // detected sibcalls.
1486     if (isTailCall) {
1487       ++NumTailCalls;
1488       isSibCall = true;
1489     }
1490   }
1491
1492   // Analyze operands of the call, assigning locations to each operand.
1493   SmallVector<CCValAssign, 16> ArgLocs;
1494   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1495                     *DAG.getContext(), Call);
1496   CCInfo.AnalyzeCallOperands(Outs,
1497                              CCAssignFnForNode(CallConv, /* Return*/ false,
1498                                                isVarArg));
1499
1500   // Get a count of how many bytes are to be pushed on the stack.
1501   unsigned NumBytes = CCInfo.getNextStackOffset();
1502
1503   // For tail calls, memory operands are available in our caller's stack.
1504   if (isSibCall)
1505     NumBytes = 0;
1506
1507   // Adjust the stack pointer for the new arguments...
1508   // These operations are automatically eliminated by the prolog/epilog pass
1509   if (!isSibCall)
1510     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1511                                  dl);
1512
1513   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1514
1515   RegsToPassVector RegsToPass;
1516   SmallVector<SDValue, 8> MemOpChains;
1517
1518   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1519   // of tail call optimization, arguments are handled later.
1520   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1521        i != e;
1522        ++i, ++realArgIdx) {
1523     CCValAssign &VA = ArgLocs[i];
1524     SDValue Arg = OutVals[realArgIdx];
1525     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1526     bool isByVal = Flags.isByVal();
1527
1528     // Promote the value if needed.
1529     switch (VA.getLocInfo()) {
1530     default: llvm_unreachable("Unknown loc info!");
1531     case CCValAssign::Full: break;
1532     case CCValAssign::SExt:
1533       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1534       break;
1535     case CCValAssign::ZExt:
1536       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1537       break;
1538     case CCValAssign::AExt:
1539       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1540       break;
1541     case CCValAssign::BCvt:
1542       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1543       break;
1544     }
1545
1546     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1547     if (VA.needsCustom()) {
1548       if (VA.getLocVT() == MVT::v2f64) {
1549         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1550                                   DAG.getConstant(0, MVT::i32));
1551         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1552                                   DAG.getConstant(1, MVT::i32));
1553
1554         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1555                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1556
1557         VA = ArgLocs[++i]; // skip ahead to next loc
1558         if (VA.isRegLoc()) {
1559           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1560                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1561         } else {
1562           assert(VA.isMemLoc());
1563
1564           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1565                                                  dl, DAG, VA, Flags));
1566         }
1567       } else {
1568         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1569                          StackPtr, MemOpChains, Flags);
1570       }
1571     } else if (VA.isRegLoc()) {
1572       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1573         assert(VA.getLocVT() == MVT::i32 &&
1574                "unexpected calling convention register assignment");
1575         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1576                "unexpected use of 'returned'");
1577         isThisReturn = true;
1578       }
1579       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1580     } else if (isByVal) {
1581       assert(VA.isMemLoc());
1582       unsigned offset = 0;
1583
1584       // True if this byval aggregate will be split between registers
1585       // and memory.
1586       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1587       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1588
1589       if (CurByValIdx < ByValArgsCount) {
1590
1591         unsigned RegBegin, RegEnd;
1592         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1593
1594         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1595         unsigned int i, j;
1596         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1597           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1598           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1599           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1600                                      MachinePointerInfo(),
1601                                      false, false, false,
1602                                      DAG.InferPtrAlignment(AddArg));
1603           MemOpChains.push_back(Load.getValue(1));
1604           RegsToPass.push_back(std::make_pair(j, Load));
1605         }
1606
1607         // If parameter size outsides register area, "offset" value
1608         // helps us to calculate stack slot for remained part properly.
1609         offset = RegEnd - RegBegin;
1610
1611         CCInfo.nextInRegsParam();
1612       }
1613
1614       if (Flags.getByValSize() > 4*offset) {
1615         unsigned LocMemOffset = VA.getLocMemOffset();
1616         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1617         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1618                                   StkPtrOff);
1619         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1620         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1621         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1622                                            MVT::i32);
1623         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1624
1625         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1626         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1627         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1628                                           Ops));
1629       }
1630     } else if (!isSibCall) {
1631       assert(VA.isMemLoc());
1632
1633       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1634                                              dl, DAG, VA, Flags));
1635     }
1636   }
1637
1638   if (!MemOpChains.empty())
1639     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1640
1641   // Build a sequence of copy-to-reg nodes chained together with token chain
1642   // and flag operands which copy the outgoing args into the appropriate regs.
1643   SDValue InFlag;
1644   // Tail call byval lowering might overwrite argument registers so in case of
1645   // tail call optimization the copies to registers are lowered later.
1646   if (!isTailCall)
1647     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1648       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1649                                RegsToPass[i].second, InFlag);
1650       InFlag = Chain.getValue(1);
1651     }
1652
1653   // For tail calls lower the arguments to the 'real' stack slot.
1654   if (isTailCall) {
1655     // Force all the incoming stack arguments to be loaded from the stack
1656     // before any new outgoing arguments are stored to the stack, because the
1657     // outgoing stack slots may alias the incoming argument stack slots, and
1658     // the alias isn't otherwise explicit. This is slightly more conservative
1659     // than necessary, because it means that each store effectively depends
1660     // on every argument instead of just those arguments it would clobber.
1661
1662     // Do not flag preceding copytoreg stuff together with the following stuff.
1663     InFlag = SDValue();
1664     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1665       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1666                                RegsToPass[i].second, InFlag);
1667       InFlag = Chain.getValue(1);
1668     }
1669     InFlag = SDValue();
1670   }
1671
1672   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1673   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1674   // node so that legalize doesn't hack it.
1675   bool isDirect = false;
1676   bool isARMFunc = false;
1677   bool isLocalARMFunc = false;
1678   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1679
1680   if (EnableARMLongCalls) {
1681     assert((Subtarget->isTargetWindows() ||
1682             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1683            "long-calls with non-static relocation model!");
1684     // Handle a global address or an external symbol. If it's not one of
1685     // those, the target's already in a register, so we don't need to do
1686     // anything extra.
1687     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1688       const GlobalValue *GV = G->getGlobal();
1689       // Create a constant pool entry for the callee address
1690       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1691       ARMConstantPoolValue *CPV =
1692         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1693
1694       // Get the address of the callee into a register
1695       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1696       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1697       Callee = DAG.getLoad(getPointerTy(), dl,
1698                            DAG.getEntryNode(), CPAddr,
1699                            MachinePointerInfo::getConstantPool(),
1700                            false, false, false, 0);
1701     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1702       const char *Sym = S->getSymbol();
1703
1704       // Create a constant pool entry for the callee address
1705       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1706       ARMConstantPoolValue *CPV =
1707         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1708                                       ARMPCLabelIndex, 0);
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     }
1717   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1718     const GlobalValue *GV = G->getGlobal();
1719     isDirect = true;
1720     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1721     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1722                    getTargetMachine().getRelocationModel() != Reloc::Static;
1723     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1724     // ARM call to a local ARM function is predicable.
1725     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1726     // tBX takes a register source operand.
1727     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1728       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1729       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1730                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1731                                                       0, ARMII::MO_NONLAZY));
1732       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1733                            MachinePointerInfo::getGOT(), false, false, true, 0);
1734     } else if (Subtarget->isTargetCOFF()) {
1735       assert(Subtarget->isTargetWindows() &&
1736              "Windows is the only supported COFF target");
1737       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1738                                  ? ARMII::MO_DLLIMPORT
1739                                  : ARMII::MO_NO_FLAG;
1740       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1741                                           TargetFlags);
1742       if (GV->hasDLLImportStorageClass())
1743         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1744                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1745                                          Callee), MachinePointerInfo::getGOT(),
1746                              false, false, false, 0);
1747     } else {
1748       // On ELF targets for PIC code, direct calls should go through the PLT
1749       unsigned OpFlags = 0;
1750       if (Subtarget->isTargetELF() &&
1751           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1752         OpFlags = ARMII::MO_PLT;
1753       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1754     }
1755   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1756     isDirect = true;
1757     bool isStub = Subtarget->isTargetMachO() &&
1758                   getTargetMachine().getRelocationModel() != Reloc::Static;
1759     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1760     // tBX takes a register source operand.
1761     const char *Sym = S->getSymbol();
1762     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1763       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1764       ARMConstantPoolValue *CPV =
1765         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1766                                       ARMPCLabelIndex, 4);
1767       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1768       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1769       Callee = DAG.getLoad(getPointerTy(), dl,
1770                            DAG.getEntryNode(), CPAddr,
1771                            MachinePointerInfo::getConstantPool(),
1772                            false, false, false, 0);
1773       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1774       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1775                            getPointerTy(), Callee, PICLabel);
1776     } else {
1777       unsigned OpFlags = 0;
1778       // On ELF targets for PIC code, direct calls should go through the PLT
1779       if (Subtarget->isTargetELF() &&
1780                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1781         OpFlags = ARMII::MO_PLT;
1782       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1783     }
1784   }
1785
1786   // FIXME: handle tail calls differently.
1787   unsigned CallOpc;
1788   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1789       AttributeSet::FunctionIndex, Attribute::MinSize);
1790   if (Subtarget->isThumb()) {
1791     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1792       CallOpc = ARMISD::CALL_NOLINK;
1793     else
1794       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1795   } else {
1796     if (!isDirect && !Subtarget->hasV5TOps())
1797       CallOpc = ARMISD::CALL_NOLINK;
1798     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1799                // Emit regular call when code size is the priority
1800                !HasMinSizeAttr)
1801       // "mov lr, pc; b _foo" to avoid confusing the RSP
1802       CallOpc = ARMISD::CALL_NOLINK;
1803     else
1804       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1805   }
1806
1807   std::vector<SDValue> Ops;
1808   Ops.push_back(Chain);
1809   Ops.push_back(Callee);
1810
1811   // Add argument registers to the end of the list so that they are known live
1812   // into the call.
1813   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1814     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1815                                   RegsToPass[i].second.getValueType()));
1816
1817   // Add a register mask operand representing the call-preserved registers.
1818   if (!isTailCall) {
1819     const uint32_t *Mask;
1820     const TargetRegisterInfo *TRI =
1821         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1822     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1823     if (isThisReturn) {
1824       // For 'this' returns, use the R0-preserving mask if applicable
1825       Mask = ARI->getThisReturnPreservedMask(CallConv);
1826       if (!Mask) {
1827         // Set isThisReturn to false if the calling convention is not one that
1828         // allows 'returned' to be modeled in this way, so LowerCallResult does
1829         // not try to pass 'this' straight through
1830         isThisReturn = false;
1831         Mask = ARI->getCallPreservedMask(CallConv);
1832       }
1833     } else
1834       Mask = ARI->getCallPreservedMask(CallConv);
1835
1836     assert(Mask && "Missing call preserved mask for calling convention");
1837     Ops.push_back(DAG.getRegisterMask(Mask));
1838   }
1839
1840   if (InFlag.getNode())
1841     Ops.push_back(InFlag);
1842
1843   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1844   if (isTailCall)
1845     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1846
1847   // Returns a chain and a flag for retval copy to use.
1848   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1849   InFlag = Chain.getValue(1);
1850
1851   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1852                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1853   if (!Ins.empty())
1854     InFlag = Chain.getValue(1);
1855
1856   // Handle result values, copying them out of physregs into vregs that we
1857   // return.
1858   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1859                          InVals, isThisReturn,
1860                          isThisReturn ? OutVals[0] : SDValue());
1861 }
1862
1863 /// HandleByVal - Every parameter *after* a byval parameter is passed
1864 /// on the stack.  Remember the next parameter register to allocate,
1865 /// and then confiscate the rest of the parameter registers to insure
1866 /// this.
1867 void
1868 ARMTargetLowering::HandleByVal(
1869     CCState *State, unsigned &size, unsigned Align) const {
1870   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1871   assert((State->getCallOrPrologue() == Prologue ||
1872           State->getCallOrPrologue() == Call) &&
1873          "unhandled ParmContext");
1874
1875   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1876     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1877       unsigned AlignInRegs = Align / 4;
1878       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1879       for (unsigned i = 0; i < Waste; ++i)
1880         reg = State->AllocateReg(GPRArgRegs, 4);
1881     }
1882     if (reg != 0) {
1883       unsigned excess = 4 * (ARM::R4 - reg);
1884
1885       // Special case when NSAA != SP and parameter size greater than size of
1886       // all remained GPR regs. In that case we can't split parameter, we must
1887       // send it to stack. We also must set NCRN to R4, so waste all
1888       // remained registers.
1889       const unsigned NSAAOffset = State->getNextStackOffset();
1890       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1891         while (State->AllocateReg(GPRArgRegs, 4))
1892           ;
1893         return;
1894       }
1895
1896       // First register for byval parameter is the first register that wasn't
1897       // allocated before this method call, so it would be "reg".
1898       // If parameter is small enough to be saved in range [reg, r4), then
1899       // the end (first after last) register would be reg + param-size-in-regs,
1900       // else parameter would be splitted between registers and stack,
1901       // end register would be r4 in this case.
1902       unsigned ByValRegBegin = reg;
1903       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1904       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1905       // Note, first register is allocated in the beginning of function already,
1906       // allocate remained amount of registers we need.
1907       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1908         State->AllocateReg(GPRArgRegs, 4);
1909       // A byval parameter that is split between registers and memory needs its
1910       // size truncated here.
1911       // In the case where the entire structure fits in registers, we set the
1912       // size in memory to zero.
1913       if (size < excess)
1914         size = 0;
1915       else
1916         size -= excess;
1917     }
1918   }
1919 }
1920
1921 /// MatchingStackOffset - Return true if the given stack call argument is
1922 /// already available in the same position (relatively) of the caller's
1923 /// incoming argument stack.
1924 static
1925 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1926                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1927                          const TargetInstrInfo *TII) {
1928   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1929   int FI = INT_MAX;
1930   if (Arg.getOpcode() == ISD::CopyFromReg) {
1931     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1932     if (!TargetRegisterInfo::isVirtualRegister(VR))
1933       return false;
1934     MachineInstr *Def = MRI->getVRegDef(VR);
1935     if (!Def)
1936       return false;
1937     if (!Flags.isByVal()) {
1938       if (!TII->isLoadFromStackSlot(Def, FI))
1939         return false;
1940     } else {
1941       return false;
1942     }
1943   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1944     if (Flags.isByVal())
1945       // ByVal argument is passed in as a pointer but it's now being
1946       // dereferenced. e.g.
1947       // define @foo(%struct.X* %A) {
1948       //   tail call @bar(%struct.X* byval %A)
1949       // }
1950       return false;
1951     SDValue Ptr = Ld->getBasePtr();
1952     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1953     if (!FINode)
1954       return false;
1955     FI = FINode->getIndex();
1956   } else
1957     return false;
1958
1959   assert(FI != INT_MAX);
1960   if (!MFI->isFixedObjectIndex(FI))
1961     return false;
1962   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1963 }
1964
1965 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1966 /// for tail call optimization. Targets which want to do tail call
1967 /// optimization should implement this function.
1968 bool
1969 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1970                                                      CallingConv::ID CalleeCC,
1971                                                      bool isVarArg,
1972                                                      bool isCalleeStructRet,
1973                                                      bool isCallerStructRet,
1974                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1975                                     const SmallVectorImpl<SDValue> &OutVals,
1976                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1977                                                      SelectionDAG& DAG) const {
1978   const Function *CallerF = DAG.getMachineFunction().getFunction();
1979   CallingConv::ID CallerCC = CallerF->getCallingConv();
1980   bool CCMatch = CallerCC == CalleeCC;
1981
1982   // Look for obvious safe cases to perform tail call optimization that do not
1983   // require ABI changes. This is what gcc calls sibcall.
1984
1985   // Do not sibcall optimize vararg calls unless the call site is not passing
1986   // any arguments.
1987   if (isVarArg && !Outs.empty())
1988     return false;
1989
1990   // Exception-handling functions need a special set of instructions to indicate
1991   // a return to the hardware. Tail-calling another function would probably
1992   // break this.
1993   if (CallerF->hasFnAttribute("interrupt"))
1994     return false;
1995
1996   // Also avoid sibcall optimization if either caller or callee uses struct
1997   // return semantics.
1998   if (isCalleeStructRet || isCallerStructRet)
1999     return false;
2000
2001   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2002   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2003   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2004   // support in the assembler and linker to be used. This would need to be
2005   // fixed to fully support tail calls in Thumb1.
2006   //
2007   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2008   // LR.  This means if we need to reload LR, it takes an extra instructions,
2009   // which outweighs the value of the tail call; but here we don't know yet
2010   // whether LR is going to be used.  Probably the right approach is to
2011   // generate the tail call here and turn it back into CALL/RET in
2012   // emitEpilogue if LR is used.
2013
2014   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2015   // but we need to make sure there are enough registers; the only valid
2016   // registers are the 4 used for parameters.  We don't currently do this
2017   // case.
2018   if (Subtarget->isThumb1Only())
2019     return false;
2020
2021   // Externally-defined functions with weak linkage should not be
2022   // tail-called on ARM when the OS does not support dynamic
2023   // pre-emption of symbols, as the AAELF spec requires normal calls
2024   // to undefined weak functions to be replaced with a NOP or jump to the
2025   // next instruction. The behaviour of branch instructions in this
2026   // situation (as used for tail calls) is implementation-defined, so we
2027   // cannot rely on the linker replacing the tail call with a return.
2028   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2029     const GlobalValue *GV = G->getGlobal();
2030     if (GV->hasExternalWeakLinkage())
2031       return false;
2032   }
2033
2034   // If the calling conventions do not match, then we'd better make sure the
2035   // results are returned in the same way as what the caller expects.
2036   if (!CCMatch) {
2037     SmallVector<CCValAssign, 16> RVLocs1;
2038     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2039                        *DAG.getContext(), Call);
2040     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2041
2042     SmallVector<CCValAssign, 16> RVLocs2;
2043     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2044                        *DAG.getContext(), Call);
2045     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2046
2047     if (RVLocs1.size() != RVLocs2.size())
2048       return false;
2049     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2050       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2051         return false;
2052       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2053         return false;
2054       if (RVLocs1[i].isRegLoc()) {
2055         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2056           return false;
2057       } else {
2058         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2059           return false;
2060       }
2061     }
2062   }
2063
2064   // If Caller's vararg or byval argument has been split between registers and
2065   // stack, do not perform tail call, since part of the argument is in caller's
2066   // local frame.
2067   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2068                                       getInfo<ARMFunctionInfo>();
2069   if (AFI_Caller->getArgRegsSaveSize())
2070     return false;
2071
2072   // If the callee takes no arguments then go on to check the results of the
2073   // call.
2074   if (!Outs.empty()) {
2075     // Check if stack adjustment is needed. For now, do not do this if any
2076     // argument is passed on the stack.
2077     SmallVector<CCValAssign, 16> ArgLocs;
2078     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2079                       *DAG.getContext(), Call);
2080     CCInfo.AnalyzeCallOperands(Outs,
2081                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2082     if (CCInfo.getNextStackOffset()) {
2083       MachineFunction &MF = DAG.getMachineFunction();
2084
2085       // Check if the arguments are already laid out in the right way as
2086       // the caller's fixed stack objects.
2087       MachineFrameInfo *MFI = MF.getFrameInfo();
2088       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2089       const TargetInstrInfo *TII =
2090           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2091       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2092            i != e;
2093            ++i, ++realArgIdx) {
2094         CCValAssign &VA = ArgLocs[i];
2095         EVT RegVT = VA.getLocVT();
2096         SDValue Arg = OutVals[realArgIdx];
2097         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2098         if (VA.getLocInfo() == CCValAssign::Indirect)
2099           return false;
2100         if (VA.needsCustom()) {
2101           // f64 and vector types are split into multiple registers or
2102           // register/stack-slot combinations.  The types will not match
2103           // the registers; give up on memory f64 refs until we figure
2104           // out what to do about this.
2105           if (!VA.isRegLoc())
2106             return false;
2107           if (!ArgLocs[++i].isRegLoc())
2108             return false;
2109           if (RegVT == MVT::v2f64) {
2110             if (!ArgLocs[++i].isRegLoc())
2111               return false;
2112             if (!ArgLocs[++i].isRegLoc())
2113               return false;
2114           }
2115         } else if (!VA.isRegLoc()) {
2116           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2117                                    MFI, MRI, TII))
2118             return false;
2119         }
2120       }
2121     }
2122   }
2123
2124   return true;
2125 }
2126
2127 bool
2128 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2129                                   MachineFunction &MF, bool isVarArg,
2130                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2131                                   LLVMContext &Context) const {
2132   SmallVector<CCValAssign, 16> RVLocs;
2133   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2134   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2135                                                     isVarArg));
2136 }
2137
2138 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2139                                     SDLoc DL, SelectionDAG &DAG) {
2140   const MachineFunction &MF = DAG.getMachineFunction();
2141   const Function *F = MF.getFunction();
2142
2143   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2144
2145   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2146   // version of the "preferred return address". These offsets affect the return
2147   // instruction if this is a return from PL1 without hypervisor extensions.
2148   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2149   //    SWI:     0      "subs pc, lr, #0"
2150   //    ABORT:   +4     "subs pc, lr, #4"
2151   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2152   // UNDEF varies depending on where the exception came from ARM or Thumb
2153   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2154
2155   int64_t LROffset;
2156   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2157       IntKind == "ABORT")
2158     LROffset = 4;
2159   else if (IntKind == "SWI" || IntKind == "UNDEF")
2160     LROffset = 0;
2161   else
2162     report_fatal_error("Unsupported interrupt attribute. If present, value "
2163                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2164
2165   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2166
2167   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2168 }
2169
2170 SDValue
2171 ARMTargetLowering::LowerReturn(SDValue Chain,
2172                                CallingConv::ID CallConv, bool isVarArg,
2173                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2174                                const SmallVectorImpl<SDValue> &OutVals,
2175                                SDLoc dl, SelectionDAG &DAG) const {
2176
2177   // CCValAssign - represent the assignment of the return value to a location.
2178   SmallVector<CCValAssign, 16> RVLocs;
2179
2180   // CCState - Info about the registers and stack slots.
2181   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2182                     *DAG.getContext(), Call);
2183
2184   // Analyze outgoing return values.
2185   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2186                                                isVarArg));
2187
2188   SDValue Flag;
2189   SmallVector<SDValue, 4> RetOps;
2190   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2191   bool isLittleEndian = Subtarget->isLittle();
2192
2193   MachineFunction &MF = DAG.getMachineFunction();
2194   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2195   AFI->setReturnRegsCount(RVLocs.size());
2196
2197   // Copy the result values into the output registers.
2198   for (unsigned i = 0, realRVLocIdx = 0;
2199        i != RVLocs.size();
2200        ++i, ++realRVLocIdx) {
2201     CCValAssign &VA = RVLocs[i];
2202     assert(VA.isRegLoc() && "Can only return in registers!");
2203
2204     SDValue Arg = OutVals[realRVLocIdx];
2205
2206     switch (VA.getLocInfo()) {
2207     default: llvm_unreachable("Unknown loc info!");
2208     case CCValAssign::Full: break;
2209     case CCValAssign::BCvt:
2210       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2211       break;
2212     }
2213
2214     if (VA.needsCustom()) {
2215       if (VA.getLocVT() == MVT::v2f64) {
2216         // Extract the first half and return it in two registers.
2217         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2218                                    DAG.getConstant(0, MVT::i32));
2219         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2220                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2221
2222         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2223                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2224                                  Flag);
2225         Flag = Chain.getValue(1);
2226         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2227         VA = RVLocs[++i]; // skip ahead to next loc
2228         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2229                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2230                                  Flag);
2231         Flag = Chain.getValue(1);
2232         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2233         VA = RVLocs[++i]; // skip ahead to next loc
2234
2235         // Extract the 2nd half and fall through to handle it as an f64 value.
2236         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2237                           DAG.getConstant(1, MVT::i32));
2238       }
2239       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2240       // available.
2241       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2242                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2243       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244                                fmrrd.getValue(isLittleEndian ? 0 : 1),
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       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2250                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2251                                Flag);
2252     } else
2253       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2254
2255     // Guarantee that all emitted copies are
2256     // stuck together, avoiding something bad.
2257     Flag = Chain.getValue(1);
2258     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2259   }
2260
2261   // Update chain and glue.
2262   RetOps[0] = Chain;
2263   if (Flag.getNode())
2264     RetOps.push_back(Flag);
2265
2266   // CPUs which aren't M-class use a special sequence to return from
2267   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2268   // though we use "subs pc, lr, #N").
2269   //
2270   // M-class CPUs actually use a normal return sequence with a special
2271   // (hardware-provided) value in LR, so the normal code path works.
2272   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2273       !Subtarget->isMClass()) {
2274     if (Subtarget->isThumb1Only())
2275       report_fatal_error("interrupt attribute is not supported in Thumb1");
2276     return LowerInterruptReturn(RetOps, dl, DAG);
2277   }
2278
2279   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2280 }
2281
2282 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2283   if (N->getNumValues() != 1)
2284     return false;
2285   if (!N->hasNUsesOfValue(1, 0))
2286     return false;
2287
2288   SDValue TCChain = Chain;
2289   SDNode *Copy = *N->use_begin();
2290   if (Copy->getOpcode() == ISD::CopyToReg) {
2291     // If the copy has a glue operand, we conservatively assume it isn't safe to
2292     // perform a tail call.
2293     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2294       return false;
2295     TCChain = Copy->getOperand(0);
2296   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2297     SDNode *VMov = Copy;
2298     // f64 returned in a pair of GPRs.
2299     SmallPtrSet<SDNode*, 2> Copies;
2300     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2301          UI != UE; ++UI) {
2302       if (UI->getOpcode() != ISD::CopyToReg)
2303         return false;
2304       Copies.insert(*UI);
2305     }
2306     if (Copies.size() > 2)
2307       return false;
2308
2309     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2310          UI != UE; ++UI) {
2311       SDValue UseChain = UI->getOperand(0);
2312       if (Copies.count(UseChain.getNode()))
2313         // Second CopyToReg
2314         Copy = *UI;
2315       else
2316         // First CopyToReg
2317         TCChain = UseChain;
2318     }
2319   } else if (Copy->getOpcode() == ISD::BITCAST) {
2320     // f32 returned in a single GPR.
2321     if (!Copy->hasOneUse())
2322       return false;
2323     Copy = *Copy->use_begin();
2324     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2325       return false;
2326     TCChain = Copy->getOperand(0);
2327   } else {
2328     return false;
2329   }
2330
2331   bool HasRet = false;
2332   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2333        UI != UE; ++UI) {
2334     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2335         UI->getOpcode() != ARMISD::INTRET_FLAG)
2336       return false;
2337     HasRet = true;
2338   }
2339
2340   if (!HasRet)
2341     return false;
2342
2343   Chain = TCChain;
2344   return true;
2345 }
2346
2347 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2348   if (!Subtarget->supportsTailCall())
2349     return false;
2350
2351   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2352     return false;
2353
2354   return !Subtarget->isThumb1Only();
2355 }
2356
2357 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2358 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2359 // one of the above mentioned nodes. It has to be wrapped because otherwise
2360 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2361 // be used to form addressing mode. These wrapped nodes will be selected
2362 // into MOVi.
2363 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2364   EVT PtrVT = Op.getValueType();
2365   // FIXME there is no actual debug info here
2366   SDLoc dl(Op);
2367   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2368   SDValue Res;
2369   if (CP->isMachineConstantPoolEntry())
2370     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2371                                     CP->getAlignment());
2372   else
2373     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2374                                     CP->getAlignment());
2375   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2376 }
2377
2378 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2379   return MachineJumpTableInfo::EK_Inline;
2380 }
2381
2382 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2383                                              SelectionDAG &DAG) const {
2384   MachineFunction &MF = DAG.getMachineFunction();
2385   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2386   unsigned ARMPCLabelIndex = 0;
2387   SDLoc DL(Op);
2388   EVT PtrVT = getPointerTy();
2389   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2390   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2391   SDValue CPAddr;
2392   if (RelocM == Reloc::Static) {
2393     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2394   } else {
2395     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2396     ARMPCLabelIndex = AFI->createPICLabelUId();
2397     ARMConstantPoolValue *CPV =
2398       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2399                                       ARMCP::CPBlockAddress, PCAdj);
2400     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2401   }
2402   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2403   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2404                                MachinePointerInfo::getConstantPool(),
2405                                false, false, false, 0);
2406   if (RelocM == Reloc::Static)
2407     return Result;
2408   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2409   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2410 }
2411
2412 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2413 SDValue
2414 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2415                                                  SelectionDAG &DAG) const {
2416   SDLoc dl(GA);
2417   EVT PtrVT = getPointerTy();
2418   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2419   MachineFunction &MF = DAG.getMachineFunction();
2420   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2421   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2422   ARMConstantPoolValue *CPV =
2423     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2424                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2425   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2426   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2427   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2428                          MachinePointerInfo::getConstantPool(),
2429                          false, false, false, 0);
2430   SDValue Chain = Argument.getValue(1);
2431
2432   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2433   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2434
2435   // call __tls_get_addr.
2436   ArgListTy Args;
2437   ArgListEntry Entry;
2438   Entry.Node = Argument;
2439   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2440   Args.push_back(Entry);
2441
2442   // FIXME: is there useful debug info available here?
2443   TargetLowering::CallLoweringInfo CLI(DAG);
2444   CLI.setDebugLoc(dl).setChain(Chain)
2445     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2446                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2447                0);
2448
2449   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2450   return CallResult.first;
2451 }
2452
2453 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2454 // "local exec" model.
2455 SDValue
2456 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2457                                         SelectionDAG &DAG,
2458                                         TLSModel::Model model) const {
2459   const GlobalValue *GV = GA->getGlobal();
2460   SDLoc dl(GA);
2461   SDValue Offset;
2462   SDValue Chain = DAG.getEntryNode();
2463   EVT PtrVT = getPointerTy();
2464   // Get the Thread Pointer
2465   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2466
2467   if (model == TLSModel::InitialExec) {
2468     MachineFunction &MF = DAG.getMachineFunction();
2469     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2470     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2471     // Initial exec model.
2472     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2473     ARMConstantPoolValue *CPV =
2474       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2475                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2476                                       true);
2477     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2478     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2479     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2480                          MachinePointerInfo::getConstantPool(),
2481                          false, false, false, 0);
2482     Chain = Offset.getValue(1);
2483
2484     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2485     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2486
2487     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2488                          MachinePointerInfo::getConstantPool(),
2489                          false, false, false, 0);
2490   } else {
2491     // local exec model
2492     assert(model == TLSModel::LocalExec);
2493     ARMConstantPoolValue *CPV =
2494       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2495     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2496     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2497     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2498                          MachinePointerInfo::getConstantPool(),
2499                          false, false, false, 0);
2500   }
2501
2502   // The address of the thread local variable is the add of the thread
2503   // pointer with the offset of the variable.
2504   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2505 }
2506
2507 SDValue
2508 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2509   // TODO: implement the "local dynamic" model
2510   assert(Subtarget->isTargetELF() &&
2511          "TLS not implemented for non-ELF targets");
2512   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2513
2514   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2515
2516   switch (model) {
2517     case TLSModel::GeneralDynamic:
2518     case TLSModel::LocalDynamic:
2519       return LowerToTLSGeneralDynamicModel(GA, DAG);
2520     case TLSModel::InitialExec:
2521     case TLSModel::LocalExec:
2522       return LowerToTLSExecModels(GA, DAG, model);
2523   }
2524   llvm_unreachable("bogus TLS model");
2525 }
2526
2527 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2528                                                  SelectionDAG &DAG) const {
2529   EVT PtrVT = getPointerTy();
2530   SDLoc dl(Op);
2531   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2532   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2533     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2534     ARMConstantPoolValue *CPV =
2535       ARMConstantPoolConstant::Create(GV,
2536                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2537     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2538     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2539     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2540                                  CPAddr,
2541                                  MachinePointerInfo::getConstantPool(),
2542                                  false, false, false, 0);
2543     SDValue Chain = Result.getValue(1);
2544     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2545     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2546     if (!UseGOTOFF)
2547       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2548                            MachinePointerInfo::getGOT(),
2549                            false, false, false, 0);
2550     return Result;
2551   }
2552
2553   // If we have T2 ops, we can materialize the address directly via movt/movw
2554   // pair. This is always cheaper.
2555   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2556     ++NumMovwMovt;
2557     // FIXME: Once remat is capable of dealing with instructions with register
2558     // operands, expand this into two nodes.
2559     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2560                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2561   } else {
2562     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2563     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2565                        MachinePointerInfo::getConstantPool(),
2566                        false, false, false, 0);
2567   }
2568 }
2569
2570 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2571                                                     SelectionDAG &DAG) const {
2572   EVT PtrVT = getPointerTy();
2573   SDLoc dl(Op);
2574   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2575   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2576
2577   if (Subtarget->useMovt(DAG.getMachineFunction()))
2578     ++NumMovwMovt;
2579
2580   // FIXME: Once remat is capable of dealing with instructions with register
2581   // operands, expand this into multiple nodes
2582   unsigned Wrapper =
2583       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2584
2585   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2586   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2587
2588   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2589     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2590                          MachinePointerInfo::getGOT(), false, false, false, 0);
2591   return Result;
2592 }
2593
2594 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2595                                                      SelectionDAG &DAG) const {
2596   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2597   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2598          "Windows on ARM expects to use movw/movt");
2599
2600   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2601   const ARMII::TOF TargetFlags =
2602     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2603   EVT PtrVT = getPointerTy();
2604   SDValue Result;
2605   SDLoc DL(Op);
2606
2607   ++NumMovwMovt;
2608
2609   // FIXME: Once remat is capable of dealing with instructions with register
2610   // operands, expand this into two nodes.
2611   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2612                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2613                                                   TargetFlags));
2614   if (GV->hasDLLImportStorageClass())
2615     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2616                          MachinePointerInfo::getGOT(), false, false, false, 0);
2617   return Result;
2618 }
2619
2620 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2621                                                     SelectionDAG &DAG) const {
2622   assert(Subtarget->isTargetELF() &&
2623          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2624   MachineFunction &MF = DAG.getMachineFunction();
2625   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2626   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2627   EVT PtrVT = getPointerTy();
2628   SDLoc dl(Op);
2629   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2630   ARMConstantPoolValue *CPV =
2631     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2632                                   ARMPCLabelIndex, PCAdj);
2633   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2634   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2635   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2636                                MachinePointerInfo::getConstantPool(),
2637                                false, false, false, 0);
2638   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2639   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2640 }
2641
2642 SDValue
2643 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2644   SDLoc dl(Op);
2645   SDValue Val = DAG.getConstant(0, MVT::i32);
2646   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2647                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2648                      Op.getOperand(1), Val);
2649 }
2650
2651 SDValue
2652 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2653   SDLoc dl(Op);
2654   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2655                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2656 }
2657
2658 SDValue
2659 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2660                                           const ARMSubtarget *Subtarget) const {
2661   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2662   SDLoc dl(Op);
2663   switch (IntNo) {
2664   default: return SDValue();    // Don't custom lower most intrinsics.
2665   case Intrinsic::arm_rbit: {
2666     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2667            "RBIT intrinsic must have i32 type!");
2668     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2669   }
2670   case Intrinsic::arm_thread_pointer: {
2671     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2672     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2673   }
2674   case Intrinsic::eh_sjlj_lsda: {
2675     MachineFunction &MF = DAG.getMachineFunction();
2676     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2677     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2678     EVT PtrVT = getPointerTy();
2679     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2680     SDValue CPAddr;
2681     unsigned PCAdj = (RelocM != Reloc::PIC_)
2682       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2683     ARMConstantPoolValue *CPV =
2684       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2685                                       ARMCP::CPLSDA, PCAdj);
2686     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2687     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2688     SDValue Result =
2689       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2690                   MachinePointerInfo::getConstantPool(),
2691                   false, false, false, 0);
2692
2693     if (RelocM == Reloc::PIC_) {
2694       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2695       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2696     }
2697     return Result;
2698   }
2699   case Intrinsic::arm_neon_vmulls:
2700   case Intrinsic::arm_neon_vmullu: {
2701     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2702       ? ARMISD::VMULLs : ARMISD::VMULLu;
2703     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2704                        Op.getOperand(1), Op.getOperand(2));
2705   }
2706   }
2707 }
2708
2709 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2710                                  const ARMSubtarget *Subtarget) {
2711   // FIXME: handle "fence singlethread" more efficiently.
2712   SDLoc dl(Op);
2713   if (!Subtarget->hasDataBarrier()) {
2714     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2715     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2716     // here.
2717     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2718            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2719     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2720                        DAG.getConstant(0, MVT::i32));
2721   }
2722
2723   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2724   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2725   unsigned Domain = ARM_MB::ISH;
2726   if (Subtarget->isMClass()) {
2727     // Only a full system barrier exists in the M-class architectures.
2728     Domain = ARM_MB::SY;
2729   } else if (Subtarget->isSwift() && Ord == Release) {
2730     // Swift happens to implement ISHST barriers in a way that's compatible with
2731     // Release semantics but weaker than ISH so we'd be fools not to use
2732     // it. Beware: other processors probably don't!
2733     Domain = ARM_MB::ISHST;
2734   }
2735
2736   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2737                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2738                      DAG.getConstant(Domain, MVT::i32));
2739 }
2740
2741 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2742                              const ARMSubtarget *Subtarget) {
2743   // ARM pre v5TE and Thumb1 does not have preload instructions.
2744   if (!(Subtarget->isThumb2() ||
2745         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2746     // Just preserve the chain.
2747     return Op.getOperand(0);
2748
2749   SDLoc dl(Op);
2750   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2751   if (!isRead &&
2752       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2753     // ARMv7 with MP extension has PLDW.
2754     return Op.getOperand(0);
2755
2756   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2757   if (Subtarget->isThumb()) {
2758     // Invert the bits.
2759     isRead = ~isRead & 1;
2760     isData = ~isData & 1;
2761   }
2762
2763   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2764                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2765                      DAG.getConstant(isData, MVT::i32));
2766 }
2767
2768 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2769   MachineFunction &MF = DAG.getMachineFunction();
2770   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2771
2772   // vastart just stores the address of the VarArgsFrameIndex slot into the
2773   // memory location argument.
2774   SDLoc dl(Op);
2775   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2776   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2777   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2778   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2779                       MachinePointerInfo(SV), false, false, 0);
2780 }
2781
2782 SDValue
2783 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2784                                         SDValue &Root, SelectionDAG &DAG,
2785                                         SDLoc dl) const {
2786   MachineFunction &MF = DAG.getMachineFunction();
2787   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2788
2789   const TargetRegisterClass *RC;
2790   if (AFI->isThumb1OnlyFunction())
2791     RC = &ARM::tGPRRegClass;
2792   else
2793     RC = &ARM::GPRRegClass;
2794
2795   // Transform the arguments stored in physical registers into virtual ones.
2796   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2797   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2798
2799   SDValue ArgValue2;
2800   if (NextVA.isMemLoc()) {
2801     MachineFrameInfo *MFI = MF.getFrameInfo();
2802     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2803
2804     // Create load node to retrieve arguments from the stack.
2805     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2806     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2807                             MachinePointerInfo::getFixedStack(FI),
2808                             false, false, false, 0);
2809   } else {
2810     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2811     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2812   }
2813   if (!Subtarget->isLittle())
2814     std::swap (ArgValue, ArgValue2);
2815   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2816 }
2817
2818 void
2819 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2820                                   unsigned InRegsParamRecordIdx,
2821                                   unsigned ArgSize,
2822                                   unsigned &ArgRegsSize,
2823                                   unsigned &ArgRegsSaveSize)
2824   const {
2825   unsigned NumGPRs;
2826   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2827     unsigned RBegin, REnd;
2828     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2829     NumGPRs = REnd - RBegin;
2830   } else {
2831     unsigned int firstUnalloced;
2832     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2833                                                 sizeof(GPRArgRegs) /
2834                                                 sizeof(GPRArgRegs[0]));
2835     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2836   }
2837
2838   unsigned Align = MF.getTarget()
2839                        .getSubtargetImpl()
2840                        ->getFrameLowering()
2841                        ->getStackAlignment();
2842   ArgRegsSize = NumGPRs * 4;
2843
2844   // If parameter is split between stack and GPRs...
2845   if (NumGPRs && Align > 4 &&
2846       (ArgRegsSize < ArgSize ||
2847         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2848     // Add padding for part of param recovered from GPRs.  For example,
2849     // if Align == 8, its last byte must be at address K*8 - 1.
2850     // We need to do it, since remained (stack) part of parameter has
2851     // stack alignment, and we need to "attach" "GPRs head" without gaps
2852     // to it:
2853     // Stack:
2854     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2855     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2856     //
2857     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2858     unsigned Padding =
2859         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2860     ArgRegsSaveSize = ArgRegsSize + Padding;
2861   } else
2862     // We don't need to extend regs save size for byval parameters if they
2863     // are passed via GPRs only.
2864     ArgRegsSaveSize = ArgRegsSize;
2865 }
2866
2867 // The remaining GPRs hold either the beginning of variable-argument
2868 // data, or the beginning of an aggregate passed by value (usually
2869 // byval).  Either way, we allocate stack slots adjacent to the data
2870 // provided by our caller, and store the unallocated registers there.
2871 // If this is a variadic function, the va_list pointer will begin with
2872 // these values; otherwise, this reassembles a (byval) structure that
2873 // was split between registers and memory.
2874 // Return: The frame index registers were stored into.
2875 int
2876 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2877                                   SDLoc dl, SDValue &Chain,
2878                                   const Value *OrigArg,
2879                                   unsigned InRegsParamRecordIdx,
2880                                   unsigned OffsetFromOrigArg,
2881                                   unsigned ArgOffset,
2882                                   unsigned ArgSize,
2883                                   bool ForceMutable,
2884                                   unsigned ByValStoreOffset,
2885                                   unsigned TotalArgRegsSaveSize) const {
2886
2887   // Currently, two use-cases possible:
2888   // Case #1. Non-var-args function, and we meet first byval parameter.
2889   //          Setup first unallocated register as first byval register;
2890   //          eat all remained registers
2891   //          (these two actions are performed by HandleByVal method).
2892   //          Then, here, we initialize stack frame with
2893   //          "store-reg" instructions.
2894   // Case #2. Var-args function, that doesn't contain byval parameters.
2895   //          The same: eat all remained unallocated registers,
2896   //          initialize stack frame.
2897
2898   MachineFunction &MF = DAG.getMachineFunction();
2899   MachineFrameInfo *MFI = MF.getFrameInfo();
2900   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2901   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2902   unsigned RBegin, REnd;
2903   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2904     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2905     firstRegToSaveIndex = RBegin - ARM::R0;
2906     lastRegToSaveIndex = REnd - ARM::R0;
2907   } else {
2908     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2909       (GPRArgRegs, array_lengthof(GPRArgRegs));
2910     lastRegToSaveIndex = 4;
2911   }
2912
2913   unsigned ArgRegsSize, ArgRegsSaveSize;
2914   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2915                  ArgRegsSize, ArgRegsSaveSize);
2916
2917   // Store any by-val regs to their spots on the stack so that they may be
2918   // loaded by deferencing the result of formal parameter pointer or va_next.
2919   // Note: once stack area for byval/varargs registers
2920   // was initialized, it can't be initialized again.
2921   if (ArgRegsSaveSize) {
2922     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2923
2924     if (Padding) {
2925       assert(AFI->getStoredByValParamsPadding() == 0 &&
2926              "The only parameter may be padded.");
2927       AFI->setStoredByValParamsPadding(Padding);
2928     }
2929
2930     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2931                                             Padding +
2932                                               ByValStoreOffset -
2933                                               (int64_t)TotalArgRegsSaveSize,
2934                                             false);
2935     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2936     if (Padding) {
2937        MFI->CreateFixedObject(Padding,
2938                               ArgOffset + ByValStoreOffset -
2939                                 (int64_t)ArgRegsSaveSize,
2940                               false);
2941     }
2942
2943     SmallVector<SDValue, 4> MemOps;
2944     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2945          ++firstRegToSaveIndex, ++i) {
2946       const TargetRegisterClass *RC;
2947       if (AFI->isThumb1OnlyFunction())
2948         RC = &ARM::tGPRRegClass;
2949       else
2950         RC = &ARM::GPRRegClass;
2951
2952       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2953       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2954       SDValue Store =
2955         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2956                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2957                      false, false, 0);
2958       MemOps.push_back(Store);
2959       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2960                         DAG.getConstant(4, getPointerTy()));
2961     }
2962
2963     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2964
2965     if (!MemOps.empty())
2966       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2967     return FrameIndex;
2968   } else {
2969     if (ArgSize == 0) {
2970       // We cannot allocate a zero-byte object for the first variadic argument,
2971       // so just make up a size.
2972       ArgSize = 4;
2973     }
2974     // This will point to the next argument passed via stack.
2975     return MFI->CreateFixedObject(
2976       ArgSize, ArgOffset, !ForceMutable);
2977   }
2978 }
2979
2980 // Setup stack frame, the va_list pointer will start from.
2981 void
2982 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2983                                         SDLoc dl, SDValue &Chain,
2984                                         unsigned ArgOffset,
2985                                         unsigned TotalArgRegsSaveSize,
2986                                         bool ForceMutable) const {
2987   MachineFunction &MF = DAG.getMachineFunction();
2988   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2989
2990   // Try to store any remaining integer argument regs
2991   // to their spots on the stack so that they may be loaded by deferencing
2992   // the result of va_next.
2993   // If there is no regs to be stored, just point address after last
2994   // argument passed via stack.
2995   int FrameIndex =
2996     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2997                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2998                    0, TotalArgRegsSaveSize);
2999
3000   AFI->setVarArgsFrameIndex(FrameIndex);
3001 }
3002
3003 SDValue
3004 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3005                                         CallingConv::ID CallConv, bool isVarArg,
3006                                         const SmallVectorImpl<ISD::InputArg>
3007                                           &Ins,
3008                                         SDLoc dl, SelectionDAG &DAG,
3009                                         SmallVectorImpl<SDValue> &InVals)
3010                                           const {
3011   MachineFunction &MF = DAG.getMachineFunction();
3012   MachineFrameInfo *MFI = MF.getFrameInfo();
3013
3014   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3015
3016   // Assign locations to all of the incoming arguments.
3017   SmallVector<CCValAssign, 16> ArgLocs;
3018   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3019                     *DAG.getContext(), Prologue);
3020   CCInfo.AnalyzeFormalArguments(Ins,
3021                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3022                                                   isVarArg));
3023
3024   SmallVector<SDValue, 16> ArgValues;
3025   int lastInsIndex = -1;
3026   SDValue ArgValue;
3027   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3028   unsigned CurArgIdx = 0;
3029
3030   // Initially ArgRegsSaveSize is zero.
3031   // Then we increase this value each time we meet byval parameter.
3032   // We also increase this value in case of varargs function.
3033   AFI->setArgRegsSaveSize(0);
3034
3035   unsigned ByValStoreOffset = 0;
3036   unsigned TotalArgRegsSaveSize = 0;
3037   unsigned ArgRegsSaveSizeMaxAlign = 4;
3038
3039   // Calculate the amount of stack space that we need to allocate to store
3040   // byval and variadic arguments that are passed in registers.
3041   // We need to know this before we allocate the first byval or variadic
3042   // argument, as they will be allocated a stack slot below the CFA (Canonical
3043   // Frame Address, the stack pointer at entry to the function).
3044   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3045     CCValAssign &VA = ArgLocs[i];
3046     if (VA.isMemLoc()) {
3047       int index = VA.getValNo();
3048       if (index != lastInsIndex) {
3049         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3050         if (Flags.isByVal()) {
3051           unsigned ExtraArgRegsSize;
3052           unsigned ExtraArgRegsSaveSize;
3053           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3054                          Flags.getByValSize(),
3055                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3056
3057           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3058           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3059               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3060           CCInfo.nextInRegsParam();
3061         }
3062         lastInsIndex = index;
3063       }
3064     }
3065   }
3066   CCInfo.rewindByValRegsInfo();
3067   lastInsIndex = -1;
3068   if (isVarArg && MFI->hasVAStart()) {
3069     unsigned ExtraArgRegsSize;
3070     unsigned ExtraArgRegsSaveSize;
3071     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3072                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3073     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3074   }
3075   // If the arg regs save area contains N-byte aligned values, the
3076   // bottom of it must be at least N-byte aligned.
3077   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3078   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3079
3080   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3081     CCValAssign &VA = ArgLocs[i];
3082     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3083     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3084     // Arguments stored in registers.
3085     if (VA.isRegLoc()) {
3086       EVT RegVT = VA.getLocVT();
3087
3088       if (VA.needsCustom()) {
3089         // f64 and vector types are split up into multiple registers or
3090         // combinations of registers and stack slots.
3091         if (VA.getLocVT() == MVT::v2f64) {
3092           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3093                                                    Chain, DAG, dl);
3094           VA = ArgLocs[++i]; // skip ahead to next loc
3095           SDValue ArgValue2;
3096           if (VA.isMemLoc()) {
3097             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3098             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3099             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3100                                     MachinePointerInfo::getFixedStack(FI),
3101                                     false, false, false, 0);
3102           } else {
3103             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3104                                              Chain, DAG, dl);
3105           }
3106           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3107           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3108                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3109           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3110                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3111         } else
3112           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3113
3114       } else {
3115         const TargetRegisterClass *RC;
3116
3117         if (RegVT == MVT::f32)
3118           RC = &ARM::SPRRegClass;
3119         else if (RegVT == MVT::f64)
3120           RC = &ARM::DPRRegClass;
3121         else if (RegVT == MVT::v2f64)
3122           RC = &ARM::QPRRegClass;
3123         else if (RegVT == MVT::i32)
3124           RC = AFI->isThumb1OnlyFunction() ?
3125             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3126             (const TargetRegisterClass*)&ARM::GPRRegClass;
3127         else
3128           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3129
3130         // Transform the arguments in physical registers into virtual ones.
3131         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3132         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3133       }
3134
3135       // If this is an 8 or 16-bit value, it is really passed promoted
3136       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3137       // truncate to the right size.
3138       switch (VA.getLocInfo()) {
3139       default: llvm_unreachable("Unknown loc info!");
3140       case CCValAssign::Full: break;
3141       case CCValAssign::BCvt:
3142         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3143         break;
3144       case CCValAssign::SExt:
3145         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3146                                DAG.getValueType(VA.getValVT()));
3147         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3148         break;
3149       case CCValAssign::ZExt:
3150         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3151                                DAG.getValueType(VA.getValVT()));
3152         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3153         break;
3154       }
3155
3156       InVals.push_back(ArgValue);
3157
3158     } else { // VA.isRegLoc()
3159
3160       // sanity check
3161       assert(VA.isMemLoc());
3162       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3163
3164       int index = ArgLocs[i].getValNo();
3165
3166       // Some Ins[] entries become multiple ArgLoc[] entries.
3167       // Process them only once.
3168       if (index != lastInsIndex)
3169         {
3170           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3171           // FIXME: For now, all byval parameter objects are marked mutable.
3172           // This can be changed with more analysis.
3173           // In case of tail call optimization mark all arguments mutable.
3174           // Since they could be overwritten by lowering of arguments in case of
3175           // a tail call.
3176           if (Flags.isByVal()) {
3177             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3178
3179             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3180             int FrameIndex = StoreByValRegs(
3181                 CCInfo, DAG, dl, Chain, CurOrigArg,
3182                 CurByValIndex,
3183                 Ins[VA.getValNo()].PartOffset,
3184                 VA.getLocMemOffset(),
3185                 Flags.getByValSize(),
3186                 true /*force mutable frames*/,
3187                 ByValStoreOffset,
3188                 TotalArgRegsSaveSize);
3189             ByValStoreOffset += Flags.getByValSize();
3190             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3191             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3192             CCInfo.nextInRegsParam();
3193           } else {
3194             unsigned FIOffset = VA.getLocMemOffset();
3195             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3196                                             FIOffset, true);
3197
3198             // Create load nodes to retrieve arguments from the stack.
3199             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3200             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3201                                          MachinePointerInfo::getFixedStack(FI),
3202                                          false, false, false, 0));
3203           }
3204           lastInsIndex = index;
3205         }
3206     }
3207   }
3208
3209   // varargs
3210   if (isVarArg && MFI->hasVAStart())
3211     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3212                          CCInfo.getNextStackOffset(),
3213                          TotalArgRegsSaveSize);
3214
3215   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3216
3217   return Chain;
3218 }
3219
3220 /// isFloatingPointZero - Return true if this is +0.0.
3221 static bool isFloatingPointZero(SDValue Op) {
3222   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3223     return CFP->getValueAPF().isPosZero();
3224   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3225     // Maybe this has already been legalized into the constant pool?
3226     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3227       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3228       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3229         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3230           return CFP->getValueAPF().isPosZero();
3231     }
3232   }
3233   return false;
3234 }
3235
3236 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3237 /// the given operands.
3238 SDValue
3239 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3240                              SDValue &ARMcc, SelectionDAG &DAG,
3241                              SDLoc dl) const {
3242   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3243     unsigned C = RHSC->getZExtValue();
3244     if (!isLegalICmpImmediate(C)) {
3245       // Constant does not fit, try adjusting it by one?
3246       switch (CC) {
3247       default: break;
3248       case ISD::SETLT:
3249       case ISD::SETGE:
3250         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3251           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3252           RHS = DAG.getConstant(C-1, MVT::i32);
3253         }
3254         break;
3255       case ISD::SETULT:
3256       case ISD::SETUGE:
3257         if (C != 0 && isLegalICmpImmediate(C-1)) {
3258           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3259           RHS = DAG.getConstant(C-1, MVT::i32);
3260         }
3261         break;
3262       case ISD::SETLE:
3263       case ISD::SETGT:
3264         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3265           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3266           RHS = DAG.getConstant(C+1, MVT::i32);
3267         }
3268         break;
3269       case ISD::SETULE:
3270       case ISD::SETUGT:
3271         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3272           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3273           RHS = DAG.getConstant(C+1, MVT::i32);
3274         }
3275         break;
3276       }
3277     }
3278   }
3279
3280   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3281   ARMISD::NodeType CompareType;
3282   switch (CondCode) {
3283   default:
3284     CompareType = ARMISD::CMP;
3285     break;
3286   case ARMCC::EQ:
3287   case ARMCC::NE:
3288     // Uses only Z Flag
3289     CompareType = ARMISD::CMPZ;
3290     break;
3291   }
3292   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3293   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3294 }
3295
3296 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3297 SDValue
3298 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3299                              SDLoc dl) const {
3300   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3301   SDValue Cmp;
3302   if (!isFloatingPointZero(RHS))
3303     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3304   else
3305     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3306   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3307 }
3308
3309 /// duplicateCmp - Glue values can have only one use, so this function
3310 /// duplicates a comparison node.
3311 SDValue
3312 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3313   unsigned Opc = Cmp.getOpcode();
3314   SDLoc DL(Cmp);
3315   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3316     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3317
3318   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3319   Cmp = Cmp.getOperand(0);
3320   Opc = Cmp.getOpcode();
3321   if (Opc == ARMISD::CMPFP)
3322     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3323   else {
3324     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3325     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3326   }
3327   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3328 }
3329
3330 std::pair<SDValue, SDValue>
3331 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3332                                  SDValue &ARMcc) const {
3333   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3334
3335   SDValue Value, OverflowCmp;
3336   SDValue LHS = Op.getOperand(0);
3337   SDValue RHS = Op.getOperand(1);
3338
3339
3340   // FIXME: We are currently always generating CMPs because we don't support
3341   // generating CMN through the backend. This is not as good as the natural
3342   // CMP case because it causes a register dependency and cannot be folded
3343   // later.
3344
3345   switch (Op.getOpcode()) {
3346   default:
3347     llvm_unreachable("Unknown overflow instruction!");
3348   case ISD::SADDO:
3349     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3350     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3351     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3352     break;
3353   case ISD::UADDO:
3354     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3355     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3356     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3357     break;
3358   case ISD::SSUBO:
3359     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3360     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3361     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3362     break;
3363   case ISD::USUBO:
3364     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3365     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3366     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3367     break;
3368   } // switch (...)
3369
3370   return std::make_pair(Value, OverflowCmp);
3371 }
3372
3373
3374 SDValue
3375 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3376   // Let legalize expand this if it isn't a legal type yet.
3377   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3378     return SDValue();
3379
3380   SDValue Value, OverflowCmp;
3381   SDValue ARMcc;
3382   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3383   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3384   // We use 0 and 1 as false and true values.
3385   SDValue TVal = DAG.getConstant(1, MVT::i32);
3386   SDValue FVal = DAG.getConstant(0, MVT::i32);
3387   EVT VT = Op.getValueType();
3388
3389   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3390                                  ARMcc, CCR, OverflowCmp);
3391
3392   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3393   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3394 }
3395
3396
3397 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3398   SDValue Cond = Op.getOperand(0);
3399   SDValue SelectTrue = Op.getOperand(1);
3400   SDValue SelectFalse = Op.getOperand(2);
3401   SDLoc dl(Op);
3402   unsigned Opc = Cond.getOpcode();
3403
3404   if (Cond.getResNo() == 1 &&
3405       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3406        Opc == ISD::USUBO)) {
3407     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3408       return SDValue();
3409
3410     SDValue Value, OverflowCmp;
3411     SDValue ARMcc;
3412     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3413     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3414     EVT VT = Op.getValueType();
3415
3416     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3417                    OverflowCmp, DAG);
3418   }
3419
3420   // Convert:
3421   //
3422   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3423   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3424   //
3425   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3426     const ConstantSDNode *CMOVTrue =
3427       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3428     const ConstantSDNode *CMOVFalse =
3429       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3430
3431     if (CMOVTrue && CMOVFalse) {
3432       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3433       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3434
3435       SDValue True;
3436       SDValue False;
3437       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3438         True = SelectTrue;
3439         False = SelectFalse;
3440       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3441         True = SelectFalse;
3442         False = SelectTrue;
3443       }
3444
3445       if (True.getNode() && False.getNode()) {
3446         EVT VT = Op.getValueType();
3447         SDValue ARMcc = Cond.getOperand(2);
3448         SDValue CCR = Cond.getOperand(3);
3449         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3450         assert(True.getValueType() == VT);
3451         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3452       }
3453     }
3454   }
3455
3456   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3457   // undefined bits before doing a full-word comparison with zero.
3458   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3459                      DAG.getConstant(1, Cond.getValueType()));
3460
3461   return DAG.getSelectCC(dl, Cond,
3462                          DAG.getConstant(0, Cond.getValueType()),
3463                          SelectTrue, SelectFalse, ISD::SETNE);
3464 }
3465
3466 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3467   if (CC == ISD::SETNE)
3468     return ISD::SETEQ;
3469   return ISD::getSetCCInverse(CC, true);
3470 }
3471
3472 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3473                                  bool &swpCmpOps, bool &swpVselOps) {
3474   // Start by selecting the GE condition code for opcodes that return true for
3475   // 'equality'
3476   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3477       CC == ISD::SETULE)
3478     CondCode = ARMCC::GE;
3479
3480   // and GT for opcodes that return false for 'equality'.
3481   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3482            CC == ISD::SETULT)
3483     CondCode = ARMCC::GT;
3484
3485   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3486   // to swap the compare operands.
3487   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3488       CC == ISD::SETULT)
3489     swpCmpOps = true;
3490
3491   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3492   // If we have an unordered opcode, we need to swap the operands to the VSEL
3493   // instruction (effectively negating the condition).
3494   //
3495   // This also has the effect of swapping which one of 'less' or 'greater'
3496   // returns true, so we also swap the compare operands. It also switches
3497   // whether we return true for 'equality', so we compensate by picking the
3498   // opposite condition code to our original choice.
3499   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3500       CC == ISD::SETUGT) {
3501     swpCmpOps = !swpCmpOps;
3502     swpVselOps = !swpVselOps;
3503     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3504   }
3505
3506   // 'ordered' is 'anything but unordered', so use the VS condition code and
3507   // swap the VSEL operands.
3508   if (CC == ISD::SETO) {
3509     CondCode = ARMCC::VS;
3510     swpVselOps = true;
3511   }
3512
3513   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3514   // code and swap the VSEL operands.
3515   if (CC == ISD::SETUNE) {
3516     CondCode = ARMCC::EQ;
3517     swpVselOps = true;
3518   }
3519 }
3520
3521 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3522                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3523                                    SDValue Cmp, SelectionDAG &DAG) const {
3524   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3525     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3526                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3527     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3528                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3529
3530     SDValue TrueLow = TrueVal.getValue(0);
3531     SDValue TrueHigh = TrueVal.getValue(1);
3532     SDValue FalseLow = FalseVal.getValue(0);
3533     SDValue FalseHigh = FalseVal.getValue(1);
3534
3535     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3536                               ARMcc, CCR, Cmp);
3537     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3538                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3539
3540     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3541   } else {
3542     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3543                        Cmp);
3544   }
3545 }
3546
3547 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3548   EVT VT = Op.getValueType();
3549   SDValue LHS = Op.getOperand(0);
3550   SDValue RHS = Op.getOperand(1);
3551   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3552   SDValue TrueVal = Op.getOperand(2);
3553   SDValue FalseVal = Op.getOperand(3);
3554   SDLoc dl(Op);
3555
3556   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3557     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3558                                                     dl);
3559
3560     // If softenSetCCOperands only returned one value, we should compare it to
3561     // zero.
3562     if (!RHS.getNode()) {
3563       RHS = DAG.getConstant(0, LHS.getValueType());
3564       CC = ISD::SETNE;
3565     }
3566   }
3567
3568   if (LHS.getValueType() == MVT::i32) {
3569     // Try to generate VSEL on ARMv8.
3570     // The VSEL instruction can't use all the usual ARM condition
3571     // codes: it only has two bits to select the condition code, so it's
3572     // constrained to use only GE, GT, VS and EQ.
3573     //
3574     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3575     // swap the operands of the previous compare instruction (effectively
3576     // inverting the compare condition, swapping 'less' and 'greater') and
3577     // sometimes need to swap the operands to the VSEL (which inverts the
3578     // condition in the sense of firing whenever the previous condition didn't)
3579     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3580                                       TrueVal.getValueType() == MVT::f64)) {
3581       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3582       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3583           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3584         CC = getInverseCCForVSEL(CC);
3585         std::swap(TrueVal, FalseVal);
3586       }
3587     }
3588
3589     SDValue ARMcc;
3590     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3591     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3592     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3593   }
3594
3595   ARMCC::CondCodes CondCode, CondCode2;
3596   FPCCToARMCC(CC, CondCode, CondCode2);
3597
3598   // Try to generate VSEL on ARMv8.
3599   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3600                                     TrueVal.getValueType() == MVT::f64)) {
3601     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3602     // same operands, as follows:
3603     //   c = fcmp [ogt, olt, ugt, ult] a, b
3604     //   select c, a, b
3605     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3606     // handled differently than the original code sequence.
3607     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3608         RHS == FalseVal) {
3609       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3610         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3611       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3612         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3613     }
3614
3615     bool swpCmpOps = false;
3616     bool swpVselOps = false;
3617     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3618
3619     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3620         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3621       if (swpCmpOps)
3622         std::swap(LHS, RHS);
3623       if (swpVselOps)
3624         std::swap(TrueVal, FalseVal);
3625     }
3626   }
3627
3628   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3629   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3630   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3631   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3632   if (CondCode2 != ARMCC::AL) {
3633     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3634     // FIXME: Needs another CMP because flag can have but one use.
3635     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3636     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3637   }
3638   return Result;
3639 }
3640
3641 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3642 /// to morph to an integer compare sequence.
3643 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3644                            const ARMSubtarget *Subtarget) {
3645   SDNode *N = Op.getNode();
3646   if (!N->hasOneUse())
3647     // Otherwise it requires moving the value from fp to integer registers.
3648     return false;
3649   if (!N->getNumValues())
3650     return false;
3651   EVT VT = Op.getValueType();
3652   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3653     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3654     // vmrs are very slow, e.g. cortex-a8.
3655     return false;
3656
3657   if (isFloatingPointZero(Op)) {
3658     SeenZero = true;
3659     return true;
3660   }
3661   return ISD::isNormalLoad(N);
3662 }
3663
3664 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3665   if (isFloatingPointZero(Op))
3666     return DAG.getConstant(0, MVT::i32);
3667
3668   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3669     return DAG.getLoad(MVT::i32, SDLoc(Op),
3670                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3671                        Ld->isVolatile(), Ld->isNonTemporal(),
3672                        Ld->isInvariant(), Ld->getAlignment());
3673
3674   llvm_unreachable("Unknown VFP cmp argument!");
3675 }
3676
3677 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3678                            SDValue &RetVal1, SDValue &RetVal2) {
3679   if (isFloatingPointZero(Op)) {
3680     RetVal1 = DAG.getConstant(0, MVT::i32);
3681     RetVal2 = DAG.getConstant(0, MVT::i32);
3682     return;
3683   }
3684
3685   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3686     SDValue Ptr = Ld->getBasePtr();
3687     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3688                           Ld->getChain(), Ptr,
3689                           Ld->getPointerInfo(),
3690                           Ld->isVolatile(), Ld->isNonTemporal(),
3691                           Ld->isInvariant(), Ld->getAlignment());
3692
3693     EVT PtrType = Ptr.getValueType();
3694     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3695     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3696                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3697     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3698                           Ld->getChain(), NewPtr,
3699                           Ld->getPointerInfo().getWithOffset(4),
3700                           Ld->isVolatile(), Ld->isNonTemporal(),
3701                           Ld->isInvariant(), NewAlign);
3702     return;
3703   }
3704
3705   llvm_unreachable("Unknown VFP cmp argument!");
3706 }
3707
3708 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3709 /// f32 and even f64 comparisons to integer ones.
3710 SDValue
3711 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3712   SDValue Chain = Op.getOperand(0);
3713   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3714   SDValue LHS = Op.getOperand(2);
3715   SDValue RHS = Op.getOperand(3);
3716   SDValue Dest = Op.getOperand(4);
3717   SDLoc dl(Op);
3718
3719   bool LHSSeenZero = false;
3720   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3721   bool RHSSeenZero = false;
3722   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3723   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3724     // If unsafe fp math optimization is enabled and there are no other uses of
3725     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3726     // to an integer comparison.
3727     if (CC == ISD::SETOEQ)
3728       CC = ISD::SETEQ;
3729     else if (CC == ISD::SETUNE)
3730       CC = ISD::SETNE;
3731
3732     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3733     SDValue ARMcc;
3734     if (LHS.getValueType() == MVT::f32) {
3735       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3736                         bitcastf32Toi32(LHS, DAG), Mask);
3737       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3738                         bitcastf32Toi32(RHS, DAG), Mask);
3739       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3740       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3741       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3742                          Chain, Dest, ARMcc, CCR, Cmp);
3743     }
3744
3745     SDValue LHS1, LHS2;
3746     SDValue RHS1, RHS2;
3747     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3748     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3749     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3750     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3751     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3752     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3753     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3754     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3755     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3756   }
3757
3758   return SDValue();
3759 }
3760
3761 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3762   SDValue Chain = Op.getOperand(0);
3763   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3764   SDValue LHS = Op.getOperand(2);
3765   SDValue RHS = Op.getOperand(3);
3766   SDValue Dest = Op.getOperand(4);
3767   SDLoc dl(Op);
3768
3769   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3770     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3771                                                     dl);
3772
3773     // If softenSetCCOperands only returned one value, we should compare it to
3774     // zero.
3775     if (!RHS.getNode()) {
3776       RHS = DAG.getConstant(0, LHS.getValueType());
3777       CC = ISD::SETNE;
3778     }
3779   }
3780
3781   if (LHS.getValueType() == MVT::i32) {
3782     SDValue ARMcc;
3783     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3784     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3785     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3786                        Chain, Dest, ARMcc, CCR, Cmp);
3787   }
3788
3789   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3790
3791   if (getTargetMachine().Options.UnsafeFPMath &&
3792       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3793        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3794     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3795     if (Result.getNode())
3796       return Result;
3797   }
3798
3799   ARMCC::CondCodes CondCode, CondCode2;
3800   FPCCToARMCC(CC, CondCode, CondCode2);
3801
3802   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3803   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3804   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3805   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3806   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3807   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3808   if (CondCode2 != ARMCC::AL) {
3809     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3810     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3811     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3812   }
3813   return Res;
3814 }
3815
3816 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3817   SDValue Chain = Op.getOperand(0);
3818   SDValue Table = Op.getOperand(1);
3819   SDValue Index = Op.getOperand(2);
3820   SDLoc dl(Op);
3821
3822   EVT PTy = getPointerTy();
3823   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3824   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3825   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3826   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3827   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3828   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3829   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3830   if (Subtarget->isThumb2()) {
3831     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3832     // which does another jump to the destination. This also makes it easier
3833     // to translate it to TBB / TBH later.
3834     // FIXME: This might not work if the function is extremely large.
3835     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3836                        Addr, Op.getOperand(2), JTI, UId);
3837   }
3838   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3839     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3840                        MachinePointerInfo::getJumpTable(),
3841                        false, false, false, 0);
3842     Chain = Addr.getValue(1);
3843     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3844     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3845   } else {
3846     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3847                        MachinePointerInfo::getJumpTable(),
3848                        false, false, false, 0);
3849     Chain = Addr.getValue(1);
3850     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3851   }
3852 }
3853
3854 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3855   EVT VT = Op.getValueType();
3856   SDLoc dl(Op);
3857
3858   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3859     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3860       return Op;
3861     return DAG.UnrollVectorOp(Op.getNode());
3862   }
3863
3864   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3865          "Invalid type for custom lowering!");
3866   if (VT != MVT::v4i16)
3867     return DAG.UnrollVectorOp(Op.getNode());
3868
3869   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3870   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3871 }
3872
3873 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3874   EVT VT = Op.getValueType();
3875   if (VT.isVector())
3876     return LowerVectorFP_TO_INT(Op, DAG);
3877
3878   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3879     RTLIB::Libcall LC;
3880     if (Op.getOpcode() == ISD::FP_TO_SINT)
3881       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3882                               Op.getValueType());
3883     else
3884       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3885                               Op.getValueType());
3886     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3887                        /*isSigned*/ false, SDLoc(Op)).first;
3888   }
3889
3890   SDLoc dl(Op);
3891   unsigned Opc;
3892
3893   switch (Op.getOpcode()) {
3894   default: llvm_unreachable("Invalid opcode!");
3895   case ISD::FP_TO_SINT:
3896     Opc = ARMISD::FTOSI;
3897     break;
3898   case ISD::FP_TO_UINT:
3899     Opc = ARMISD::FTOUI;
3900     break;
3901   }
3902   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3903   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3904 }
3905
3906 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3907   EVT VT = Op.getValueType();
3908   SDLoc dl(Op);
3909
3910   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3911     if (VT.getVectorElementType() == MVT::f32)
3912       return Op;
3913     return DAG.UnrollVectorOp(Op.getNode());
3914   }
3915
3916   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3917          "Invalid type for custom lowering!");
3918   if (VT != MVT::v4f32)
3919     return DAG.UnrollVectorOp(Op.getNode());
3920
3921   unsigned CastOpc;
3922   unsigned Opc;
3923   switch (Op.getOpcode()) {
3924   default: llvm_unreachable("Invalid opcode!");
3925   case ISD::SINT_TO_FP:
3926     CastOpc = ISD::SIGN_EXTEND;
3927     Opc = ISD::SINT_TO_FP;
3928     break;
3929   case ISD::UINT_TO_FP:
3930     CastOpc = ISD::ZERO_EXTEND;
3931     Opc = ISD::UINT_TO_FP;
3932     break;
3933   }
3934
3935   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3936   return DAG.getNode(Opc, dl, VT, Op);
3937 }
3938
3939 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3940   EVT VT = Op.getValueType();
3941   if (VT.isVector())
3942     return LowerVectorINT_TO_FP(Op, DAG);
3943
3944   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3945     RTLIB::Libcall LC;
3946     if (Op.getOpcode() == ISD::SINT_TO_FP)
3947       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3948                               Op.getValueType());
3949     else
3950       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3951                               Op.getValueType());
3952     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3953                        /*isSigned*/ false, SDLoc(Op)).first;
3954   }
3955
3956   SDLoc dl(Op);
3957   unsigned Opc;
3958
3959   switch (Op.getOpcode()) {
3960   default: llvm_unreachable("Invalid opcode!");
3961   case ISD::SINT_TO_FP:
3962     Opc = ARMISD::SITOF;
3963     break;
3964   case ISD::UINT_TO_FP:
3965     Opc = ARMISD::UITOF;
3966     break;
3967   }
3968
3969   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3970   return DAG.getNode(Opc, dl, VT, Op);
3971 }
3972
3973 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3974   // Implement fcopysign with a fabs and a conditional fneg.
3975   SDValue Tmp0 = Op.getOperand(0);
3976   SDValue Tmp1 = Op.getOperand(1);
3977   SDLoc dl(Op);
3978   EVT VT = Op.getValueType();
3979   EVT SrcVT = Tmp1.getValueType();
3980   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3981     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3982   bool UseNEON = !InGPR && Subtarget->hasNEON();
3983
3984   if (UseNEON) {
3985     // Use VBSL to copy the sign bit.
3986     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3987     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3988                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3989     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3990     if (VT == MVT::f64)
3991       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3992                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3993                          DAG.getConstant(32, MVT::i32));
3994     else /*if (VT == MVT::f32)*/
3995       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3996     if (SrcVT == MVT::f32) {
3997       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3998       if (VT == MVT::f64)
3999         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4000                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4001                            DAG.getConstant(32, MVT::i32));
4002     } else if (VT == MVT::f32)
4003       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4004                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4005                          DAG.getConstant(32, MVT::i32));
4006     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4007     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4008
4009     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4010                                             MVT::i32);
4011     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4012     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4013                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4014
4015     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4016                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4017                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4018     if (VT == MVT::f32) {
4019       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4020       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4021                         DAG.getConstant(0, MVT::i32));
4022     } else {
4023       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4024     }
4025
4026     return Res;
4027   }
4028
4029   // Bitcast operand 1 to i32.
4030   if (SrcVT == MVT::f64)
4031     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4032                        Tmp1).getValue(1);
4033   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4034
4035   // Or in the signbit with integer operations.
4036   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4037   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4038   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4039   if (VT == MVT::f32) {
4040     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4041                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4042     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4043                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4044   }
4045
4046   // f64: Or the high part with signbit and then combine two parts.
4047   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4048                      Tmp0);
4049   SDValue Lo = Tmp0.getValue(0);
4050   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4051   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4052   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4053 }
4054
4055 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4056   MachineFunction &MF = DAG.getMachineFunction();
4057   MachineFrameInfo *MFI = MF.getFrameInfo();
4058   MFI->setReturnAddressIsTaken(true);
4059
4060   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4061     return SDValue();
4062
4063   EVT VT = Op.getValueType();
4064   SDLoc dl(Op);
4065   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4066   if (Depth) {
4067     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4068     SDValue Offset = DAG.getConstant(4, MVT::i32);
4069     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4070                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4071                        MachinePointerInfo(), false, false, false, 0);
4072   }
4073
4074   // Return LR, which contains the return address. Mark it an implicit live-in.
4075   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4076   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4077 }
4078
4079 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4080   const ARMBaseRegisterInfo &ARI =
4081     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4082   MachineFunction &MF = DAG.getMachineFunction();
4083   MachineFrameInfo *MFI = MF.getFrameInfo();
4084   MFI->setFrameAddressIsTaken(true);
4085
4086   EVT VT = Op.getValueType();
4087   SDLoc dl(Op);  // FIXME probably not meaningful
4088   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4089   unsigned FrameReg = ARI.getFrameRegister(MF);
4090   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4091   while (Depth--)
4092     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4093                             MachinePointerInfo(),
4094                             false, false, false, 0);
4095   return FrameAddr;
4096 }
4097
4098 // FIXME? Maybe this could be a TableGen attribute on some registers and
4099 // this table could be generated automatically from RegInfo.
4100 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4101                                               EVT VT) const {
4102   unsigned Reg = StringSwitch<unsigned>(RegName)
4103                        .Case("sp", ARM::SP)
4104                        .Default(0);
4105   if (Reg)
4106     return Reg;
4107   report_fatal_error("Invalid register name global variable");
4108 }
4109
4110 /// ExpandBITCAST - If the target supports VFP, this function is called to
4111 /// expand a bit convert where either the source or destination type is i64 to
4112 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4113 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4114 /// vectors), since the legalizer won't know what to do with that.
4115 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4117   SDLoc dl(N);
4118   SDValue Op = N->getOperand(0);
4119
4120   // This function is only supposed to be called for i64 types, either as the
4121   // source or destination of the bit convert.
4122   EVT SrcVT = Op.getValueType();
4123   EVT DstVT = N->getValueType(0);
4124   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4125          "ExpandBITCAST called for non-i64 type");
4126
4127   // Turn i64->f64 into VMOVDRR.
4128   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4129     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4130                              DAG.getConstant(0, MVT::i32));
4131     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4132                              DAG.getConstant(1, MVT::i32));
4133     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4134                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4135   }
4136
4137   // Turn f64->i64 into VMOVRRD.
4138   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4139     SDValue Cvt;
4140     if (TLI.isBigEndian() && SrcVT.isVector() &&
4141         SrcVT.getVectorNumElements() > 1)
4142       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4143                         DAG.getVTList(MVT::i32, MVT::i32),
4144                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4145     else
4146       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4147                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4148     // Merge the pieces into a single i64 value.
4149     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4150   }
4151
4152   return SDValue();
4153 }
4154
4155 /// getZeroVector - Returns a vector of specified type with all zero elements.
4156 /// Zero vectors are used to represent vector negation and in those cases
4157 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4158 /// not support i64 elements, so sometimes the zero vectors will need to be
4159 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4160 /// zero vector.
4161 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4162   assert(VT.isVector() && "Expected a vector type");
4163   // The canonical modified immediate encoding of a zero vector is....0!
4164   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4165   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4166   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4167   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4168 }
4169
4170 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4171 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4172 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4173                                                 SelectionDAG &DAG) const {
4174   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4175   EVT VT = Op.getValueType();
4176   unsigned VTBits = VT.getSizeInBits();
4177   SDLoc dl(Op);
4178   SDValue ShOpLo = Op.getOperand(0);
4179   SDValue ShOpHi = Op.getOperand(1);
4180   SDValue ShAmt  = Op.getOperand(2);
4181   SDValue ARMcc;
4182   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4183
4184   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4185
4186   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4187                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4188   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4189   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4190                                    DAG.getConstant(VTBits, MVT::i32));
4191   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4192   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4193   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4194
4195   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4196   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4197                           ARMcc, DAG, dl);
4198   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4199   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4200                            CCR, Cmp);
4201
4202   SDValue Ops[2] = { Lo, Hi };
4203   return DAG.getMergeValues(Ops, dl);
4204 }
4205
4206 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4207 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4208 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4209                                                SelectionDAG &DAG) const {
4210   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4211   EVT VT = Op.getValueType();
4212   unsigned VTBits = VT.getSizeInBits();
4213   SDLoc dl(Op);
4214   SDValue ShOpLo = Op.getOperand(0);
4215   SDValue ShOpHi = Op.getOperand(1);
4216   SDValue ShAmt  = Op.getOperand(2);
4217   SDValue ARMcc;
4218
4219   assert(Op.getOpcode() == ISD::SHL_PARTS);
4220   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4221                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4222   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4223   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4224                                    DAG.getConstant(VTBits, MVT::i32));
4225   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4226   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4227
4228   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4229   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4230   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4231                           ARMcc, DAG, dl);
4232   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4233   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4234                            CCR, Cmp);
4235
4236   SDValue Ops[2] = { Lo, Hi };
4237   return DAG.getMergeValues(Ops, dl);
4238 }
4239
4240 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4241                                             SelectionDAG &DAG) const {
4242   // The rounding mode is in bits 23:22 of the FPSCR.
4243   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4244   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4245   // so that the shift + and get folded into a bitfield extract.
4246   SDLoc dl(Op);
4247   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4248                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4249                                               MVT::i32));
4250   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4251                                   DAG.getConstant(1U << 22, MVT::i32));
4252   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4253                               DAG.getConstant(22, MVT::i32));
4254   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4255                      DAG.getConstant(3, MVT::i32));
4256 }
4257
4258 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4259                          const ARMSubtarget *ST) {
4260   EVT VT = N->getValueType(0);
4261   SDLoc dl(N);
4262
4263   if (!ST->hasV6T2Ops())
4264     return SDValue();
4265
4266   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4267   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4268 }
4269
4270 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4271 /// for each 16-bit element from operand, repeated.  The basic idea is to
4272 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4273 ///
4274 /// Trace for v4i16:
4275 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4276 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4277 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4278 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4279 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4280 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4281 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4282 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4283 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4284   EVT VT = N->getValueType(0);
4285   SDLoc DL(N);
4286
4287   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4288   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4289   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4290   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4291   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4292   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4293 }
4294
4295 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4296 /// bit-count for each 16-bit element from the operand.  We need slightly
4297 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4298 /// 64/128-bit registers.
4299 ///
4300 /// Trace for v4i16:
4301 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4302 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4303 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4304 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4305 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4306   EVT VT = N->getValueType(0);
4307   SDLoc DL(N);
4308
4309   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4310   if (VT.is64BitVector()) {
4311     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4312     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4313                        DAG.getIntPtrConstant(0));
4314   } else {
4315     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4316                                     BitCounts, DAG.getIntPtrConstant(0));
4317     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4318   }
4319 }
4320
4321 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4322 /// bit-count for each 32-bit element from the operand.  The idea here is
4323 /// to split the vector into 16-bit elements, leverage the 16-bit count
4324 /// routine, and then combine the results.
4325 ///
4326 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4327 /// input    = [v0    v1    ] (vi: 32-bit elements)
4328 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4329 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4330 /// vrev: N0 = [k1 k0 k3 k2 ]
4331 ///            [k0 k1 k2 k3 ]
4332 ///       N1 =+[k1 k0 k3 k2 ]
4333 ///            [k0 k2 k1 k3 ]
4334 ///       N2 =+[k1 k3 k0 k2 ]
4335 ///            [k0    k2    k1    k3    ]
4336 /// Extended =+[k1    k3    k0    k2    ]
4337 ///            [k0    k2    ]
4338 /// Extracted=+[k1    k3    ]
4339 ///
4340 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4341   EVT VT = N->getValueType(0);
4342   SDLoc DL(N);
4343
4344   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4345
4346   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4347   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4348   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4349   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4350   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4351
4352   if (VT.is64BitVector()) {
4353     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4354     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4355                        DAG.getIntPtrConstant(0));
4356   } else {
4357     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4358                                     DAG.getIntPtrConstant(0));
4359     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4360   }
4361 }
4362
4363 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4364                           const ARMSubtarget *ST) {
4365   EVT VT = N->getValueType(0);
4366
4367   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4368   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4369           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4370          "Unexpected type for custom ctpop lowering");
4371
4372   if (VT.getVectorElementType() == MVT::i32)
4373     return lowerCTPOP32BitElements(N, DAG);
4374   else
4375     return lowerCTPOP16BitElements(N, DAG);
4376 }
4377
4378 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4379                           const ARMSubtarget *ST) {
4380   EVT VT = N->getValueType(0);
4381   SDLoc dl(N);
4382
4383   if (!VT.isVector())
4384     return SDValue();
4385
4386   // Lower vector shifts on NEON to use VSHL.
4387   assert(ST->hasNEON() && "unexpected vector shift");
4388
4389   // Left shifts translate directly to the vshiftu intrinsic.
4390   if (N->getOpcode() == ISD::SHL)
4391     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4392                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4393                        N->getOperand(0), N->getOperand(1));
4394
4395   assert((N->getOpcode() == ISD::SRA ||
4396           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4397
4398   // NEON uses the same intrinsics for both left and right shifts.  For
4399   // right shifts, the shift amounts are negative, so negate the vector of
4400   // shift amounts.
4401   EVT ShiftVT = N->getOperand(1).getValueType();
4402   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4403                                      getZeroVector(ShiftVT, DAG, dl),
4404                                      N->getOperand(1));
4405   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4406                              Intrinsic::arm_neon_vshifts :
4407                              Intrinsic::arm_neon_vshiftu);
4408   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4409                      DAG.getConstant(vshiftInt, MVT::i32),
4410                      N->getOperand(0), NegatedCount);
4411 }
4412
4413 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4414                                 const ARMSubtarget *ST) {
4415   EVT VT = N->getValueType(0);
4416   SDLoc dl(N);
4417
4418   // We can get here for a node like i32 = ISD::SHL i32, i64
4419   if (VT != MVT::i64)
4420     return SDValue();
4421
4422   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4423          "Unknown shift to lower!");
4424
4425   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4426   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4427       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4428     return SDValue();
4429
4430   // If we are in thumb mode, we don't have RRX.
4431   if (ST->isThumb1Only()) return SDValue();
4432
4433   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4434   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4435                            DAG.getConstant(0, MVT::i32));
4436   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4437                            DAG.getConstant(1, MVT::i32));
4438
4439   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4440   // captures the result into a carry flag.
4441   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4442   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4443
4444   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4445   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4446
4447   // Merge the pieces into a single i64 value.
4448  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4449 }
4450
4451 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4452   SDValue TmpOp0, TmpOp1;
4453   bool Invert = false;
4454   bool Swap = false;
4455   unsigned Opc = 0;
4456
4457   SDValue Op0 = Op.getOperand(0);
4458   SDValue Op1 = Op.getOperand(1);
4459   SDValue CC = Op.getOperand(2);
4460   EVT VT = Op.getValueType();
4461   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4462   SDLoc dl(Op);
4463
4464   if (Op1.getValueType().isFloatingPoint()) {
4465     switch (SetCCOpcode) {
4466     default: llvm_unreachable("Illegal FP comparison");
4467     case ISD::SETUNE:
4468     case ISD::SETNE:  Invert = true; // Fallthrough
4469     case ISD::SETOEQ:
4470     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4471     case ISD::SETOLT:
4472     case ISD::SETLT: Swap = true; // Fallthrough
4473     case ISD::SETOGT:
4474     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4475     case ISD::SETOLE:
4476     case ISD::SETLE:  Swap = true; // Fallthrough
4477     case ISD::SETOGE:
4478     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4479     case ISD::SETUGE: Swap = true; // Fallthrough
4480     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4481     case ISD::SETUGT: Swap = true; // Fallthrough
4482     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4483     case ISD::SETUEQ: Invert = true; // Fallthrough
4484     case ISD::SETONE:
4485       // Expand this to (OLT | OGT).
4486       TmpOp0 = Op0;
4487       TmpOp1 = Op1;
4488       Opc = ISD::OR;
4489       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4490       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4491       break;
4492     case ISD::SETUO: Invert = true; // Fallthrough
4493     case ISD::SETO:
4494       // Expand this to (OLT | OGE).
4495       TmpOp0 = Op0;
4496       TmpOp1 = Op1;
4497       Opc = ISD::OR;
4498       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4499       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4500       break;
4501     }
4502   } else {
4503     // Integer comparisons.
4504     switch (SetCCOpcode) {
4505     default: llvm_unreachable("Illegal integer comparison");
4506     case ISD::SETNE:  Invert = true;
4507     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4508     case ISD::SETLT:  Swap = true;
4509     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4510     case ISD::SETLE:  Swap = true;
4511     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4512     case ISD::SETULT: Swap = true;
4513     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4514     case ISD::SETULE: Swap = true;
4515     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4516     }
4517
4518     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4519     if (Opc == ARMISD::VCEQ) {
4520
4521       SDValue AndOp;
4522       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4523         AndOp = Op0;
4524       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4525         AndOp = Op1;
4526
4527       // Ignore bitconvert.
4528       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4529         AndOp = AndOp.getOperand(0);
4530
4531       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4532         Opc = ARMISD::VTST;
4533         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4534         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4535         Invert = !Invert;
4536       }
4537     }
4538   }
4539
4540   if (Swap)
4541     std::swap(Op0, Op1);
4542
4543   // If one of the operands is a constant vector zero, attempt to fold the
4544   // comparison to a specialized compare-against-zero form.
4545   SDValue SingleOp;
4546   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4547     SingleOp = Op0;
4548   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4549     if (Opc == ARMISD::VCGE)
4550       Opc = ARMISD::VCLEZ;
4551     else if (Opc == ARMISD::VCGT)
4552       Opc = ARMISD::VCLTZ;
4553     SingleOp = Op1;
4554   }
4555
4556   SDValue Result;
4557   if (SingleOp.getNode()) {
4558     switch (Opc) {
4559     case ARMISD::VCEQ:
4560       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4561     case ARMISD::VCGE:
4562       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4563     case ARMISD::VCLEZ:
4564       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4565     case ARMISD::VCGT:
4566       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4567     case ARMISD::VCLTZ:
4568       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4569     default:
4570       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4571     }
4572   } else {
4573      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4574   }
4575
4576   if (Invert)
4577     Result = DAG.getNOT(dl, Result, VT);
4578
4579   return Result;
4580 }
4581
4582 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4583 /// valid vector constant for a NEON instruction with a "modified immediate"
4584 /// operand (e.g., VMOV).  If so, return the encoded value.
4585 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4586                                  unsigned SplatBitSize, SelectionDAG &DAG,
4587                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4588   unsigned OpCmode, Imm;
4589
4590   // SplatBitSize is set to the smallest size that splats the vector, so a
4591   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4592   // immediate instructions others than VMOV do not support the 8-bit encoding
4593   // of a zero vector, and the default encoding of zero is supposed to be the
4594   // 32-bit version.
4595   if (SplatBits == 0)
4596     SplatBitSize = 32;
4597
4598   switch (SplatBitSize) {
4599   case 8:
4600     if (type != VMOVModImm)
4601       return SDValue();
4602     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4603     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4604     OpCmode = 0xe;
4605     Imm = SplatBits;
4606     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4607     break;
4608
4609   case 16:
4610     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4611     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4612     if ((SplatBits & ~0xff) == 0) {
4613       // Value = 0x00nn: Op=x, Cmode=100x.
4614       OpCmode = 0x8;
4615       Imm = SplatBits;
4616       break;
4617     }
4618     if ((SplatBits & ~0xff00) == 0) {
4619       // Value = 0xnn00: Op=x, Cmode=101x.
4620       OpCmode = 0xa;
4621       Imm = SplatBits >> 8;
4622       break;
4623     }
4624     return SDValue();
4625
4626   case 32:
4627     // NEON's 32-bit VMOV supports splat values where:
4628     // * only one byte is nonzero, or
4629     // * the least significant byte is 0xff and the second byte is nonzero, or
4630     // * the least significant 2 bytes are 0xff and the third is nonzero.
4631     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4632     if ((SplatBits & ~0xff) == 0) {
4633       // Value = 0x000000nn: Op=x, Cmode=000x.
4634       OpCmode = 0;
4635       Imm = SplatBits;
4636       break;
4637     }
4638     if ((SplatBits & ~0xff00) == 0) {
4639       // Value = 0x0000nn00: Op=x, Cmode=001x.
4640       OpCmode = 0x2;
4641       Imm = SplatBits >> 8;
4642       break;
4643     }
4644     if ((SplatBits & ~0xff0000) == 0) {
4645       // Value = 0x00nn0000: Op=x, Cmode=010x.
4646       OpCmode = 0x4;
4647       Imm = SplatBits >> 16;
4648       break;
4649     }
4650     if ((SplatBits & ~0xff000000) == 0) {
4651       // Value = 0xnn000000: Op=x, Cmode=011x.
4652       OpCmode = 0x6;
4653       Imm = SplatBits >> 24;
4654       break;
4655     }
4656
4657     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4658     if (type == OtherModImm) return SDValue();
4659
4660     if ((SplatBits & ~0xffff) == 0 &&
4661         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4662       // Value = 0x0000nnff: Op=x, Cmode=1100.
4663       OpCmode = 0xc;
4664       Imm = SplatBits >> 8;
4665       break;
4666     }
4667
4668     if ((SplatBits & ~0xffffff) == 0 &&
4669         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4670       // Value = 0x00nnffff: Op=x, Cmode=1101.
4671       OpCmode = 0xd;
4672       Imm = SplatBits >> 16;
4673       break;
4674     }
4675
4676     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4677     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4678     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4679     // and fall through here to test for a valid 64-bit splat.  But, then the
4680     // caller would also need to check and handle the change in size.
4681     return SDValue();
4682
4683   case 64: {
4684     if (type != VMOVModImm)
4685       return SDValue();
4686     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4687     uint64_t BitMask = 0xff;
4688     uint64_t Val = 0;
4689     unsigned ImmMask = 1;
4690     Imm = 0;
4691     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4692       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4693         Val |= BitMask;
4694         Imm |= ImmMask;
4695       } else if ((SplatBits & BitMask) != 0) {
4696         return SDValue();
4697       }
4698       BitMask <<= 8;
4699       ImmMask <<= 1;
4700     }
4701
4702     if (DAG.getTargetLoweringInfo().isBigEndian())
4703       // swap higher and lower 32 bit word
4704       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4705
4706     // Op=1, Cmode=1110.
4707     OpCmode = 0x1e;
4708     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4709     break;
4710   }
4711
4712   default:
4713     llvm_unreachable("unexpected size for isNEONModifiedImm");
4714   }
4715
4716   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4717   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4718 }
4719
4720 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4721                                            const ARMSubtarget *ST) const {
4722   if (!ST->hasVFP3())
4723     return SDValue();
4724
4725   bool IsDouble = Op.getValueType() == MVT::f64;
4726   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4727
4728   // Use the default (constant pool) lowering for double constants when we have
4729   // an SP-only FPU
4730   if (IsDouble && Subtarget->isFPOnlySP())
4731     return SDValue();
4732
4733   // Try splatting with a VMOV.f32...
4734   APFloat FPVal = CFP->getValueAPF();
4735   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4736
4737   if (ImmVal != -1) {
4738     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4739       // We have code in place to select a valid ConstantFP already, no need to
4740       // do any mangling.
4741       return Op;
4742     }
4743
4744     // It's a float and we are trying to use NEON operations where
4745     // possible. Lower it to a splat followed by an extract.
4746     SDLoc DL(Op);
4747     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4748     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4749                                       NewVal);
4750     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4751                        DAG.getConstant(0, MVT::i32));
4752   }
4753
4754   // The rest of our options are NEON only, make sure that's allowed before
4755   // proceeding..
4756   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4757     return SDValue();
4758
4759   EVT VMovVT;
4760   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4761
4762   // It wouldn't really be worth bothering for doubles except for one very
4763   // important value, which does happen to match: 0.0. So make sure we don't do
4764   // anything stupid.
4765   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4766     return SDValue();
4767
4768   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4769   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4770                                      false, VMOVModImm);
4771   if (NewVal != SDValue()) {
4772     SDLoc DL(Op);
4773     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4774                                       NewVal);
4775     if (IsDouble)
4776       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4777
4778     // It's a float: cast and extract a vector element.
4779     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4780                                        VecConstant);
4781     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4782                        DAG.getConstant(0, MVT::i32));
4783   }
4784
4785   // Finally, try a VMVN.i32
4786   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4787                              false, VMVNModImm);
4788   if (NewVal != SDValue()) {
4789     SDLoc DL(Op);
4790     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4791
4792     if (IsDouble)
4793       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4794
4795     // It's a float: cast and extract a vector element.
4796     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4797                                        VecConstant);
4798     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4799                        DAG.getConstant(0, MVT::i32));
4800   }
4801
4802   return SDValue();
4803 }
4804
4805 // check if an VEXT instruction can handle the shuffle mask when the
4806 // vector sources of the shuffle are the same.
4807 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4808   unsigned NumElts = VT.getVectorNumElements();
4809
4810   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4811   if (M[0] < 0)
4812     return false;
4813
4814   Imm = M[0];
4815
4816   // If this is a VEXT shuffle, the immediate value is the index of the first
4817   // element.  The other shuffle indices must be the successive elements after
4818   // the first one.
4819   unsigned ExpectedElt = Imm;
4820   for (unsigned i = 1; i < NumElts; ++i) {
4821     // Increment the expected index.  If it wraps around, just follow it
4822     // back to index zero and keep going.
4823     ++ExpectedElt;
4824     if (ExpectedElt == NumElts)
4825       ExpectedElt = 0;
4826
4827     if (M[i] < 0) continue; // ignore UNDEF indices
4828     if (ExpectedElt != static_cast<unsigned>(M[i]))
4829       return false;
4830   }
4831
4832   return true;
4833 }
4834
4835
4836 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4837                        bool &ReverseVEXT, unsigned &Imm) {
4838   unsigned NumElts = VT.getVectorNumElements();
4839   ReverseVEXT = false;
4840
4841   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4842   if (M[0] < 0)
4843     return false;
4844
4845   Imm = M[0];
4846
4847   // If this is a VEXT shuffle, the immediate value is the index of the first
4848   // element.  The other shuffle indices must be the successive elements after
4849   // the first one.
4850   unsigned ExpectedElt = Imm;
4851   for (unsigned i = 1; i < NumElts; ++i) {
4852     // Increment the expected index.  If it wraps around, it may still be
4853     // a VEXT but the source vectors must be swapped.
4854     ExpectedElt += 1;
4855     if (ExpectedElt == NumElts * 2) {
4856       ExpectedElt = 0;
4857       ReverseVEXT = true;
4858     }
4859
4860     if (M[i] < 0) continue; // ignore UNDEF indices
4861     if (ExpectedElt != static_cast<unsigned>(M[i]))
4862       return false;
4863   }
4864
4865   // Adjust the index value if the source operands will be swapped.
4866   if (ReverseVEXT)
4867     Imm -= NumElts;
4868
4869   return true;
4870 }
4871
4872 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4873 /// instruction with the specified blocksize.  (The order of the elements
4874 /// within each block of the vector is reversed.)
4875 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4876   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4877          "Only possible block sizes for VREV are: 16, 32, 64");
4878
4879   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4880   if (EltSz == 64)
4881     return false;
4882
4883   unsigned NumElts = VT.getVectorNumElements();
4884   unsigned BlockElts = M[0] + 1;
4885   // If the first shuffle index is UNDEF, be optimistic.
4886   if (M[0] < 0)
4887     BlockElts = BlockSize / EltSz;
4888
4889   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4890     return false;
4891
4892   for (unsigned i = 0; i < NumElts; ++i) {
4893     if (M[i] < 0) continue; // ignore UNDEF indices
4894     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4895       return false;
4896   }
4897
4898   return true;
4899 }
4900
4901 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4902   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4903   // range, then 0 is placed into the resulting vector. So pretty much any mask
4904   // of 8 elements can work here.
4905   return VT == MVT::v8i8 && M.size() == 8;
4906 }
4907
4908 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4909   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4910   if (EltSz == 64)
4911     return false;
4912
4913   unsigned NumElts = VT.getVectorNumElements();
4914   WhichResult = (M[0] == 0 ? 0 : 1);
4915   for (unsigned i = 0; i < NumElts; i += 2) {
4916     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4917         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4918       return false;
4919   }
4920   return true;
4921 }
4922
4923 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4924 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4925 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4926 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4927   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4928   if (EltSz == 64)
4929     return false;
4930
4931   unsigned NumElts = VT.getVectorNumElements();
4932   WhichResult = (M[0] == 0 ? 0 : 1);
4933   for (unsigned i = 0; i < NumElts; i += 2) {
4934     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4935         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4936       return false;
4937   }
4938   return true;
4939 }
4940
4941 static bool isVUZPMask(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) {
4949     if (M[i] < 0) continue; // ignore UNDEF indices
4950     if ((unsigned) M[i] != 2 * i + WhichResult)
4951       return false;
4952   }
4953
4954   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4955   if (VT.is64BitVector() && EltSz == 32)
4956     return false;
4957
4958   return true;
4959 }
4960
4961 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4962 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4963 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4964 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4965   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4966   if (EltSz == 64)
4967     return false;
4968
4969   unsigned Half = VT.getVectorNumElements() / 2;
4970   WhichResult = (M[0] == 0 ? 0 : 1);
4971   for (unsigned j = 0; j != 2; ++j) {
4972     unsigned Idx = WhichResult;
4973     for (unsigned i = 0; i != Half; ++i) {
4974       int MIdx = M[i + j * Half];
4975       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4976         return false;
4977       Idx += 2;
4978     }
4979   }
4980
4981   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4982   if (VT.is64BitVector() && EltSz == 32)
4983     return false;
4984
4985   return true;
4986 }
4987
4988 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4989   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4990   if (EltSz == 64)
4991     return false;
4992
4993   unsigned NumElts = VT.getVectorNumElements();
4994   WhichResult = (M[0] == 0 ? 0 : 1);
4995   unsigned Idx = WhichResult * NumElts / 2;
4996   for (unsigned i = 0; i != NumElts; i += 2) {
4997     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4998         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4999       return false;
5000     Idx += 1;
5001   }
5002
5003   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5004   if (VT.is64BitVector() && EltSz == 32)
5005     return false;
5006
5007   return true;
5008 }
5009
5010 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5011 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5012 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5013 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5014   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5015   if (EltSz == 64)
5016     return false;
5017
5018   unsigned NumElts = VT.getVectorNumElements();
5019   WhichResult = (M[0] == 0 ? 0 : 1);
5020   unsigned Idx = WhichResult * NumElts / 2;
5021   for (unsigned i = 0; i != NumElts; i += 2) {
5022     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5023         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5024       return false;
5025     Idx += 1;
5026   }
5027
5028   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5029   if (VT.is64BitVector() && EltSz == 32)
5030     return false;
5031
5032   return true;
5033 }
5034
5035 /// \return true if this is a reverse operation on an vector.
5036 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5037   unsigned NumElts = VT.getVectorNumElements();
5038   // Make sure the mask has the right size.
5039   if (NumElts != M.size())
5040       return false;
5041
5042   // Look for <15, ..., 3, -1, 1, 0>.
5043   for (unsigned i = 0; i != NumElts; ++i)
5044     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5045       return false;
5046
5047   return true;
5048 }
5049
5050 // If N is an integer constant that can be moved into a register in one
5051 // instruction, return an SDValue of such a constant (will become a MOV
5052 // instruction).  Otherwise return null.
5053 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5054                                      const ARMSubtarget *ST, SDLoc dl) {
5055   uint64_t Val;
5056   if (!isa<ConstantSDNode>(N))
5057     return SDValue();
5058   Val = cast<ConstantSDNode>(N)->getZExtValue();
5059
5060   if (ST->isThumb1Only()) {
5061     if (Val <= 255 || ~Val <= 255)
5062       return DAG.getConstant(Val, MVT::i32);
5063   } else {
5064     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5065       return DAG.getConstant(Val, MVT::i32);
5066   }
5067   return SDValue();
5068 }
5069
5070 // If this is a case we can't handle, return null and let the default
5071 // expansion code take care of it.
5072 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5073                                              const ARMSubtarget *ST) const {
5074   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5075   SDLoc dl(Op);
5076   EVT VT = Op.getValueType();
5077
5078   APInt SplatBits, SplatUndef;
5079   unsigned SplatBitSize;
5080   bool HasAnyUndefs;
5081   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5082     if (SplatBitSize <= 64) {
5083       // Check if an immediate VMOV works.
5084       EVT VmovVT;
5085       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5086                                       SplatUndef.getZExtValue(), SplatBitSize,
5087                                       DAG, VmovVT, VT.is128BitVector(),
5088                                       VMOVModImm);
5089       if (Val.getNode()) {
5090         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5091         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5092       }
5093
5094       // Try an immediate VMVN.
5095       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5096       Val = isNEONModifiedImm(NegatedImm,
5097                                       SplatUndef.getZExtValue(), SplatBitSize,
5098                                       DAG, VmovVT, VT.is128BitVector(),
5099                                       VMVNModImm);
5100       if (Val.getNode()) {
5101         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5102         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5103       }
5104
5105       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5106       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5107         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5108         if (ImmVal != -1) {
5109           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5110           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5111         }
5112       }
5113     }
5114   }
5115
5116   // Scan through the operands to see if only one value is used.
5117   //
5118   // As an optimisation, even if more than one value is used it may be more
5119   // profitable to splat with one value then change some lanes.
5120   //
5121   // Heuristically we decide to do this if the vector has a "dominant" value,
5122   // defined as splatted to more than half of the lanes.
5123   unsigned NumElts = VT.getVectorNumElements();
5124   bool isOnlyLowElement = true;
5125   bool usesOnlyOneValue = true;
5126   bool hasDominantValue = false;
5127   bool isConstant = true;
5128
5129   // Map of the number of times a particular SDValue appears in the
5130   // element list.
5131   DenseMap<SDValue, unsigned> ValueCounts;
5132   SDValue Value;
5133   for (unsigned i = 0; i < NumElts; ++i) {
5134     SDValue V = Op.getOperand(i);
5135     if (V.getOpcode() == ISD::UNDEF)
5136       continue;
5137     if (i > 0)
5138       isOnlyLowElement = false;
5139     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5140       isConstant = false;
5141
5142     ValueCounts.insert(std::make_pair(V, 0));
5143     unsigned &Count = ValueCounts[V];
5144
5145     // Is this value dominant? (takes up more than half of the lanes)
5146     if (++Count > (NumElts / 2)) {
5147       hasDominantValue = true;
5148       Value = V;
5149     }
5150   }
5151   if (ValueCounts.size() != 1)
5152     usesOnlyOneValue = false;
5153   if (!Value.getNode() && ValueCounts.size() > 0)
5154     Value = ValueCounts.begin()->first;
5155
5156   if (ValueCounts.size() == 0)
5157     return DAG.getUNDEF(VT);
5158
5159   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5160   // Keep going if we are hitting this case.
5161   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5162     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5163
5164   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5165
5166   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5167   // i32 and try again.
5168   if (hasDominantValue && EltSize <= 32) {
5169     if (!isConstant) {
5170       SDValue N;
5171
5172       // If we are VDUPing a value that comes directly from a vector, that will
5173       // cause an unnecessary move to and from a GPR, where instead we could
5174       // just use VDUPLANE. We can only do this if the lane being extracted
5175       // is at a constant index, as the VDUP from lane instructions only have
5176       // constant-index forms.
5177       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5178           isa<ConstantSDNode>(Value->getOperand(1))) {
5179         // We need to create a new undef vector to use for the VDUPLANE if the
5180         // size of the vector from which we get the value is different than the
5181         // size of the vector that we need to create. We will insert the element
5182         // such that the register coalescer will remove unnecessary copies.
5183         if (VT != Value->getOperand(0).getValueType()) {
5184           ConstantSDNode *constIndex;
5185           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5186           assert(constIndex && "The index is not a constant!");
5187           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5188                              VT.getVectorNumElements();
5189           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5190                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5191                         Value, DAG.getConstant(index, MVT::i32)),
5192                            DAG.getConstant(index, MVT::i32));
5193         } else
5194           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5195                         Value->getOperand(0), Value->getOperand(1));
5196       } else
5197         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5198
5199       if (!usesOnlyOneValue) {
5200         // The dominant value was splatted as 'N', but we now have to insert
5201         // all differing elements.
5202         for (unsigned I = 0; I < NumElts; ++I) {
5203           if (Op.getOperand(I) == Value)
5204             continue;
5205           SmallVector<SDValue, 3> Ops;
5206           Ops.push_back(N);
5207           Ops.push_back(Op.getOperand(I));
5208           Ops.push_back(DAG.getConstant(I, MVT::i32));
5209           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5210         }
5211       }
5212       return N;
5213     }
5214     if (VT.getVectorElementType().isFloatingPoint()) {
5215       SmallVector<SDValue, 8> Ops;
5216       for (unsigned i = 0; i < NumElts; ++i)
5217         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5218                                   Op.getOperand(i)));
5219       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5220       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5221       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5222       if (Val.getNode())
5223         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5224     }
5225     if (usesOnlyOneValue) {
5226       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5227       if (isConstant && Val.getNode())
5228         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5229     }
5230   }
5231
5232   // If all elements are constants and the case above didn't get hit, fall back
5233   // to the default expansion, which will generate a load from the constant
5234   // pool.
5235   if (isConstant)
5236     return SDValue();
5237
5238   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5239   if (NumElts >= 4) {
5240     SDValue shuffle = ReconstructShuffle(Op, DAG);
5241     if (shuffle != SDValue())
5242       return shuffle;
5243   }
5244
5245   // Vectors with 32- or 64-bit elements can be built by directly assigning
5246   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5247   // will be legalized.
5248   if (EltSize >= 32) {
5249     // Do the expansion with floating-point types, since that is what the VFP
5250     // registers are defined to use, and since i64 is not legal.
5251     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5252     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5253     SmallVector<SDValue, 8> Ops;
5254     for (unsigned i = 0; i < NumElts; ++i)
5255       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5256     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5257     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5258   }
5259
5260   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5261   // know the default expansion would otherwise fall back on something even
5262   // worse. For a vector with one or two non-undef values, that's
5263   // scalar_to_vector for the elements followed by a shuffle (provided the
5264   // shuffle is valid for the target) and materialization element by element
5265   // on the stack followed by a load for everything else.
5266   if (!isConstant && !usesOnlyOneValue) {
5267     SDValue Vec = DAG.getUNDEF(VT);
5268     for (unsigned i = 0 ; i < NumElts; ++i) {
5269       SDValue V = Op.getOperand(i);
5270       if (V.getOpcode() == ISD::UNDEF)
5271         continue;
5272       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5273       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5274     }
5275     return Vec;
5276   }
5277
5278   return SDValue();
5279 }
5280
5281 // Gather data to see if the operation can be modelled as a
5282 // shuffle in combination with VEXTs.
5283 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5284                                               SelectionDAG &DAG) const {
5285   SDLoc dl(Op);
5286   EVT VT = Op.getValueType();
5287   unsigned NumElts = VT.getVectorNumElements();
5288
5289   SmallVector<SDValue, 2> SourceVecs;
5290   SmallVector<unsigned, 2> MinElts;
5291   SmallVector<unsigned, 2> MaxElts;
5292
5293   for (unsigned i = 0; i < NumElts; ++i) {
5294     SDValue V = Op.getOperand(i);
5295     if (V.getOpcode() == ISD::UNDEF)
5296       continue;
5297     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5298       // A shuffle can only come from building a vector from various
5299       // elements of other vectors.
5300       return SDValue();
5301     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5302                VT.getVectorElementType()) {
5303       // This code doesn't know how to handle shuffles where the vector
5304       // element types do not match (this happens because type legalization
5305       // promotes the return type of EXTRACT_VECTOR_ELT).
5306       // FIXME: It might be appropriate to extend this code to handle
5307       // mismatched types.
5308       return SDValue();
5309     }
5310
5311     // Record this extraction against the appropriate vector if possible...
5312     SDValue SourceVec = V.getOperand(0);
5313     // If the element number isn't a constant, we can't effectively
5314     // analyze what's going on.
5315     if (!isa<ConstantSDNode>(V.getOperand(1)))
5316       return SDValue();
5317     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5318     bool FoundSource = false;
5319     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5320       if (SourceVecs[j] == SourceVec) {
5321         if (MinElts[j] > EltNo)
5322           MinElts[j] = EltNo;
5323         if (MaxElts[j] < EltNo)
5324           MaxElts[j] = EltNo;
5325         FoundSource = true;
5326         break;
5327       }
5328     }
5329
5330     // Or record a new source if not...
5331     if (!FoundSource) {
5332       SourceVecs.push_back(SourceVec);
5333       MinElts.push_back(EltNo);
5334       MaxElts.push_back(EltNo);
5335     }
5336   }
5337
5338   // Currently only do something sane when at most two source vectors
5339   // involved.
5340   if (SourceVecs.size() > 2)
5341     return SDValue();
5342
5343   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5344   int VEXTOffsets[2] = {0, 0};
5345
5346   // This loop extracts the usage patterns of the source vectors
5347   // and prepares appropriate SDValues for a shuffle if possible.
5348   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5349     if (SourceVecs[i].getValueType() == VT) {
5350       // No VEXT necessary
5351       ShuffleSrcs[i] = SourceVecs[i];
5352       VEXTOffsets[i] = 0;
5353       continue;
5354     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5355       // It probably isn't worth padding out a smaller vector just to
5356       // break it down again in a shuffle.
5357       return SDValue();
5358     }
5359
5360     // Since only 64-bit and 128-bit vectors are legal on ARM and
5361     // we've eliminated the other cases...
5362     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5363            "unexpected vector sizes in ReconstructShuffle");
5364
5365     if (MaxElts[i] - MinElts[i] >= NumElts) {
5366       // Span too large for a VEXT to cope
5367       return SDValue();
5368     }
5369
5370     if (MinElts[i] >= NumElts) {
5371       // The extraction can just take the second half
5372       VEXTOffsets[i] = NumElts;
5373       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5374                                    SourceVecs[i],
5375                                    DAG.getIntPtrConstant(NumElts));
5376     } else if (MaxElts[i] < NumElts) {
5377       // The extraction can just take the first half
5378       VEXTOffsets[i] = 0;
5379       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5380                                    SourceVecs[i],
5381                                    DAG.getIntPtrConstant(0));
5382     } else {
5383       // An actual VEXT is needed
5384       VEXTOffsets[i] = MinElts[i];
5385       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5386                                      SourceVecs[i],
5387                                      DAG.getIntPtrConstant(0));
5388       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5389                                      SourceVecs[i],
5390                                      DAG.getIntPtrConstant(NumElts));
5391       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5392                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5393     }
5394   }
5395
5396   SmallVector<int, 8> Mask;
5397
5398   for (unsigned i = 0; i < NumElts; ++i) {
5399     SDValue Entry = Op.getOperand(i);
5400     if (Entry.getOpcode() == ISD::UNDEF) {
5401       Mask.push_back(-1);
5402       continue;
5403     }
5404
5405     SDValue ExtractVec = Entry.getOperand(0);
5406     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5407                                           .getOperand(1))->getSExtValue();
5408     if (ExtractVec == SourceVecs[0]) {
5409       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5410     } else {
5411       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5412     }
5413   }
5414
5415   // Final check before we try to produce nonsense...
5416   if (isShuffleMaskLegal(Mask, VT))
5417     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5418                                 &Mask[0]);
5419
5420   return SDValue();
5421 }
5422
5423 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5424 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5425 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5426 /// are assumed to be legal.
5427 bool
5428 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5429                                       EVT VT) const {
5430   if (VT.getVectorNumElements() == 4 &&
5431       (VT.is128BitVector() || VT.is64BitVector())) {
5432     unsigned PFIndexes[4];
5433     for (unsigned i = 0; i != 4; ++i) {
5434       if (M[i] < 0)
5435         PFIndexes[i] = 8;
5436       else
5437         PFIndexes[i] = M[i];
5438     }
5439
5440     // Compute the index in the perfect shuffle table.
5441     unsigned PFTableIndex =
5442       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5443     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5444     unsigned Cost = (PFEntry >> 30);
5445
5446     if (Cost <= 4)
5447       return true;
5448   }
5449
5450   bool ReverseVEXT;
5451   unsigned Imm, WhichResult;
5452
5453   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5454   return (EltSize >= 32 ||
5455           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5456           isVREVMask(M, VT, 64) ||
5457           isVREVMask(M, VT, 32) ||
5458           isVREVMask(M, VT, 16) ||
5459           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5460           isVTBLMask(M, VT) ||
5461           isVTRNMask(M, VT, WhichResult) ||
5462           isVUZPMask(M, VT, WhichResult) ||
5463           isVZIPMask(M, VT, WhichResult) ||
5464           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5465           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5466           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5467           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5468 }
5469
5470 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5471 /// the specified operations to build the shuffle.
5472 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5473                                       SDValue RHS, SelectionDAG &DAG,
5474                                       SDLoc dl) {
5475   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5476   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5477   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5478
5479   enum {
5480     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5481     OP_VREV,
5482     OP_VDUP0,
5483     OP_VDUP1,
5484     OP_VDUP2,
5485     OP_VDUP3,
5486     OP_VEXT1,
5487     OP_VEXT2,
5488     OP_VEXT3,
5489     OP_VUZPL, // VUZP, left result
5490     OP_VUZPR, // VUZP, right result
5491     OP_VZIPL, // VZIP, left result
5492     OP_VZIPR, // VZIP, right result
5493     OP_VTRNL, // VTRN, left result
5494     OP_VTRNR  // VTRN, right result
5495   };
5496
5497   if (OpNum == OP_COPY) {
5498     if (LHSID == (1*9+2)*9+3) return LHS;
5499     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5500     return RHS;
5501   }
5502
5503   SDValue OpLHS, OpRHS;
5504   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5505   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5506   EVT VT = OpLHS.getValueType();
5507
5508   switch (OpNum) {
5509   default: llvm_unreachable("Unknown shuffle opcode!");
5510   case OP_VREV:
5511     // VREV divides the vector in half and swaps within the half.
5512     if (VT.getVectorElementType() == MVT::i32 ||
5513         VT.getVectorElementType() == MVT::f32)
5514       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5515     // vrev <4 x i16> -> VREV32
5516     if (VT.getVectorElementType() == MVT::i16)
5517       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5518     // vrev <4 x i8> -> VREV16
5519     assert(VT.getVectorElementType() == MVT::i8);
5520     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5521   case OP_VDUP0:
5522   case OP_VDUP1:
5523   case OP_VDUP2:
5524   case OP_VDUP3:
5525     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5526                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5527   case OP_VEXT1:
5528   case OP_VEXT2:
5529   case OP_VEXT3:
5530     return DAG.getNode(ARMISD::VEXT, dl, VT,
5531                        OpLHS, OpRHS,
5532                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5533   case OP_VUZPL:
5534   case OP_VUZPR:
5535     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5536                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5537   case OP_VZIPL:
5538   case OP_VZIPR:
5539     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5540                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5541   case OP_VTRNL:
5542   case OP_VTRNR:
5543     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5544                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5545   }
5546 }
5547
5548 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5549                                        ArrayRef<int> ShuffleMask,
5550                                        SelectionDAG &DAG) {
5551   // Check to see if we can use the VTBL instruction.
5552   SDValue V1 = Op.getOperand(0);
5553   SDValue V2 = Op.getOperand(1);
5554   SDLoc DL(Op);
5555
5556   SmallVector<SDValue, 8> VTBLMask;
5557   for (ArrayRef<int>::iterator
5558          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5559     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5560
5561   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5562     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5563                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5564
5565   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5566                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5567 }
5568
5569 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5570                                                       SelectionDAG &DAG) {
5571   SDLoc DL(Op);
5572   SDValue OpLHS = Op.getOperand(0);
5573   EVT VT = OpLHS.getValueType();
5574
5575   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5576          "Expect an v8i16/v16i8 type");
5577   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5578   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5579   // extract the first 8 bytes into the top double word and the last 8 bytes
5580   // into the bottom double word. The v8i16 case is similar.
5581   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5582   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5583                      DAG.getConstant(ExtractNum, MVT::i32));
5584 }
5585
5586 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5587   SDValue V1 = Op.getOperand(0);
5588   SDValue V2 = Op.getOperand(1);
5589   SDLoc dl(Op);
5590   EVT VT = Op.getValueType();
5591   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5592
5593   // Convert shuffles that are directly supported on NEON to target-specific
5594   // DAG nodes, instead of keeping them as shuffles and matching them again
5595   // during code selection.  This is more efficient and avoids the possibility
5596   // of inconsistencies between legalization and selection.
5597   // FIXME: floating-point vectors should be canonicalized to integer vectors
5598   // of the same time so that they get CSEd properly.
5599   ArrayRef<int> ShuffleMask = SVN->getMask();
5600
5601   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5602   if (EltSize <= 32) {
5603     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5604       int Lane = SVN->getSplatIndex();
5605       // If this is undef splat, generate it via "just" vdup, if possible.
5606       if (Lane == -1) Lane = 0;
5607
5608       // Test if V1 is a SCALAR_TO_VECTOR.
5609       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5610         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5611       }
5612       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5613       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5614       // reaches it).
5615       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5616           !isa<ConstantSDNode>(V1.getOperand(0))) {
5617         bool IsScalarToVector = true;
5618         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5619           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5620             IsScalarToVector = false;
5621             break;
5622           }
5623         if (IsScalarToVector)
5624           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5625       }
5626       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5627                          DAG.getConstant(Lane, MVT::i32));
5628     }
5629
5630     bool ReverseVEXT;
5631     unsigned Imm;
5632     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5633       if (ReverseVEXT)
5634         std::swap(V1, V2);
5635       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5636                          DAG.getConstant(Imm, MVT::i32));
5637     }
5638
5639     if (isVREVMask(ShuffleMask, VT, 64))
5640       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5641     if (isVREVMask(ShuffleMask, VT, 32))
5642       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5643     if (isVREVMask(ShuffleMask, VT, 16))
5644       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5645
5646     if (V2->getOpcode() == ISD::UNDEF &&
5647         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5648       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5649                          DAG.getConstant(Imm, MVT::i32));
5650     }
5651
5652     // Check for Neon shuffles that modify both input vectors in place.
5653     // If both results are used, i.e., if there are two shuffles with the same
5654     // source operands and with masks corresponding to both results of one of
5655     // these operations, DAG memoization will ensure that a single node is
5656     // used for both shuffles.
5657     unsigned WhichResult;
5658     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5659       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5660                          V1, V2).getValue(WhichResult);
5661     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5662       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5663                          V1, V2).getValue(WhichResult);
5664     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5665       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5666                          V1, V2).getValue(WhichResult);
5667
5668     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5669       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5670                          V1, V1).getValue(WhichResult);
5671     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5672       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5673                          V1, V1).getValue(WhichResult);
5674     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5675       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5676                          V1, V1).getValue(WhichResult);
5677   }
5678
5679   // If the shuffle is not directly supported and it has 4 elements, use
5680   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5681   unsigned NumElts = VT.getVectorNumElements();
5682   if (NumElts == 4) {
5683     unsigned PFIndexes[4];
5684     for (unsigned i = 0; i != 4; ++i) {
5685       if (ShuffleMask[i] < 0)
5686         PFIndexes[i] = 8;
5687       else
5688         PFIndexes[i] = ShuffleMask[i];
5689     }
5690
5691     // Compute the index in the perfect shuffle table.
5692     unsigned PFTableIndex =
5693       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5694     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5695     unsigned Cost = (PFEntry >> 30);
5696
5697     if (Cost <= 4)
5698       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5699   }
5700
5701   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5702   if (EltSize >= 32) {
5703     // Do the expansion with floating-point types, since that is what the VFP
5704     // registers are defined to use, and since i64 is not legal.
5705     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5706     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5707     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5708     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5709     SmallVector<SDValue, 8> Ops;
5710     for (unsigned i = 0; i < NumElts; ++i) {
5711       if (ShuffleMask[i] < 0)
5712         Ops.push_back(DAG.getUNDEF(EltVT));
5713       else
5714         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5715                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5716                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5717                                                   MVT::i32)));
5718     }
5719     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5720     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5721   }
5722
5723   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5724     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5725
5726   if (VT == MVT::v8i8) {
5727     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5728     if (NewOp.getNode())
5729       return NewOp;
5730   }
5731
5732   return SDValue();
5733 }
5734
5735 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5736   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5737   SDValue Lane = Op.getOperand(2);
5738   if (!isa<ConstantSDNode>(Lane))
5739     return SDValue();
5740
5741   return Op;
5742 }
5743
5744 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5745   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5746   SDValue Lane = Op.getOperand(1);
5747   if (!isa<ConstantSDNode>(Lane))
5748     return SDValue();
5749
5750   SDValue Vec = Op.getOperand(0);
5751   if (Op.getValueType() == MVT::i32 &&
5752       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5753     SDLoc dl(Op);
5754     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5755   }
5756
5757   return Op;
5758 }
5759
5760 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5761   // The only time a CONCAT_VECTORS operation can have legal types is when
5762   // two 64-bit vectors are concatenated to a 128-bit vector.
5763   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5764          "unexpected CONCAT_VECTORS");
5765   SDLoc dl(Op);
5766   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5767   SDValue Op0 = Op.getOperand(0);
5768   SDValue Op1 = Op.getOperand(1);
5769   if (Op0.getOpcode() != ISD::UNDEF)
5770     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5771                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5772                       DAG.getIntPtrConstant(0));
5773   if (Op1.getOpcode() != ISD::UNDEF)
5774     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5775                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5776                       DAG.getIntPtrConstant(1));
5777   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5778 }
5779
5780 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5781 /// element has been zero/sign-extended, depending on the isSigned parameter,
5782 /// from an integer type half its size.
5783 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5784                                    bool isSigned) {
5785   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5786   EVT VT = N->getValueType(0);
5787   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5788     SDNode *BVN = N->getOperand(0).getNode();
5789     if (BVN->getValueType(0) != MVT::v4i32 ||
5790         BVN->getOpcode() != ISD::BUILD_VECTOR)
5791       return false;
5792     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5793     unsigned HiElt = 1 - LoElt;
5794     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5795     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5796     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5797     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5798     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5799       return false;
5800     if (isSigned) {
5801       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5802           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5803         return true;
5804     } else {
5805       if (Hi0->isNullValue() && Hi1->isNullValue())
5806         return true;
5807     }
5808     return false;
5809   }
5810
5811   if (N->getOpcode() != ISD::BUILD_VECTOR)
5812     return false;
5813
5814   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5815     SDNode *Elt = N->getOperand(i).getNode();
5816     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5817       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5818       unsigned HalfSize = EltSize / 2;
5819       if (isSigned) {
5820         if (!isIntN(HalfSize, C->getSExtValue()))
5821           return false;
5822       } else {
5823         if (!isUIntN(HalfSize, C->getZExtValue()))
5824           return false;
5825       }
5826       continue;
5827     }
5828     return false;
5829   }
5830
5831   return true;
5832 }
5833
5834 /// isSignExtended - Check if a node is a vector value that is sign-extended
5835 /// or a constant BUILD_VECTOR with sign-extended elements.
5836 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5837   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5838     return true;
5839   if (isExtendedBUILD_VECTOR(N, DAG, true))
5840     return true;
5841   return false;
5842 }
5843
5844 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5845 /// or a constant BUILD_VECTOR with zero-extended elements.
5846 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5847   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5848     return true;
5849   if (isExtendedBUILD_VECTOR(N, DAG, false))
5850     return true;
5851   return false;
5852 }
5853
5854 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5855   if (OrigVT.getSizeInBits() >= 64)
5856     return OrigVT;
5857
5858   assert(OrigVT.isSimple() && "Expecting a simple value type");
5859
5860   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5861   switch (OrigSimpleTy) {
5862   default: llvm_unreachable("Unexpected Vector Type");
5863   case MVT::v2i8:
5864   case MVT::v2i16:
5865      return MVT::v2i32;
5866   case MVT::v4i8:
5867     return  MVT::v4i16;
5868   }
5869 }
5870
5871 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5872 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5873 /// We insert the required extension here to get the vector to fill a D register.
5874 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5875                                             const EVT &OrigTy,
5876                                             const EVT &ExtTy,
5877                                             unsigned ExtOpcode) {
5878   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5879   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5880   // 64-bits we need to insert a new extension so that it will be 64-bits.
5881   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5882   if (OrigTy.getSizeInBits() >= 64)
5883     return N;
5884
5885   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5886   EVT NewVT = getExtensionTo64Bits(OrigTy);
5887
5888   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5889 }
5890
5891 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5892 /// does not do any sign/zero extension. If the original vector is less
5893 /// than 64 bits, an appropriate extension will be added after the load to
5894 /// reach a total size of 64 bits. We have to add the extension separately
5895 /// because ARM does not have a sign/zero extending load for vectors.
5896 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5897   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5898
5899   // The load already has the right type.
5900   if (ExtendedTy == LD->getMemoryVT())
5901     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5902                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5903                 LD->isNonTemporal(), LD->isInvariant(),
5904                 LD->getAlignment());
5905
5906   // We need to create a zextload/sextload. We cannot just create a load
5907   // followed by a zext/zext node because LowerMUL is also run during normal
5908   // operation legalization where we can't create illegal types.
5909   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5910                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5911                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5912                         LD->isNonTemporal(), LD->getAlignment());
5913 }
5914
5915 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5916 /// extending load, or BUILD_VECTOR with extended elements, return the
5917 /// unextended value. The unextended vector should be 64 bits so that it can
5918 /// be used as an operand to a VMULL instruction. If the original vector size
5919 /// before extension is less than 64 bits we add a an extension to resize
5920 /// the vector to 64 bits.
5921 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5922   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5923     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5924                                         N->getOperand(0)->getValueType(0),
5925                                         N->getValueType(0),
5926                                         N->getOpcode());
5927
5928   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5929     return SkipLoadExtensionForVMULL(LD, DAG);
5930
5931   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5932   // have been legalized as a BITCAST from v4i32.
5933   if (N->getOpcode() == ISD::BITCAST) {
5934     SDNode *BVN = N->getOperand(0).getNode();
5935     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5936            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5937     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5938     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5939                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5940   }
5941   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5942   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5943   EVT VT = N->getValueType(0);
5944   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5945   unsigned NumElts = VT.getVectorNumElements();
5946   MVT TruncVT = MVT::getIntegerVT(EltSize);
5947   SmallVector<SDValue, 8> Ops;
5948   for (unsigned i = 0; i != NumElts; ++i) {
5949     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5950     const APInt &CInt = C->getAPIntValue();
5951     // Element types smaller than 32 bits are not legal, so use i32 elements.
5952     // The values are implicitly truncated so sext vs. zext doesn't matter.
5953     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5954   }
5955   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5956                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5957 }
5958
5959 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5960   unsigned Opcode = N->getOpcode();
5961   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5962     SDNode *N0 = N->getOperand(0).getNode();
5963     SDNode *N1 = N->getOperand(1).getNode();
5964     return N0->hasOneUse() && N1->hasOneUse() &&
5965       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5966   }
5967   return false;
5968 }
5969
5970 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5971   unsigned Opcode = N->getOpcode();
5972   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5973     SDNode *N0 = N->getOperand(0).getNode();
5974     SDNode *N1 = N->getOperand(1).getNode();
5975     return N0->hasOneUse() && N1->hasOneUse() &&
5976       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5977   }
5978   return false;
5979 }
5980
5981 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5982   // Multiplications are only custom-lowered for 128-bit vectors so that
5983   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5984   EVT VT = Op.getValueType();
5985   assert(VT.is128BitVector() && VT.isInteger() &&
5986          "unexpected type for custom-lowering ISD::MUL");
5987   SDNode *N0 = Op.getOperand(0).getNode();
5988   SDNode *N1 = Op.getOperand(1).getNode();
5989   unsigned NewOpc = 0;
5990   bool isMLA = false;
5991   bool isN0SExt = isSignExtended(N0, DAG);
5992   bool isN1SExt = isSignExtended(N1, DAG);
5993   if (isN0SExt && isN1SExt)
5994     NewOpc = ARMISD::VMULLs;
5995   else {
5996     bool isN0ZExt = isZeroExtended(N0, DAG);
5997     bool isN1ZExt = isZeroExtended(N1, DAG);
5998     if (isN0ZExt && isN1ZExt)
5999       NewOpc = ARMISD::VMULLu;
6000     else if (isN1SExt || isN1ZExt) {
6001       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6002       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6003       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6004         NewOpc = ARMISD::VMULLs;
6005         isMLA = true;
6006       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6007         NewOpc = ARMISD::VMULLu;
6008         isMLA = true;
6009       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6010         std::swap(N0, N1);
6011         NewOpc = ARMISD::VMULLu;
6012         isMLA = true;
6013       }
6014     }
6015
6016     if (!NewOpc) {
6017       if (VT == MVT::v2i64)
6018         // Fall through to expand this.  It is not legal.
6019         return SDValue();
6020       else
6021         // Other vector multiplications are legal.
6022         return Op;
6023     }
6024   }
6025
6026   // Legalize to a VMULL instruction.
6027   SDLoc DL(Op);
6028   SDValue Op0;
6029   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6030   if (!isMLA) {
6031     Op0 = SkipExtensionForVMULL(N0, DAG);
6032     assert(Op0.getValueType().is64BitVector() &&
6033            Op1.getValueType().is64BitVector() &&
6034            "unexpected types for extended operands to VMULL");
6035     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6036   }
6037
6038   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6039   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6040   //   vmull q0, d4, d6
6041   //   vmlal q0, d5, d6
6042   // is faster than
6043   //   vaddl q0, d4, d5
6044   //   vmovl q1, d6
6045   //   vmul  q0, q0, q1
6046   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6047   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6048   EVT Op1VT = Op1.getValueType();
6049   return DAG.getNode(N0->getOpcode(), DL, VT,
6050                      DAG.getNode(NewOpc, DL, VT,
6051                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6052                      DAG.getNode(NewOpc, DL, VT,
6053                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6054 }
6055
6056 static SDValue
6057 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6058   // Convert to float
6059   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6060   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6061   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6062   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6063   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6064   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6065   // Get reciprocal estimate.
6066   // float4 recip = vrecpeq_f32(yf);
6067   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6068                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6069   // Because char has a smaller range than uchar, we can actually get away
6070   // without any newton steps.  This requires that we use a weird bias
6071   // of 0xb000, however (again, this has been exhaustively tested).
6072   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6073   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6074   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6075   Y = DAG.getConstant(0xb000, MVT::i32);
6076   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6077   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6078   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6079   // Convert back to short.
6080   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6081   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6082   return X;
6083 }
6084
6085 static SDValue
6086 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6087   SDValue N2;
6088   // Convert to float.
6089   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6090   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6091   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6092   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6093   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6094   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6095
6096   // Use reciprocal estimate and one refinement step.
6097   // float4 recip = vrecpeq_f32(yf);
6098   // recip *= vrecpsq_f32(yf, recip);
6099   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6100                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6101   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6102                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6103                    N1, N2);
6104   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6105   // Because short has a smaller range than ushort, we can actually get away
6106   // with only a single newton step.  This requires that we use a weird bias
6107   // of 89, however (again, this has been exhaustively tested).
6108   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6109   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6110   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6111   N1 = DAG.getConstant(0x89, MVT::i32);
6112   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6113   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6114   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6115   // Convert back to integer and return.
6116   // return vmovn_s32(vcvt_s32_f32(result));
6117   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6118   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6119   return N0;
6120 }
6121
6122 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6123   EVT VT = Op.getValueType();
6124   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6125          "unexpected type for custom-lowering ISD::SDIV");
6126
6127   SDLoc dl(Op);
6128   SDValue N0 = Op.getOperand(0);
6129   SDValue N1 = Op.getOperand(1);
6130   SDValue N2, N3;
6131
6132   if (VT == MVT::v8i8) {
6133     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6134     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6135
6136     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6137                      DAG.getIntPtrConstant(4));
6138     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6139                      DAG.getIntPtrConstant(4));
6140     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6141                      DAG.getIntPtrConstant(0));
6142     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6143                      DAG.getIntPtrConstant(0));
6144
6145     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6146     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6147
6148     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6149     N0 = LowerCONCAT_VECTORS(N0, DAG);
6150
6151     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6152     return N0;
6153   }
6154   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6155 }
6156
6157 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6158   EVT VT = Op.getValueType();
6159   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6160          "unexpected type for custom-lowering ISD::UDIV");
6161
6162   SDLoc dl(Op);
6163   SDValue N0 = Op.getOperand(0);
6164   SDValue N1 = Op.getOperand(1);
6165   SDValue N2, N3;
6166
6167   if (VT == MVT::v8i8) {
6168     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6169     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6170
6171     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6172                      DAG.getIntPtrConstant(4));
6173     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6174                      DAG.getIntPtrConstant(4));
6175     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6176                      DAG.getIntPtrConstant(0));
6177     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6178                      DAG.getIntPtrConstant(0));
6179
6180     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6181     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6182
6183     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6184     N0 = LowerCONCAT_VECTORS(N0, DAG);
6185
6186     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6187                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6188                      N0);
6189     return N0;
6190   }
6191
6192   // v4i16 sdiv ... Convert to float.
6193   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6194   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6195   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6196   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6197   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6198   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6199
6200   // Use reciprocal estimate and two refinement steps.
6201   // float4 recip = vrecpeq_f32(yf);
6202   // recip *= vrecpsq_f32(yf, recip);
6203   // recip *= vrecpsq_f32(yf, recip);
6204   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6205                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6206   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6207                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6208                    BN1, N2);
6209   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6210   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6211                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6212                    BN1, N2);
6213   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6214   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6215   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6216   // and that it will never cause us to return an answer too large).
6217   // float4 result = as_float4(as_int4(xf*recip) + 2);
6218   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6219   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6220   N1 = DAG.getConstant(2, MVT::i32);
6221   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6222   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6223   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6224   // Convert back to integer and return.
6225   // return vmovn_u32(vcvt_s32_f32(result));
6226   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6227   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6228   return N0;
6229 }
6230
6231 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6232   EVT VT = Op.getNode()->getValueType(0);
6233   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6234
6235   unsigned Opc;
6236   bool ExtraOp = false;
6237   switch (Op.getOpcode()) {
6238   default: llvm_unreachable("Invalid code");
6239   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6240   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6241   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6242   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6243   }
6244
6245   if (!ExtraOp)
6246     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6247                        Op.getOperand(1));
6248   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6249                      Op.getOperand(1), Op.getOperand(2));
6250 }
6251
6252 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6253   assert(Subtarget->isTargetDarwin());
6254
6255   // For iOS, we want to call an alternative entry point: __sincos_stret,
6256   // return values are passed via sret.
6257   SDLoc dl(Op);
6258   SDValue Arg = Op.getOperand(0);
6259   EVT ArgVT = Arg.getValueType();
6260   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6261
6262   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6264
6265   // Pair of floats / doubles used to pass the result.
6266   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6267
6268   // Create stack object for sret.
6269   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6270   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6271   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6272   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6273
6274   ArgListTy Args;
6275   ArgListEntry Entry;
6276
6277   Entry.Node = SRet;
6278   Entry.Ty = RetTy->getPointerTo();
6279   Entry.isSExt = false;
6280   Entry.isZExt = false;
6281   Entry.isSRet = true;
6282   Args.push_back(Entry);
6283
6284   Entry.Node = Arg;
6285   Entry.Ty = ArgTy;
6286   Entry.isSExt = false;
6287   Entry.isZExt = false;
6288   Args.push_back(Entry);
6289
6290   const char *LibcallName  = (ArgVT == MVT::f64)
6291   ? "__sincos_stret" : "__sincosf_stret";
6292   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6293
6294   TargetLowering::CallLoweringInfo CLI(DAG);
6295   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6296     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6297                std::move(Args), 0)
6298     .setDiscardResult();
6299
6300   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6301
6302   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6303                                 MachinePointerInfo(), false, false, false, 0);
6304
6305   // Address of cos field.
6306   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6307                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6308   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6309                                 MachinePointerInfo(), false, false, false, 0);
6310
6311   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6312   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6313                      LoadSin.getValue(0), LoadCos.getValue(0));
6314 }
6315
6316 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6317   // Monotonic load/store is legal for all targets
6318   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6319     return Op;
6320
6321   // Acquire/Release load/store is not legal for targets without a
6322   // dmb or equivalent available.
6323   return SDValue();
6324 }
6325
6326 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6327                                     SmallVectorImpl<SDValue> &Results,
6328                                     SelectionDAG &DAG,
6329                                     const ARMSubtarget *Subtarget) {
6330   SDLoc DL(N);
6331   SDValue Cycles32, OutChain;
6332
6333   if (Subtarget->hasPerfMon()) {
6334     // Under Power Management extensions, the cycle-count is:
6335     //    mrc p15, #0, <Rt>, c9, c13, #0
6336     SDValue Ops[] = { N->getOperand(0), // Chain
6337                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6338                       DAG.getConstant(15, MVT::i32),
6339                       DAG.getConstant(0, MVT::i32),
6340                       DAG.getConstant(9, MVT::i32),
6341                       DAG.getConstant(13, MVT::i32),
6342                       DAG.getConstant(0, MVT::i32)
6343     };
6344
6345     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6346                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6347     OutChain = Cycles32.getValue(1);
6348   } else {
6349     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6350     // there are older ARM CPUs that have implementation-specific ways of
6351     // obtaining this information (FIXME!).
6352     Cycles32 = DAG.getConstant(0, MVT::i32);
6353     OutChain = DAG.getEntryNode();
6354   }
6355
6356
6357   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6358                                  Cycles32, DAG.getConstant(0, MVT::i32));
6359   Results.push_back(Cycles64);
6360   Results.push_back(OutChain);
6361 }
6362
6363 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6364   switch (Op.getOpcode()) {
6365   default: llvm_unreachable("Don't know how to custom lower this!");
6366   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6367   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6368   case ISD::GlobalAddress:
6369     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6370     default: llvm_unreachable("unknown object format");
6371     case Triple::COFF:
6372       return LowerGlobalAddressWindows(Op, DAG);
6373     case Triple::ELF:
6374       return LowerGlobalAddressELF(Op, DAG);
6375     case Triple::MachO:
6376       return LowerGlobalAddressDarwin(Op, DAG);
6377     }
6378   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6379   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6380   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6381   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6382   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6383   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6384   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6385   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6386   case ISD::SINT_TO_FP:
6387   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6388   case ISD::FP_TO_SINT:
6389   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6390   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6391   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6392   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6393   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6394   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6395   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6396   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6397                                                                Subtarget);
6398   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6399   case ISD::SHL:
6400   case ISD::SRL:
6401   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6402   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6403   case ISD::SRL_PARTS:
6404   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6405   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6406   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6407   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6408   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6409   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6410   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6411   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6412   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6413   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6414   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6415   case ISD::MUL:           return LowerMUL(Op, DAG);
6416   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6417   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6418   case ISD::ADDC:
6419   case ISD::ADDE:
6420   case ISD::SUBC:
6421   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6422   case ISD::SADDO:
6423   case ISD::UADDO:
6424   case ISD::SSUBO:
6425   case ISD::USUBO:
6426     return LowerXALUO(Op, DAG);
6427   case ISD::ATOMIC_LOAD:
6428   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6429   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6430   case ISD::SDIVREM:
6431   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6432   case ISD::DYNAMIC_STACKALLOC:
6433     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6434       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6435     llvm_unreachable("Don't know how to custom lower this!");
6436   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6437   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6438   }
6439 }
6440
6441 /// ReplaceNodeResults - Replace the results of node with an illegal result
6442 /// type with new values built out of custom code.
6443 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6444                                            SmallVectorImpl<SDValue>&Results,
6445                                            SelectionDAG &DAG) const {
6446   SDValue Res;
6447   switch (N->getOpcode()) {
6448   default:
6449     llvm_unreachable("Don't know how to custom expand this!");
6450   case ISD::BITCAST:
6451     Res = ExpandBITCAST(N, DAG);
6452     break;
6453   case ISD::SRL:
6454   case ISD::SRA:
6455     Res = Expand64BitShift(N, DAG, Subtarget);
6456     break;
6457   case ISD::READCYCLECOUNTER:
6458     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6459     return;
6460   }
6461   if (Res.getNode())
6462     Results.push_back(Res);
6463 }
6464
6465 //===----------------------------------------------------------------------===//
6466 //                           ARM Scheduler Hooks
6467 //===----------------------------------------------------------------------===//
6468
6469 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6470 /// registers the function context.
6471 void ARMTargetLowering::
6472 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6473                        MachineBasicBlock *DispatchBB, int FI) const {
6474   const TargetInstrInfo *TII =
6475       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6476   DebugLoc dl = MI->getDebugLoc();
6477   MachineFunction *MF = MBB->getParent();
6478   MachineRegisterInfo *MRI = &MF->getRegInfo();
6479   MachineConstantPool *MCP = MF->getConstantPool();
6480   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6481   const Function *F = MF->getFunction();
6482
6483   bool isThumb = Subtarget->isThumb();
6484   bool isThumb2 = Subtarget->isThumb2();
6485
6486   unsigned PCLabelId = AFI->createPICLabelUId();
6487   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6488   ARMConstantPoolValue *CPV =
6489     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6490   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6491
6492   const TargetRegisterClass *TRC = isThumb ?
6493     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6494     (const TargetRegisterClass*)&ARM::GPRRegClass;
6495
6496   // Grab constant pool and fixed stack memory operands.
6497   MachineMemOperand *CPMMO =
6498     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6499                              MachineMemOperand::MOLoad, 4, 4);
6500
6501   MachineMemOperand *FIMMOSt =
6502     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6503                              MachineMemOperand::MOStore, 4, 4);
6504
6505   // Load the address of the dispatch MBB into the jump buffer.
6506   if (isThumb2) {
6507     // Incoming value: jbuf
6508     //   ldr.n  r5, LCPI1_1
6509     //   orr    r5, r5, #1
6510     //   add    r5, pc
6511     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6512     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6513     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6514                    .addConstantPoolIndex(CPI)
6515                    .addMemOperand(CPMMO));
6516     // Set the low bit because of thumb mode.
6517     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6518     AddDefaultCC(
6519       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6520                      .addReg(NewVReg1, RegState::Kill)
6521                      .addImm(0x01)));
6522     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6523     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6524       .addReg(NewVReg2, RegState::Kill)
6525       .addImm(PCLabelId);
6526     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6527                    .addReg(NewVReg3, RegState::Kill)
6528                    .addFrameIndex(FI)
6529                    .addImm(36)  // &jbuf[1] :: pc
6530                    .addMemOperand(FIMMOSt));
6531   } else if (isThumb) {
6532     // Incoming value: jbuf
6533     //   ldr.n  r1, LCPI1_4
6534     //   add    r1, pc
6535     //   mov    r2, #1
6536     //   orrs   r1, r2
6537     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6538     //   str    r1, [r2]
6539     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6540     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6541                    .addConstantPoolIndex(CPI)
6542                    .addMemOperand(CPMMO));
6543     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6544     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6545       .addReg(NewVReg1, RegState::Kill)
6546       .addImm(PCLabelId);
6547     // Set the low bit because of thumb mode.
6548     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6549     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6550                    .addReg(ARM::CPSR, RegState::Define)
6551                    .addImm(1));
6552     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6553     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6554                    .addReg(ARM::CPSR, RegState::Define)
6555                    .addReg(NewVReg2, RegState::Kill)
6556                    .addReg(NewVReg3, RegState::Kill));
6557     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6558     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6559                    .addFrameIndex(FI)
6560                    .addImm(36)); // &jbuf[1] :: pc
6561     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6562                    .addReg(NewVReg4, RegState::Kill)
6563                    .addReg(NewVReg5, RegState::Kill)
6564                    .addImm(0)
6565                    .addMemOperand(FIMMOSt));
6566   } else {
6567     // Incoming value: jbuf
6568     //   ldr  r1, LCPI1_1
6569     //   add  r1, pc, r1
6570     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6571     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6572     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6573                    .addConstantPoolIndex(CPI)
6574                    .addImm(0)
6575                    .addMemOperand(CPMMO));
6576     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6577     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6578                    .addReg(NewVReg1, RegState::Kill)
6579                    .addImm(PCLabelId));
6580     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6581                    .addReg(NewVReg2, RegState::Kill)
6582                    .addFrameIndex(FI)
6583                    .addImm(36)  // &jbuf[1] :: pc
6584                    .addMemOperand(FIMMOSt));
6585   }
6586 }
6587
6588 MachineBasicBlock *ARMTargetLowering::
6589 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6590   const TargetInstrInfo *TII =
6591       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6592   DebugLoc dl = MI->getDebugLoc();
6593   MachineFunction *MF = MBB->getParent();
6594   MachineRegisterInfo *MRI = &MF->getRegInfo();
6595   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6596   MachineFrameInfo *MFI = MF->getFrameInfo();
6597   int FI = MFI->getFunctionContextIndex();
6598
6599   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6600     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6601     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6602
6603   // Get a mapping of the call site numbers to all of the landing pads they're
6604   // associated with.
6605   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6606   unsigned MaxCSNum = 0;
6607   MachineModuleInfo &MMI = MF->getMMI();
6608   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6609        ++BB) {
6610     if (!BB->isLandingPad()) continue;
6611
6612     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6613     // pad.
6614     for (MachineBasicBlock::iterator
6615            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6616       if (!II->isEHLabel()) continue;
6617
6618       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6619       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6620
6621       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6622       for (SmallVectorImpl<unsigned>::iterator
6623              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6624            CSI != CSE; ++CSI) {
6625         CallSiteNumToLPad[*CSI].push_back(BB);
6626         MaxCSNum = std::max(MaxCSNum, *CSI);
6627       }
6628       break;
6629     }
6630   }
6631
6632   // Get an ordered list of the machine basic blocks for the jump table.
6633   std::vector<MachineBasicBlock*> LPadList;
6634   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6635   LPadList.reserve(CallSiteNumToLPad.size());
6636   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6637     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6638     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6639            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6640       LPadList.push_back(*II);
6641       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6642     }
6643   }
6644
6645   assert(!LPadList.empty() &&
6646          "No landing pad destinations for the dispatch jump table!");
6647
6648   // Create the jump table and associated information.
6649   MachineJumpTableInfo *JTI =
6650     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6651   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6652   unsigned UId = AFI->createJumpTableUId();
6653   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6654
6655   // Create the MBBs for the dispatch code.
6656
6657   // Shove the dispatch's address into the return slot in the function context.
6658   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6659   DispatchBB->setIsLandingPad();
6660
6661   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6662   unsigned trap_opcode;
6663   if (Subtarget->isThumb())
6664     trap_opcode = ARM::tTRAP;
6665   else
6666     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6667
6668   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6669   DispatchBB->addSuccessor(TrapBB);
6670
6671   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6672   DispatchBB->addSuccessor(DispContBB);
6673
6674   // Insert and MBBs.
6675   MF->insert(MF->end(), DispatchBB);
6676   MF->insert(MF->end(), DispContBB);
6677   MF->insert(MF->end(), TrapBB);
6678
6679   // Insert code into the entry block that creates and registers the function
6680   // context.
6681   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6682
6683   MachineMemOperand *FIMMOLd =
6684     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6685                              MachineMemOperand::MOLoad |
6686                              MachineMemOperand::MOVolatile, 4, 4);
6687
6688   MachineInstrBuilder MIB;
6689   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6690
6691   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6692   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6693
6694   // Add a register mask with no preserved registers.  This results in all
6695   // registers being marked as clobbered.
6696   MIB.addRegMask(RI.getNoPreservedMask());
6697
6698   unsigned NumLPads = LPadList.size();
6699   if (Subtarget->isThumb2()) {
6700     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6701     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6702                    .addFrameIndex(FI)
6703                    .addImm(4)
6704                    .addMemOperand(FIMMOLd));
6705
6706     if (NumLPads < 256) {
6707       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6708                      .addReg(NewVReg1)
6709                      .addImm(LPadList.size()));
6710     } else {
6711       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6712       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6713                      .addImm(NumLPads & 0xFFFF));
6714
6715       unsigned VReg2 = VReg1;
6716       if ((NumLPads & 0xFFFF0000) != 0) {
6717         VReg2 = MRI->createVirtualRegister(TRC);
6718         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6719                        .addReg(VReg1)
6720                        .addImm(NumLPads >> 16));
6721       }
6722
6723       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6724                      .addReg(NewVReg1)
6725                      .addReg(VReg2));
6726     }
6727
6728     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6729       .addMBB(TrapBB)
6730       .addImm(ARMCC::HI)
6731       .addReg(ARM::CPSR);
6732
6733     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6734     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6735                    .addJumpTableIndex(MJTI)
6736                    .addImm(UId));
6737
6738     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6739     AddDefaultCC(
6740       AddDefaultPred(
6741         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6742         .addReg(NewVReg3, RegState::Kill)
6743         .addReg(NewVReg1)
6744         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6745
6746     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6747       .addReg(NewVReg4, RegState::Kill)
6748       .addReg(NewVReg1)
6749       .addJumpTableIndex(MJTI)
6750       .addImm(UId);
6751   } else if (Subtarget->isThumb()) {
6752     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6753     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6754                    .addFrameIndex(FI)
6755                    .addImm(1)
6756                    .addMemOperand(FIMMOLd));
6757
6758     if (NumLPads < 256) {
6759       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6760                      .addReg(NewVReg1)
6761                      .addImm(NumLPads));
6762     } else {
6763       MachineConstantPool *ConstantPool = MF->getConstantPool();
6764       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6765       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6766
6767       // MachineConstantPool wants an explicit alignment.
6768       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6769       if (Align == 0)
6770         Align = getDataLayout()->getTypeAllocSize(C->getType());
6771       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6772
6773       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6774       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6775                      .addReg(VReg1, RegState::Define)
6776                      .addConstantPoolIndex(Idx));
6777       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6778                      .addReg(NewVReg1)
6779                      .addReg(VReg1));
6780     }
6781
6782     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6783       .addMBB(TrapBB)
6784       .addImm(ARMCC::HI)
6785       .addReg(ARM::CPSR);
6786
6787     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6788     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6789                    .addReg(ARM::CPSR, RegState::Define)
6790                    .addReg(NewVReg1)
6791                    .addImm(2));
6792
6793     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6794     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6795                    .addJumpTableIndex(MJTI)
6796                    .addImm(UId));
6797
6798     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6799     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6800                    .addReg(ARM::CPSR, RegState::Define)
6801                    .addReg(NewVReg2, RegState::Kill)
6802                    .addReg(NewVReg3));
6803
6804     MachineMemOperand *JTMMOLd =
6805       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6806                                MachineMemOperand::MOLoad, 4, 4);
6807
6808     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6809     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6810                    .addReg(NewVReg4, RegState::Kill)
6811                    .addImm(0)
6812                    .addMemOperand(JTMMOLd));
6813
6814     unsigned NewVReg6 = NewVReg5;
6815     if (RelocM == Reloc::PIC_) {
6816       NewVReg6 = MRI->createVirtualRegister(TRC);
6817       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6818                      .addReg(ARM::CPSR, RegState::Define)
6819                      .addReg(NewVReg5, RegState::Kill)
6820                      .addReg(NewVReg3));
6821     }
6822
6823     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6824       .addReg(NewVReg6, RegState::Kill)
6825       .addJumpTableIndex(MJTI)
6826       .addImm(UId);
6827   } else {
6828     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6829     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6830                    .addFrameIndex(FI)
6831                    .addImm(4)
6832                    .addMemOperand(FIMMOLd));
6833
6834     if (NumLPads < 256) {
6835       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6836                      .addReg(NewVReg1)
6837                      .addImm(NumLPads));
6838     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6839       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6840       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6841                      .addImm(NumLPads & 0xFFFF));
6842
6843       unsigned VReg2 = VReg1;
6844       if ((NumLPads & 0xFFFF0000) != 0) {
6845         VReg2 = MRI->createVirtualRegister(TRC);
6846         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6847                        .addReg(VReg1)
6848                        .addImm(NumLPads >> 16));
6849       }
6850
6851       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6852                      .addReg(NewVReg1)
6853                      .addReg(VReg2));
6854     } else {
6855       MachineConstantPool *ConstantPool = MF->getConstantPool();
6856       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6857       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6858
6859       // MachineConstantPool wants an explicit alignment.
6860       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6861       if (Align == 0)
6862         Align = getDataLayout()->getTypeAllocSize(C->getType());
6863       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6864
6865       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6866       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6867                      .addReg(VReg1, RegState::Define)
6868                      .addConstantPoolIndex(Idx)
6869                      .addImm(0));
6870       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6871                      .addReg(NewVReg1)
6872                      .addReg(VReg1, RegState::Kill));
6873     }
6874
6875     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6876       .addMBB(TrapBB)
6877       .addImm(ARMCC::HI)
6878       .addReg(ARM::CPSR);
6879
6880     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6881     AddDefaultCC(
6882       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6883                      .addReg(NewVReg1)
6884                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6885     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6886     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6887                    .addJumpTableIndex(MJTI)
6888                    .addImm(UId));
6889
6890     MachineMemOperand *JTMMOLd =
6891       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6892                                MachineMemOperand::MOLoad, 4, 4);
6893     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6894     AddDefaultPred(
6895       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6896       .addReg(NewVReg3, RegState::Kill)
6897       .addReg(NewVReg4)
6898       .addImm(0)
6899       .addMemOperand(JTMMOLd));
6900
6901     if (RelocM == Reloc::PIC_) {
6902       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6903         .addReg(NewVReg5, RegState::Kill)
6904         .addReg(NewVReg4)
6905         .addJumpTableIndex(MJTI)
6906         .addImm(UId);
6907     } else {
6908       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6909         .addReg(NewVReg5, RegState::Kill)
6910         .addJumpTableIndex(MJTI)
6911         .addImm(UId);
6912     }
6913   }
6914
6915   // Add the jump table entries as successors to the MBB.
6916   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6917   for (std::vector<MachineBasicBlock*>::iterator
6918          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6919     MachineBasicBlock *CurMBB = *I;
6920     if (SeenMBBs.insert(CurMBB))
6921       DispContBB->addSuccessor(CurMBB);
6922   }
6923
6924   // N.B. the order the invoke BBs are processed in doesn't matter here.
6925   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6926   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6927   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6928          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6929     MachineBasicBlock *BB = *I;
6930
6931     // Remove the landing pad successor from the invoke block and replace it
6932     // with the new dispatch block.
6933     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6934                                                   BB->succ_end());
6935     while (!Successors.empty()) {
6936       MachineBasicBlock *SMBB = Successors.pop_back_val();
6937       if (SMBB->isLandingPad()) {
6938         BB->removeSuccessor(SMBB);
6939         MBBLPads.push_back(SMBB);
6940       }
6941     }
6942
6943     BB->addSuccessor(DispatchBB);
6944
6945     // Find the invoke call and mark all of the callee-saved registers as
6946     // 'implicit defined' so that they're spilled. This prevents code from
6947     // moving instructions to before the EH block, where they will never be
6948     // executed.
6949     for (MachineBasicBlock::reverse_iterator
6950            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6951       if (!II->isCall()) continue;
6952
6953       DenseMap<unsigned, bool> DefRegs;
6954       for (MachineInstr::mop_iterator
6955              OI = II->operands_begin(), OE = II->operands_end();
6956            OI != OE; ++OI) {
6957         if (!OI->isReg()) continue;
6958         DefRegs[OI->getReg()] = true;
6959       }
6960
6961       MachineInstrBuilder MIB(*MF, &*II);
6962
6963       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6964         unsigned Reg = SavedRegs[i];
6965         if (Subtarget->isThumb2() &&
6966             !ARM::tGPRRegClass.contains(Reg) &&
6967             !ARM::hGPRRegClass.contains(Reg))
6968           continue;
6969         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6970           continue;
6971         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6972           continue;
6973         if (!DefRegs[Reg])
6974           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6975       }
6976
6977       break;
6978     }
6979   }
6980
6981   // Mark all former landing pads as non-landing pads. The dispatch is the only
6982   // landing pad now.
6983   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6984          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6985     (*I)->setIsLandingPad(false);
6986
6987   // The instruction is gone now.
6988   MI->eraseFromParent();
6989
6990   return MBB;
6991 }
6992
6993 static
6994 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6995   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6996        E = MBB->succ_end(); I != E; ++I)
6997     if (*I != Succ)
6998       return *I;
6999   llvm_unreachable("Expecting a BB with two successors!");
7000 }
7001
7002 /// Return the load opcode for a given load size. If load size >= 8,
7003 /// neon opcode will be returned.
7004 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7005   if (LdSize >= 8)
7006     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7007                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7008   if (IsThumb1)
7009     return LdSize == 4 ? ARM::tLDRi
7010                        : LdSize == 2 ? ARM::tLDRHi
7011                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7012   if (IsThumb2)
7013     return LdSize == 4 ? ARM::t2LDR_POST
7014                        : LdSize == 2 ? ARM::t2LDRH_POST
7015                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7016   return LdSize == 4 ? ARM::LDR_POST_IMM
7017                      : LdSize == 2 ? ARM::LDRH_POST
7018                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7019 }
7020
7021 /// Return the store opcode for a given store size. If store size >= 8,
7022 /// neon opcode will be returned.
7023 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7024   if (StSize >= 8)
7025     return StSize == 16 ? ARM::VST1q32wb_fixed
7026                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7027   if (IsThumb1)
7028     return StSize == 4 ? ARM::tSTRi
7029                        : StSize == 2 ? ARM::tSTRHi
7030                                      : StSize == 1 ? ARM::tSTRBi : 0;
7031   if (IsThumb2)
7032     return StSize == 4 ? ARM::t2STR_POST
7033                        : StSize == 2 ? ARM::t2STRH_POST
7034                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7035   return StSize == 4 ? ARM::STR_POST_IMM
7036                      : StSize == 2 ? ARM::STRH_POST
7037                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7038 }
7039
7040 /// Emit a post-increment load operation with given size. The instructions
7041 /// will be added to BB at Pos.
7042 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7043                        const TargetInstrInfo *TII, DebugLoc dl,
7044                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7045                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7046   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7047   assert(LdOpc != 0 && "Should have a load opcode");
7048   if (LdSize >= 8) {
7049     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7050                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7051                        .addImm(0));
7052   } else if (IsThumb1) {
7053     // load + update AddrIn
7054     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7055                        .addReg(AddrIn).addImm(0));
7056     MachineInstrBuilder MIB =
7057         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7058     MIB = AddDefaultT1CC(MIB);
7059     MIB.addReg(AddrIn).addImm(LdSize);
7060     AddDefaultPred(MIB);
7061   } else if (IsThumb2) {
7062     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7063                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7064                        .addImm(LdSize));
7065   } else { // arm
7066     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7067                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7068                        .addReg(0).addImm(LdSize));
7069   }
7070 }
7071
7072 /// Emit a post-increment store operation with given size. The instructions
7073 /// will be added to BB at Pos.
7074 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7075                        const TargetInstrInfo *TII, DebugLoc dl,
7076                        unsigned StSize, unsigned Data, unsigned AddrIn,
7077                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7078   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7079   assert(StOpc != 0 && "Should have a store opcode");
7080   if (StSize >= 8) {
7081     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7082                        .addReg(AddrIn).addImm(0).addReg(Data));
7083   } else if (IsThumb1) {
7084     // store + update AddrIn
7085     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7086                        .addReg(AddrIn).addImm(0));
7087     MachineInstrBuilder MIB =
7088         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7089     MIB = AddDefaultT1CC(MIB);
7090     MIB.addReg(AddrIn).addImm(StSize);
7091     AddDefaultPred(MIB);
7092   } else if (IsThumb2) {
7093     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7094                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7095   } else { // arm
7096     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7097                        .addReg(Data).addReg(AddrIn).addReg(0)
7098                        .addImm(StSize));
7099   }
7100 }
7101
7102 MachineBasicBlock *
7103 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7104                                    MachineBasicBlock *BB) const {
7105   // This pseudo instruction has 3 operands: dst, src, size
7106   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7107   // Otherwise, we will generate unrolled scalar copies.
7108   const TargetInstrInfo *TII =
7109       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7110   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7111   MachineFunction::iterator It = BB;
7112   ++It;
7113
7114   unsigned dest = MI->getOperand(0).getReg();
7115   unsigned src = MI->getOperand(1).getReg();
7116   unsigned SizeVal = MI->getOperand(2).getImm();
7117   unsigned Align = MI->getOperand(3).getImm();
7118   DebugLoc dl = MI->getDebugLoc();
7119
7120   MachineFunction *MF = BB->getParent();
7121   MachineRegisterInfo &MRI = MF->getRegInfo();
7122   unsigned UnitSize = 0;
7123   const TargetRegisterClass *TRC = nullptr;
7124   const TargetRegisterClass *VecTRC = nullptr;
7125
7126   bool IsThumb1 = Subtarget->isThumb1Only();
7127   bool IsThumb2 = Subtarget->isThumb2();
7128
7129   if (Align & 1) {
7130     UnitSize = 1;
7131   } else if (Align & 2) {
7132     UnitSize = 2;
7133   } else {
7134     // Check whether we can use NEON instructions.
7135     if (!MF->getFunction()->getAttributes().
7136           hasAttribute(AttributeSet::FunctionIndex,
7137                        Attribute::NoImplicitFloat) &&
7138         Subtarget->hasNEON()) {
7139       if ((Align % 16 == 0) && SizeVal >= 16)
7140         UnitSize = 16;
7141       else if ((Align % 8 == 0) && SizeVal >= 8)
7142         UnitSize = 8;
7143     }
7144     // Can't use NEON instructions.
7145     if (UnitSize == 0)
7146       UnitSize = 4;
7147   }
7148
7149   // Select the correct opcode and register class for unit size load/store
7150   bool IsNeon = UnitSize >= 8;
7151   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7152                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7153   if (IsNeon)
7154     VecTRC = UnitSize == 16
7155                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7156                  : UnitSize == 8
7157                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7158                        : nullptr;
7159
7160   unsigned BytesLeft = SizeVal % UnitSize;
7161   unsigned LoopSize = SizeVal - BytesLeft;
7162
7163   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7164     // Use LDR and STR to copy.
7165     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7166     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7167     unsigned srcIn = src;
7168     unsigned destIn = dest;
7169     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7170       unsigned srcOut = MRI.createVirtualRegister(TRC);
7171       unsigned destOut = MRI.createVirtualRegister(TRC);
7172       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7173       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7174                  IsThumb1, IsThumb2);
7175       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7176                  IsThumb1, IsThumb2);
7177       srcIn = srcOut;
7178       destIn = destOut;
7179     }
7180
7181     // Handle the leftover bytes with LDRB and STRB.
7182     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7183     // [destOut] = STRB_POST(scratch, destIn, 1)
7184     for (unsigned i = 0; i < BytesLeft; i++) {
7185       unsigned srcOut = MRI.createVirtualRegister(TRC);
7186       unsigned destOut = MRI.createVirtualRegister(TRC);
7187       unsigned scratch = MRI.createVirtualRegister(TRC);
7188       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7189                  IsThumb1, IsThumb2);
7190       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7191                  IsThumb1, IsThumb2);
7192       srcIn = srcOut;
7193       destIn = destOut;
7194     }
7195     MI->eraseFromParent();   // The instruction is gone now.
7196     return BB;
7197   }
7198
7199   // Expand the pseudo op to a loop.
7200   // thisMBB:
7201   //   ...
7202   //   movw varEnd, # --> with thumb2
7203   //   movt varEnd, #
7204   //   ldrcp varEnd, idx --> without thumb2
7205   //   fallthrough --> loopMBB
7206   // loopMBB:
7207   //   PHI varPhi, varEnd, varLoop
7208   //   PHI srcPhi, src, srcLoop
7209   //   PHI destPhi, dst, destLoop
7210   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7211   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7212   //   subs varLoop, varPhi, #UnitSize
7213   //   bne loopMBB
7214   //   fallthrough --> exitMBB
7215   // exitMBB:
7216   //   epilogue to handle left-over bytes
7217   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7218   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7219   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7220   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7221   MF->insert(It, loopMBB);
7222   MF->insert(It, exitMBB);
7223
7224   // Transfer the remainder of BB and its successor edges to exitMBB.
7225   exitMBB->splice(exitMBB->begin(), BB,
7226                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7227   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7228
7229   // Load an immediate to varEnd.
7230   unsigned varEnd = MRI.createVirtualRegister(TRC);
7231   if (IsThumb2) {
7232     unsigned Vtmp = varEnd;
7233     if ((LoopSize & 0xFFFF0000) != 0)
7234       Vtmp = MRI.createVirtualRegister(TRC);
7235     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7236                        .addImm(LoopSize & 0xFFFF));
7237
7238     if ((LoopSize & 0xFFFF0000) != 0)
7239       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7240                          .addReg(Vtmp).addImm(LoopSize >> 16));
7241   } else {
7242     MachineConstantPool *ConstantPool = MF->getConstantPool();
7243     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7244     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7245
7246     // MachineConstantPool wants an explicit alignment.
7247     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7248     if (Align == 0)
7249       Align = getDataLayout()->getTypeAllocSize(C->getType());
7250     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7251
7252     if (IsThumb1)
7253       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7254           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7255     else
7256       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7257           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7258   }
7259   BB->addSuccessor(loopMBB);
7260
7261   // Generate the loop body:
7262   //   varPhi = PHI(varLoop, varEnd)
7263   //   srcPhi = PHI(srcLoop, src)
7264   //   destPhi = PHI(destLoop, dst)
7265   MachineBasicBlock *entryBB = BB;
7266   BB = loopMBB;
7267   unsigned varLoop = MRI.createVirtualRegister(TRC);
7268   unsigned varPhi = MRI.createVirtualRegister(TRC);
7269   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7270   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7271   unsigned destLoop = MRI.createVirtualRegister(TRC);
7272   unsigned destPhi = MRI.createVirtualRegister(TRC);
7273
7274   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7275     .addReg(varLoop).addMBB(loopMBB)
7276     .addReg(varEnd).addMBB(entryBB);
7277   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7278     .addReg(srcLoop).addMBB(loopMBB)
7279     .addReg(src).addMBB(entryBB);
7280   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7281     .addReg(destLoop).addMBB(loopMBB)
7282     .addReg(dest).addMBB(entryBB);
7283
7284   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7285   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7286   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7287   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7288              IsThumb1, IsThumb2);
7289   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7290              IsThumb1, IsThumb2);
7291
7292   // Decrement loop variable by UnitSize.
7293   if (IsThumb1) {
7294     MachineInstrBuilder MIB =
7295         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7296     MIB = AddDefaultT1CC(MIB);
7297     MIB.addReg(varPhi).addImm(UnitSize);
7298     AddDefaultPred(MIB);
7299   } else {
7300     MachineInstrBuilder MIB =
7301         BuildMI(*BB, BB->end(), dl,
7302                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7303     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7304     MIB->getOperand(5).setReg(ARM::CPSR);
7305     MIB->getOperand(5).setIsDef(true);
7306   }
7307   BuildMI(*BB, BB->end(), dl,
7308           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7309       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7310
7311   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7312   BB->addSuccessor(loopMBB);
7313   BB->addSuccessor(exitMBB);
7314
7315   // Add epilogue to handle BytesLeft.
7316   BB = exitMBB;
7317   MachineInstr *StartOfExit = exitMBB->begin();
7318
7319   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7320   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7321   unsigned srcIn = srcLoop;
7322   unsigned destIn = destLoop;
7323   for (unsigned i = 0; i < BytesLeft; i++) {
7324     unsigned srcOut = MRI.createVirtualRegister(TRC);
7325     unsigned destOut = MRI.createVirtualRegister(TRC);
7326     unsigned scratch = MRI.createVirtualRegister(TRC);
7327     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7328                IsThumb1, IsThumb2);
7329     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7330                IsThumb1, IsThumb2);
7331     srcIn = srcOut;
7332     destIn = destOut;
7333   }
7334
7335   MI->eraseFromParent();   // The instruction is gone now.
7336   return BB;
7337 }
7338
7339 MachineBasicBlock *
7340 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7341                                        MachineBasicBlock *MBB) const {
7342   const TargetMachine &TM = getTargetMachine();
7343   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7344   DebugLoc DL = MI->getDebugLoc();
7345
7346   assert(Subtarget->isTargetWindows() &&
7347          "__chkstk is only supported on Windows");
7348   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7349
7350   // __chkstk takes the number of words to allocate on the stack in R4, and
7351   // returns the stack adjustment in number of bytes in R4.  This will not
7352   // clober any other registers (other than the obvious lr).
7353   //
7354   // Although, technically, IP should be considered a register which may be
7355   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7356   // thumb-2 environment, so there is no interworking required.  As a result, we
7357   // do not expect a veneer to be emitted by the linker, clobbering IP.
7358   //
7359   // Each module receives its own copy of __chkstk, so no import thunk is
7360   // required, again, ensuring that IP is not clobbered.
7361   //
7362   // Finally, although some linkers may theoretically provide a trampoline for
7363   // out of range calls (which is quite common due to a 32M range limitation of
7364   // branches for Thumb), we can generate the long-call version via
7365   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7366   // IP.
7367
7368   switch (TM.getCodeModel()) {
7369   case CodeModel::Small:
7370   case CodeModel::Medium:
7371   case CodeModel::Default:
7372   case CodeModel::Kernel:
7373     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7374       .addImm((unsigned)ARMCC::AL).addReg(0)
7375       .addExternalSymbol("__chkstk")
7376       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7377       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7378       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7379     break;
7380   case CodeModel::Large:
7381   case CodeModel::JITDefault: {
7382     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7383     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7384
7385     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7386       .addExternalSymbol("__chkstk");
7387     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7388       .addImm((unsigned)ARMCC::AL).addReg(0)
7389       .addReg(Reg, RegState::Kill)
7390       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7391       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7392       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7393     break;
7394   }
7395   }
7396
7397   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7398                                       ARM::SP)
7399                               .addReg(ARM::SP).addReg(ARM::R4)));
7400
7401   MI->eraseFromParent();
7402   return MBB;
7403 }
7404
7405 MachineBasicBlock *
7406 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7407                                                MachineBasicBlock *BB) const {
7408   const TargetInstrInfo *TII =
7409       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7410   DebugLoc dl = MI->getDebugLoc();
7411   bool isThumb2 = Subtarget->isThumb2();
7412   switch (MI->getOpcode()) {
7413   default: {
7414     MI->dump();
7415     llvm_unreachable("Unexpected instr type to insert");
7416   }
7417   // The Thumb2 pre-indexed stores have the same MI operands, they just
7418   // define them differently in the .td files from the isel patterns, so
7419   // they need pseudos.
7420   case ARM::t2STR_preidx:
7421     MI->setDesc(TII->get(ARM::t2STR_PRE));
7422     return BB;
7423   case ARM::t2STRB_preidx:
7424     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7425     return BB;
7426   case ARM::t2STRH_preidx:
7427     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7428     return BB;
7429
7430   case ARM::STRi_preidx:
7431   case ARM::STRBi_preidx: {
7432     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7433       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7434     // Decode the offset.
7435     unsigned Offset = MI->getOperand(4).getImm();
7436     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7437     Offset = ARM_AM::getAM2Offset(Offset);
7438     if (isSub)
7439       Offset = -Offset;
7440
7441     MachineMemOperand *MMO = *MI->memoperands_begin();
7442     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7443       .addOperand(MI->getOperand(0))  // Rn_wb
7444       .addOperand(MI->getOperand(1))  // Rt
7445       .addOperand(MI->getOperand(2))  // Rn
7446       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7447       .addOperand(MI->getOperand(5))  // pred
7448       .addOperand(MI->getOperand(6))
7449       .addMemOperand(MMO);
7450     MI->eraseFromParent();
7451     return BB;
7452   }
7453   case ARM::STRr_preidx:
7454   case ARM::STRBr_preidx:
7455   case ARM::STRH_preidx: {
7456     unsigned NewOpc;
7457     switch (MI->getOpcode()) {
7458     default: llvm_unreachable("unexpected opcode!");
7459     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7460     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7461     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7462     }
7463     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7464     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7465       MIB.addOperand(MI->getOperand(i));
7466     MI->eraseFromParent();
7467     return BB;
7468   }
7469
7470   case ARM::tMOVCCr_pseudo: {
7471     // To "insert" a SELECT_CC instruction, we actually have to insert the
7472     // diamond control-flow pattern.  The incoming instruction knows the
7473     // destination vreg to set, the condition code register to branch on, the
7474     // true/false values to select between, and a branch opcode to use.
7475     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7476     MachineFunction::iterator It = BB;
7477     ++It;
7478
7479     //  thisMBB:
7480     //  ...
7481     //   TrueVal = ...
7482     //   cmpTY ccX, r1, r2
7483     //   bCC copy1MBB
7484     //   fallthrough --> copy0MBB
7485     MachineBasicBlock *thisMBB  = BB;
7486     MachineFunction *F = BB->getParent();
7487     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7488     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7489     F->insert(It, copy0MBB);
7490     F->insert(It, sinkMBB);
7491
7492     // Transfer the remainder of BB and its successor edges to sinkMBB.
7493     sinkMBB->splice(sinkMBB->begin(), BB,
7494                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7495     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7496
7497     BB->addSuccessor(copy0MBB);
7498     BB->addSuccessor(sinkMBB);
7499
7500     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7501       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7502
7503     //  copy0MBB:
7504     //   %FalseValue = ...
7505     //   # fallthrough to sinkMBB
7506     BB = copy0MBB;
7507
7508     // Update machine-CFG edges
7509     BB->addSuccessor(sinkMBB);
7510
7511     //  sinkMBB:
7512     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7513     //  ...
7514     BB = sinkMBB;
7515     BuildMI(*BB, BB->begin(), dl,
7516             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7517       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7518       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7519
7520     MI->eraseFromParent();   // The pseudo instruction is gone now.
7521     return BB;
7522   }
7523
7524   case ARM::BCCi64:
7525   case ARM::BCCZi64: {
7526     // If there is an unconditional branch to the other successor, remove it.
7527     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7528
7529     // Compare both parts that make up the double comparison separately for
7530     // equality.
7531     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7532
7533     unsigned LHS1 = MI->getOperand(1).getReg();
7534     unsigned LHS2 = MI->getOperand(2).getReg();
7535     if (RHSisZero) {
7536       AddDefaultPred(BuildMI(BB, dl,
7537                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7538                      .addReg(LHS1).addImm(0));
7539       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7540         .addReg(LHS2).addImm(0)
7541         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7542     } else {
7543       unsigned RHS1 = MI->getOperand(3).getReg();
7544       unsigned RHS2 = MI->getOperand(4).getReg();
7545       AddDefaultPred(BuildMI(BB, dl,
7546                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7547                      .addReg(LHS1).addReg(RHS1));
7548       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7549         .addReg(LHS2).addReg(RHS2)
7550         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7551     }
7552
7553     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7554     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7555     if (MI->getOperand(0).getImm() == ARMCC::NE)
7556       std::swap(destMBB, exitMBB);
7557
7558     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7559       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7560     if (isThumb2)
7561       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7562     else
7563       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7564
7565     MI->eraseFromParent();   // The pseudo instruction is gone now.
7566     return BB;
7567   }
7568
7569   case ARM::Int_eh_sjlj_setjmp:
7570   case ARM::Int_eh_sjlj_setjmp_nofp:
7571   case ARM::tInt_eh_sjlj_setjmp:
7572   case ARM::t2Int_eh_sjlj_setjmp:
7573   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7574     EmitSjLjDispatchBlock(MI, BB);
7575     return BB;
7576
7577   case ARM::ABS:
7578   case ARM::t2ABS: {
7579     // To insert an ABS instruction, we have to insert the
7580     // diamond control-flow pattern.  The incoming instruction knows the
7581     // source vreg to test against 0, the destination vreg to set,
7582     // the condition code register to branch on, the
7583     // true/false values to select between, and a branch opcode to use.
7584     // It transforms
7585     //     V1 = ABS V0
7586     // into
7587     //     V2 = MOVS V0
7588     //     BCC                      (branch to SinkBB if V0 >= 0)
7589     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7590     //     SinkBB: V1 = PHI(V2, V3)
7591     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7592     MachineFunction::iterator BBI = BB;
7593     ++BBI;
7594     MachineFunction *Fn = BB->getParent();
7595     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7596     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7597     Fn->insert(BBI, RSBBB);
7598     Fn->insert(BBI, SinkBB);
7599
7600     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7601     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7602     bool isThumb2 = Subtarget->isThumb2();
7603     MachineRegisterInfo &MRI = Fn->getRegInfo();
7604     // In Thumb mode S must not be specified if source register is the SP or
7605     // PC and if destination register is the SP, so restrict register class
7606     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7607       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7608       (const TargetRegisterClass*)&ARM::GPRRegClass);
7609
7610     // Transfer the remainder of BB and its successor edges to sinkMBB.
7611     SinkBB->splice(SinkBB->begin(), BB,
7612                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7613     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7614
7615     BB->addSuccessor(RSBBB);
7616     BB->addSuccessor(SinkBB);
7617
7618     // fall through to SinkMBB
7619     RSBBB->addSuccessor(SinkBB);
7620
7621     // insert a cmp at the end of BB
7622     AddDefaultPred(BuildMI(BB, dl,
7623                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7624                    .addReg(ABSSrcReg).addImm(0));
7625
7626     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7627     BuildMI(BB, dl,
7628       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7629       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7630
7631     // insert rsbri in RSBBB
7632     // Note: BCC and rsbri will be converted into predicated rsbmi
7633     // by if-conversion pass
7634     BuildMI(*RSBBB, RSBBB->begin(), dl,
7635       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7636       .addReg(ABSSrcReg, RegState::Kill)
7637       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7638
7639     // insert PHI in SinkBB,
7640     // reuse ABSDstReg to not change uses of ABS instruction
7641     BuildMI(*SinkBB, SinkBB->begin(), dl,
7642       TII->get(ARM::PHI), ABSDstReg)
7643       .addReg(NewRsbDstReg).addMBB(RSBBB)
7644       .addReg(ABSSrcReg).addMBB(BB);
7645
7646     // remove ABS instruction
7647     MI->eraseFromParent();
7648
7649     // return last added BB
7650     return SinkBB;
7651   }
7652   case ARM::COPY_STRUCT_BYVAL_I32:
7653     ++NumLoopByVals;
7654     return EmitStructByval(MI, BB);
7655   case ARM::WIN__CHKSTK:
7656     return EmitLowered__chkstk(MI, BB);
7657   }
7658 }
7659
7660 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7661                                                       SDNode *Node) const {
7662   if (!MI->hasPostISelHook()) {
7663     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7664            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7665     return;
7666   }
7667
7668   const MCInstrDesc *MCID = &MI->getDesc();
7669   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7670   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7671   // operand is still set to noreg. If needed, set the optional operand's
7672   // register to CPSR, and remove the redundant implicit def.
7673   //
7674   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7675
7676   // Rename pseudo opcodes.
7677   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7678   if (NewOpc) {
7679     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7680         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7681     MCID = &TII->get(NewOpc);
7682
7683     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7684            "converted opcode should be the same except for cc_out");
7685
7686     MI->setDesc(*MCID);
7687
7688     // Add the optional cc_out operand
7689     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7690   }
7691   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7692
7693   // Any ARM instruction that sets the 's' bit should specify an optional
7694   // "cc_out" operand in the last operand position.
7695   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7696     assert(!NewOpc && "Optional cc_out operand required");
7697     return;
7698   }
7699   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7700   // since we already have an optional CPSR def.
7701   bool definesCPSR = false;
7702   bool deadCPSR = false;
7703   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7704        i != e; ++i) {
7705     const MachineOperand &MO = MI->getOperand(i);
7706     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7707       definesCPSR = true;
7708       if (MO.isDead())
7709         deadCPSR = true;
7710       MI->RemoveOperand(i);
7711       break;
7712     }
7713   }
7714   if (!definesCPSR) {
7715     assert(!NewOpc && "Optional cc_out operand required");
7716     return;
7717   }
7718   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7719   if (deadCPSR) {
7720     assert(!MI->getOperand(ccOutIdx).getReg() &&
7721            "expect uninitialized optional cc_out operand");
7722     return;
7723   }
7724
7725   // If this instruction was defined with an optional CPSR def and its dag node
7726   // had a live implicit CPSR def, then activate the optional CPSR def.
7727   MachineOperand &MO = MI->getOperand(ccOutIdx);
7728   MO.setReg(ARM::CPSR);
7729   MO.setIsDef(true);
7730 }
7731
7732 //===----------------------------------------------------------------------===//
7733 //                           ARM Optimization Hooks
7734 //===----------------------------------------------------------------------===//
7735
7736 // Helper function that checks if N is a null or all ones constant.
7737 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7738   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7739   if (!C)
7740     return false;
7741   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7742 }
7743
7744 // Return true if N is conditionally 0 or all ones.
7745 // Detects these expressions where cc is an i1 value:
7746 //
7747 //   (select cc 0, y)   [AllOnes=0]
7748 //   (select cc y, 0)   [AllOnes=0]
7749 //   (zext cc)          [AllOnes=0]
7750 //   (sext cc)          [AllOnes=0/1]
7751 //   (select cc -1, y)  [AllOnes=1]
7752 //   (select cc y, -1)  [AllOnes=1]
7753 //
7754 // Invert is set when N is the null/all ones constant when CC is false.
7755 // OtherOp is set to the alternative value of N.
7756 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7757                                        SDValue &CC, bool &Invert,
7758                                        SDValue &OtherOp,
7759                                        SelectionDAG &DAG) {
7760   switch (N->getOpcode()) {
7761   default: return false;
7762   case ISD::SELECT: {
7763     CC = N->getOperand(0);
7764     SDValue N1 = N->getOperand(1);
7765     SDValue N2 = N->getOperand(2);
7766     if (isZeroOrAllOnes(N1, AllOnes)) {
7767       Invert = false;
7768       OtherOp = N2;
7769       return true;
7770     }
7771     if (isZeroOrAllOnes(N2, AllOnes)) {
7772       Invert = true;
7773       OtherOp = N1;
7774       return true;
7775     }
7776     return false;
7777   }
7778   case ISD::ZERO_EXTEND:
7779     // (zext cc) can never be the all ones value.
7780     if (AllOnes)
7781       return false;
7782     // Fall through.
7783   case ISD::SIGN_EXTEND: {
7784     EVT VT = N->getValueType(0);
7785     CC = N->getOperand(0);
7786     if (CC.getValueType() != MVT::i1)
7787       return false;
7788     Invert = !AllOnes;
7789     if (AllOnes)
7790       // When looking for an AllOnes constant, N is an sext, and the 'other'
7791       // value is 0.
7792       OtherOp = DAG.getConstant(0, VT);
7793     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7794       // When looking for a 0 constant, N can be zext or sext.
7795       OtherOp = DAG.getConstant(1, VT);
7796     else
7797       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7798     return true;
7799   }
7800   }
7801 }
7802
7803 // Combine a constant select operand into its use:
7804 //
7805 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7806 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7807 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7808 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7809 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7810 //
7811 // The transform is rejected if the select doesn't have a constant operand that
7812 // is null, or all ones when AllOnes is set.
7813 //
7814 // Also recognize sext/zext from i1:
7815 //
7816 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7817 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7818 //
7819 // These transformations eventually create predicated instructions.
7820 //
7821 // @param N       The node to transform.
7822 // @param Slct    The N operand that is a select.
7823 // @param OtherOp The other N operand (x above).
7824 // @param DCI     Context.
7825 // @param AllOnes Require the select constant to be all ones instead of null.
7826 // @returns The new node, or SDValue() on failure.
7827 static
7828 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7829                             TargetLowering::DAGCombinerInfo &DCI,
7830                             bool AllOnes = false) {
7831   SelectionDAG &DAG = DCI.DAG;
7832   EVT VT = N->getValueType(0);
7833   SDValue NonConstantVal;
7834   SDValue CCOp;
7835   bool SwapSelectOps;
7836   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7837                                   NonConstantVal, DAG))
7838     return SDValue();
7839
7840   // Slct is now know to be the desired identity constant when CC is true.
7841   SDValue TrueVal = OtherOp;
7842   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7843                                  OtherOp, NonConstantVal);
7844   // Unless SwapSelectOps says CC should be false.
7845   if (SwapSelectOps)
7846     std::swap(TrueVal, FalseVal);
7847
7848   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7849                      CCOp, TrueVal, FalseVal);
7850 }
7851
7852 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7853 static
7854 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7855                                        TargetLowering::DAGCombinerInfo &DCI) {
7856   SDValue N0 = N->getOperand(0);
7857   SDValue N1 = N->getOperand(1);
7858   if (N0.getNode()->hasOneUse()) {
7859     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7860     if (Result.getNode())
7861       return Result;
7862   }
7863   if (N1.getNode()->hasOneUse()) {
7864     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7865     if (Result.getNode())
7866       return Result;
7867   }
7868   return SDValue();
7869 }
7870
7871 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7872 // (only after legalization).
7873 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7874                                  TargetLowering::DAGCombinerInfo &DCI,
7875                                  const ARMSubtarget *Subtarget) {
7876
7877   // Only perform optimization if after legalize, and if NEON is available. We
7878   // also expected both operands to be BUILD_VECTORs.
7879   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7880       || N0.getOpcode() != ISD::BUILD_VECTOR
7881       || N1.getOpcode() != ISD::BUILD_VECTOR)
7882     return SDValue();
7883
7884   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7885   EVT VT = N->getValueType(0);
7886   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7887     return SDValue();
7888
7889   // Check that the vector operands are of the right form.
7890   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7891   // operands, where N is the size of the formed vector.
7892   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7893   // index such that we have a pair wise add pattern.
7894
7895   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7896   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7897     return SDValue();
7898   SDValue Vec = N0->getOperand(0)->getOperand(0);
7899   SDNode *V = Vec.getNode();
7900   unsigned nextIndex = 0;
7901
7902   // For each operands to the ADD which are BUILD_VECTORs,
7903   // check to see if each of their operands are an EXTRACT_VECTOR with
7904   // the same vector and appropriate index.
7905   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7906     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7907         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7908
7909       SDValue ExtVec0 = N0->getOperand(i);
7910       SDValue ExtVec1 = N1->getOperand(i);
7911
7912       // First operand is the vector, verify its the same.
7913       if (V != ExtVec0->getOperand(0).getNode() ||
7914           V != ExtVec1->getOperand(0).getNode())
7915         return SDValue();
7916
7917       // Second is the constant, verify its correct.
7918       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7919       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7920
7921       // For the constant, we want to see all the even or all the odd.
7922       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7923           || C1->getZExtValue() != nextIndex+1)
7924         return SDValue();
7925
7926       // Increment index.
7927       nextIndex+=2;
7928     } else
7929       return SDValue();
7930   }
7931
7932   // Create VPADDL node.
7933   SelectionDAG &DAG = DCI.DAG;
7934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7935
7936   // Build operand list.
7937   SmallVector<SDValue, 8> Ops;
7938   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7939                                 TLI.getPointerTy()));
7940
7941   // Input is the vector.
7942   Ops.push_back(Vec);
7943
7944   // Get widened type and narrowed type.
7945   MVT widenType;
7946   unsigned numElem = VT.getVectorNumElements();
7947   
7948   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7949   switch (inputLaneType.getSimpleVT().SimpleTy) {
7950     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7951     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7952     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7953     default:
7954       llvm_unreachable("Invalid vector element type for padd optimization.");
7955   }
7956
7957   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7958   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7959   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7960 }
7961
7962 static SDValue findMUL_LOHI(SDValue V) {
7963   if (V->getOpcode() == ISD::UMUL_LOHI ||
7964       V->getOpcode() == ISD::SMUL_LOHI)
7965     return V;
7966   return SDValue();
7967 }
7968
7969 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7970                                      TargetLowering::DAGCombinerInfo &DCI,
7971                                      const ARMSubtarget *Subtarget) {
7972
7973   if (Subtarget->isThumb1Only()) return SDValue();
7974
7975   // Only perform the checks after legalize when the pattern is available.
7976   if (DCI.isBeforeLegalize()) return SDValue();
7977
7978   // Look for multiply add opportunities.
7979   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7980   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7981   // a glue link from the first add to the second add.
7982   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7983   // a S/UMLAL instruction.
7984   //          loAdd   UMUL_LOHI
7985   //            \    / :lo    \ :hi
7986   //             \  /          \          [no multiline comment]
7987   //              ADDC         |  hiAdd
7988   //                 \ :glue  /  /
7989   //                  \      /  /
7990   //                    ADDE
7991   //
7992   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7993   SDValue AddcOp0 = AddcNode->getOperand(0);
7994   SDValue AddcOp1 = AddcNode->getOperand(1);
7995
7996   // Check if the two operands are from the same mul_lohi node.
7997   if (AddcOp0.getNode() == AddcOp1.getNode())
7998     return SDValue();
7999
8000   assert(AddcNode->getNumValues() == 2 &&
8001          AddcNode->getValueType(0) == MVT::i32 &&
8002          "Expect ADDC with two result values. First: i32");
8003
8004   // Check that we have a glued ADDC node.
8005   if (AddcNode->getValueType(1) != MVT::Glue)
8006     return SDValue();
8007
8008   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8009   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8010       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8011       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8012       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8013     return SDValue();
8014
8015   // Look for the glued ADDE.
8016   SDNode* AddeNode = AddcNode->getGluedUser();
8017   if (!AddeNode)
8018     return SDValue();
8019
8020   // Make sure it is really an ADDE.
8021   if (AddeNode->getOpcode() != ISD::ADDE)
8022     return SDValue();
8023
8024   assert(AddeNode->getNumOperands() == 3 &&
8025          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8026          "ADDE node has the wrong inputs");
8027
8028   // Check for the triangle shape.
8029   SDValue AddeOp0 = AddeNode->getOperand(0);
8030   SDValue AddeOp1 = AddeNode->getOperand(1);
8031
8032   // Make sure that the ADDE operands are not coming from the same node.
8033   if (AddeOp0.getNode() == AddeOp1.getNode())
8034     return SDValue();
8035
8036   // Find the MUL_LOHI node walking up ADDE's operands.
8037   bool IsLeftOperandMUL = false;
8038   SDValue MULOp = findMUL_LOHI(AddeOp0);
8039   if (MULOp == SDValue())
8040    MULOp = findMUL_LOHI(AddeOp1);
8041   else
8042     IsLeftOperandMUL = true;
8043   if (MULOp == SDValue())
8044      return SDValue();
8045
8046   // Figure out the right opcode.
8047   unsigned Opc = MULOp->getOpcode();
8048   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8049
8050   // Figure out the high and low input values to the MLAL node.
8051   SDValue* HiMul = &MULOp;
8052   SDValue* HiAdd = nullptr;
8053   SDValue* LoMul = nullptr;
8054   SDValue* LowAdd = nullptr;
8055
8056   if (IsLeftOperandMUL)
8057     HiAdd = &AddeOp1;
8058   else
8059     HiAdd = &AddeOp0;
8060
8061
8062   if (AddcOp0->getOpcode() == Opc) {
8063     LoMul = &AddcOp0;
8064     LowAdd = &AddcOp1;
8065   }
8066   if (AddcOp1->getOpcode() == Opc) {
8067     LoMul = &AddcOp1;
8068     LowAdd = &AddcOp0;
8069   }
8070
8071   if (!LoMul)
8072     return SDValue();
8073
8074   if (LoMul->getNode() != HiMul->getNode())
8075     return SDValue();
8076
8077   // Create the merged node.
8078   SelectionDAG &DAG = DCI.DAG;
8079
8080   // Build operand list.
8081   SmallVector<SDValue, 8> Ops;
8082   Ops.push_back(LoMul->getOperand(0));
8083   Ops.push_back(LoMul->getOperand(1));
8084   Ops.push_back(*LowAdd);
8085   Ops.push_back(*HiAdd);
8086
8087   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8088                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8089
8090   // Replace the ADDs' nodes uses by the MLA node's values.
8091   SDValue HiMLALResult(MLALNode.getNode(), 1);
8092   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8093
8094   SDValue LoMLALResult(MLALNode.getNode(), 0);
8095   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8096
8097   // Return original node to notify the driver to stop replacing.
8098   SDValue resNode(AddcNode, 0);
8099   return resNode;
8100 }
8101
8102 /// PerformADDCCombine - Target-specific dag combine transform from
8103 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8104 static SDValue PerformADDCCombine(SDNode *N,
8105                                  TargetLowering::DAGCombinerInfo &DCI,
8106                                  const ARMSubtarget *Subtarget) {
8107
8108   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8109
8110 }
8111
8112 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8113 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8114 /// called with the default operands, and if that fails, with commuted
8115 /// operands.
8116 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8117                                           TargetLowering::DAGCombinerInfo &DCI,
8118                                           const ARMSubtarget *Subtarget){
8119
8120   // Attempt to create vpaddl for this add.
8121   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8122   if (Result.getNode())
8123     return Result;
8124
8125   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8126   if (N0.getNode()->hasOneUse()) {
8127     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8128     if (Result.getNode()) return Result;
8129   }
8130   return SDValue();
8131 }
8132
8133 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8134 ///
8135 static SDValue PerformADDCombine(SDNode *N,
8136                                  TargetLowering::DAGCombinerInfo &DCI,
8137                                  const ARMSubtarget *Subtarget) {
8138   SDValue N0 = N->getOperand(0);
8139   SDValue N1 = N->getOperand(1);
8140
8141   // First try with the default operand order.
8142   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8143   if (Result.getNode())
8144     return Result;
8145
8146   // If that didn't work, try again with the operands commuted.
8147   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8148 }
8149
8150 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8151 ///
8152 static SDValue PerformSUBCombine(SDNode *N,
8153                                  TargetLowering::DAGCombinerInfo &DCI) {
8154   SDValue N0 = N->getOperand(0);
8155   SDValue N1 = N->getOperand(1);
8156
8157   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8158   if (N1.getNode()->hasOneUse()) {
8159     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8160     if (Result.getNode()) return Result;
8161   }
8162
8163   return SDValue();
8164 }
8165
8166 /// PerformVMULCombine
8167 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8168 /// special multiplier accumulator forwarding.
8169 ///   vmul d3, d0, d2
8170 ///   vmla d3, d1, d2
8171 /// is faster than
8172 ///   vadd d3, d0, d1
8173 ///   vmul d3, d3, d2
8174 //  However, for (A + B) * (A + B),
8175 //    vadd d2, d0, d1
8176 //    vmul d3, d0, d2
8177 //    vmla d3, d1, d2
8178 //  is slower than
8179 //    vadd d2, d0, d1
8180 //    vmul d3, d2, d2
8181 static SDValue PerformVMULCombine(SDNode *N,
8182                                   TargetLowering::DAGCombinerInfo &DCI,
8183                                   const ARMSubtarget *Subtarget) {
8184   if (!Subtarget->hasVMLxForwarding())
8185     return SDValue();
8186
8187   SelectionDAG &DAG = DCI.DAG;
8188   SDValue N0 = N->getOperand(0);
8189   SDValue N1 = N->getOperand(1);
8190   unsigned Opcode = N0.getOpcode();
8191   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8192       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8193     Opcode = N1.getOpcode();
8194     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8195         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8196       return SDValue();
8197     std::swap(N0, N1);
8198   }
8199
8200   if (N0 == N1)
8201     return SDValue();
8202
8203   EVT VT = N->getValueType(0);
8204   SDLoc DL(N);
8205   SDValue N00 = N0->getOperand(0);
8206   SDValue N01 = N0->getOperand(1);
8207   return DAG.getNode(Opcode, DL, VT,
8208                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8209                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8210 }
8211
8212 static SDValue PerformMULCombine(SDNode *N,
8213                                  TargetLowering::DAGCombinerInfo &DCI,
8214                                  const ARMSubtarget *Subtarget) {
8215   SelectionDAG &DAG = DCI.DAG;
8216
8217   if (Subtarget->isThumb1Only())
8218     return SDValue();
8219
8220   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8221     return SDValue();
8222
8223   EVT VT = N->getValueType(0);
8224   if (VT.is64BitVector() || VT.is128BitVector())
8225     return PerformVMULCombine(N, DCI, Subtarget);
8226   if (VT != MVT::i32)
8227     return SDValue();
8228
8229   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8230   if (!C)
8231     return SDValue();
8232
8233   int64_t MulAmt = C->getSExtValue();
8234   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8235
8236   ShiftAmt = ShiftAmt & (32 - 1);
8237   SDValue V = N->getOperand(0);
8238   SDLoc DL(N);
8239
8240   SDValue Res;
8241   MulAmt >>= ShiftAmt;
8242
8243   if (MulAmt >= 0) {
8244     if (isPowerOf2_32(MulAmt - 1)) {
8245       // (mul x, 2^N + 1) => (add (shl x, N), x)
8246       Res = DAG.getNode(ISD::ADD, DL, VT,
8247                         V,
8248                         DAG.getNode(ISD::SHL, DL, VT,
8249                                     V,
8250                                     DAG.getConstant(Log2_32(MulAmt - 1),
8251                                                     MVT::i32)));
8252     } else if (isPowerOf2_32(MulAmt + 1)) {
8253       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8254       Res = DAG.getNode(ISD::SUB, DL, VT,
8255                         DAG.getNode(ISD::SHL, DL, VT,
8256                                     V,
8257                                     DAG.getConstant(Log2_32(MulAmt + 1),
8258                                                     MVT::i32)),
8259                         V);
8260     } else
8261       return SDValue();
8262   } else {
8263     uint64_t MulAmtAbs = -MulAmt;
8264     if (isPowerOf2_32(MulAmtAbs + 1)) {
8265       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8266       Res = DAG.getNode(ISD::SUB, DL, VT,
8267                         V,
8268                         DAG.getNode(ISD::SHL, DL, VT,
8269                                     V,
8270                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8271                                                     MVT::i32)));
8272     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8273       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8274       Res = DAG.getNode(ISD::ADD, DL, VT,
8275                         V,
8276                         DAG.getNode(ISD::SHL, DL, VT,
8277                                     V,
8278                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8279                                                     MVT::i32)));
8280       Res = DAG.getNode(ISD::SUB, DL, VT,
8281                         DAG.getConstant(0, MVT::i32),Res);
8282
8283     } else
8284       return SDValue();
8285   }
8286
8287   if (ShiftAmt != 0)
8288     Res = DAG.getNode(ISD::SHL, DL, VT,
8289                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8290
8291   // Do not add new nodes to DAG combiner worklist.
8292   DCI.CombineTo(N, Res, false);
8293   return SDValue();
8294 }
8295
8296 static SDValue PerformANDCombine(SDNode *N,
8297                                  TargetLowering::DAGCombinerInfo &DCI,
8298                                  const ARMSubtarget *Subtarget) {
8299
8300   // Attempt to use immediate-form VBIC
8301   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8302   SDLoc dl(N);
8303   EVT VT = N->getValueType(0);
8304   SelectionDAG &DAG = DCI.DAG;
8305
8306   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8307     return SDValue();
8308
8309   APInt SplatBits, SplatUndef;
8310   unsigned SplatBitSize;
8311   bool HasAnyUndefs;
8312   if (BVN &&
8313       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8314     if (SplatBitSize <= 64) {
8315       EVT VbicVT;
8316       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8317                                       SplatUndef.getZExtValue(), SplatBitSize,
8318                                       DAG, VbicVT, VT.is128BitVector(),
8319                                       OtherModImm);
8320       if (Val.getNode()) {
8321         SDValue Input =
8322           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8323         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8324         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8325       }
8326     }
8327   }
8328
8329   if (!Subtarget->isThumb1Only()) {
8330     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8331     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8332     if (Result.getNode())
8333       return Result;
8334   }
8335
8336   return SDValue();
8337 }
8338
8339 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8340 static SDValue PerformORCombine(SDNode *N,
8341                                 TargetLowering::DAGCombinerInfo &DCI,
8342                                 const ARMSubtarget *Subtarget) {
8343   // Attempt to use immediate-form VORR
8344   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8345   SDLoc dl(N);
8346   EVT VT = N->getValueType(0);
8347   SelectionDAG &DAG = DCI.DAG;
8348
8349   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8350     return SDValue();
8351
8352   APInt SplatBits, SplatUndef;
8353   unsigned SplatBitSize;
8354   bool HasAnyUndefs;
8355   if (BVN && Subtarget->hasNEON() &&
8356       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8357     if (SplatBitSize <= 64) {
8358       EVT VorrVT;
8359       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8360                                       SplatUndef.getZExtValue(), SplatBitSize,
8361                                       DAG, VorrVT, VT.is128BitVector(),
8362                                       OtherModImm);
8363       if (Val.getNode()) {
8364         SDValue Input =
8365           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8366         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8367         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8368       }
8369     }
8370   }
8371
8372   if (!Subtarget->isThumb1Only()) {
8373     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8374     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8375     if (Result.getNode())
8376       return Result;
8377   }
8378
8379   // The code below optimizes (or (and X, Y), Z).
8380   // The AND operand needs to have a single user to make these optimizations
8381   // profitable.
8382   SDValue N0 = N->getOperand(0);
8383   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8384     return SDValue();
8385   SDValue N1 = N->getOperand(1);
8386
8387   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8388   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8389       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8390     APInt SplatUndef;
8391     unsigned SplatBitSize;
8392     bool HasAnyUndefs;
8393
8394     APInt SplatBits0, SplatBits1;
8395     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8396     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8397     // Ensure that the second operand of both ands are constants
8398     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8399                                       HasAnyUndefs) && !HasAnyUndefs) {
8400         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8401                                           HasAnyUndefs) && !HasAnyUndefs) {
8402             // Ensure that the bit width of the constants are the same and that
8403             // the splat arguments are logical inverses as per the pattern we
8404             // are trying to simplify.
8405             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8406                 SplatBits0 == ~SplatBits1) {
8407                 // Canonicalize the vector type to make instruction selection
8408                 // simpler.
8409                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8410                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8411                                              N0->getOperand(1),
8412                                              N0->getOperand(0),
8413                                              N1->getOperand(0));
8414                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8415             }
8416         }
8417     }
8418   }
8419
8420   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8421   // reasonable.
8422
8423   // BFI is only available on V6T2+
8424   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8425     return SDValue();
8426
8427   SDLoc DL(N);
8428   // 1) or (and A, mask), val => ARMbfi A, val, mask
8429   //      iff (val & mask) == val
8430   //
8431   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8432   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8433   //          && mask == ~mask2
8434   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8435   //          && ~mask == mask2
8436   //  (i.e., copy a bitfield value into another bitfield of the same width)
8437
8438   if (VT != MVT::i32)
8439     return SDValue();
8440
8441   SDValue N00 = N0.getOperand(0);
8442
8443   // The value and the mask need to be constants so we can verify this is
8444   // actually a bitfield set. If the mask is 0xffff, we can do better
8445   // via a movt instruction, so don't use BFI in that case.
8446   SDValue MaskOp = N0.getOperand(1);
8447   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8448   if (!MaskC)
8449     return SDValue();
8450   unsigned Mask = MaskC->getZExtValue();
8451   if (Mask == 0xffff)
8452     return SDValue();
8453   SDValue Res;
8454   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8455   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8456   if (N1C) {
8457     unsigned Val = N1C->getZExtValue();
8458     if ((Val & ~Mask) != Val)
8459       return SDValue();
8460
8461     if (ARM::isBitFieldInvertedMask(Mask)) {
8462       Val >>= countTrailingZeros(~Mask);
8463
8464       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8465                         DAG.getConstant(Val, MVT::i32),
8466                         DAG.getConstant(Mask, MVT::i32));
8467
8468       // Do not add new nodes to DAG combiner worklist.
8469       DCI.CombineTo(N, Res, false);
8470       return SDValue();
8471     }
8472   } else if (N1.getOpcode() == ISD::AND) {
8473     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8474     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8475     if (!N11C)
8476       return SDValue();
8477     unsigned Mask2 = N11C->getZExtValue();
8478
8479     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8480     // as is to match.
8481     if (ARM::isBitFieldInvertedMask(Mask) &&
8482         (Mask == ~Mask2)) {
8483       // The pack halfword instruction works better for masks that fit it,
8484       // so use that when it's available.
8485       if (Subtarget->hasT2ExtractPack() &&
8486           (Mask == 0xffff || Mask == 0xffff0000))
8487         return SDValue();
8488       // 2a
8489       unsigned amt = countTrailingZeros(Mask2);
8490       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8491                         DAG.getConstant(amt, MVT::i32));
8492       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8493                         DAG.getConstant(Mask, MVT::i32));
8494       // Do not add new nodes to DAG combiner worklist.
8495       DCI.CombineTo(N, Res, false);
8496       return SDValue();
8497     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8498                (~Mask == Mask2)) {
8499       // The pack halfword instruction works better for masks that fit it,
8500       // so use that when it's available.
8501       if (Subtarget->hasT2ExtractPack() &&
8502           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8503         return SDValue();
8504       // 2b
8505       unsigned lsb = countTrailingZeros(Mask);
8506       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8507                         DAG.getConstant(lsb, MVT::i32));
8508       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8509                         DAG.getConstant(Mask2, MVT::i32));
8510       // Do not add new nodes to DAG combiner worklist.
8511       DCI.CombineTo(N, Res, false);
8512       return SDValue();
8513     }
8514   }
8515
8516   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8517       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8518       ARM::isBitFieldInvertedMask(~Mask)) {
8519     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8520     // where lsb(mask) == #shamt and masked bits of B are known zero.
8521     SDValue ShAmt = N00.getOperand(1);
8522     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8523     unsigned LSB = countTrailingZeros(Mask);
8524     if (ShAmtC != LSB)
8525       return SDValue();
8526
8527     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8528                       DAG.getConstant(~Mask, MVT::i32));
8529
8530     // Do not add new nodes to DAG combiner worklist.
8531     DCI.CombineTo(N, Res, false);
8532   }
8533
8534   return SDValue();
8535 }
8536
8537 static SDValue PerformXORCombine(SDNode *N,
8538                                  TargetLowering::DAGCombinerInfo &DCI,
8539                                  const ARMSubtarget *Subtarget) {
8540   EVT VT = N->getValueType(0);
8541   SelectionDAG &DAG = DCI.DAG;
8542
8543   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8544     return SDValue();
8545
8546   if (!Subtarget->isThumb1Only()) {
8547     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8548     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8549     if (Result.getNode())
8550       return Result;
8551   }
8552
8553   return SDValue();
8554 }
8555
8556 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8557 /// the bits being cleared by the AND are not demanded by the BFI.
8558 static SDValue PerformBFICombine(SDNode *N,
8559                                  TargetLowering::DAGCombinerInfo &DCI) {
8560   SDValue N1 = N->getOperand(1);
8561   if (N1.getOpcode() == ISD::AND) {
8562     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8563     if (!N11C)
8564       return SDValue();
8565     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8566     unsigned LSB = countTrailingZeros(~InvMask);
8567     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8568     unsigned Mask = (1 << Width)-1;
8569     unsigned Mask2 = N11C->getZExtValue();
8570     if ((Mask & (~Mask2)) == 0)
8571       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8572                              N->getOperand(0), N1.getOperand(0),
8573                              N->getOperand(2));
8574   }
8575   return SDValue();
8576 }
8577
8578 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8579 /// ARMISD::VMOVRRD.
8580 static SDValue PerformVMOVRRDCombine(SDNode *N,
8581                                      TargetLowering::DAGCombinerInfo &DCI,
8582                                      const ARMSubtarget *Subtarget) {
8583   // vmovrrd(vmovdrr x, y) -> x,y
8584   SDValue InDouble = N->getOperand(0);
8585   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8586     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8587
8588   // vmovrrd(load f64) -> (load i32), (load i32)
8589   SDNode *InNode = InDouble.getNode();
8590   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8591       InNode->getValueType(0) == MVT::f64 &&
8592       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8593       !cast<LoadSDNode>(InNode)->isVolatile()) {
8594     // TODO: Should this be done for non-FrameIndex operands?
8595     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8596
8597     SelectionDAG &DAG = DCI.DAG;
8598     SDLoc DL(LD);
8599     SDValue BasePtr = LD->getBasePtr();
8600     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8601                                  LD->getPointerInfo(), LD->isVolatile(),
8602                                  LD->isNonTemporal(), LD->isInvariant(),
8603                                  LD->getAlignment());
8604
8605     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8606                                     DAG.getConstant(4, MVT::i32));
8607     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8608                                  LD->getPointerInfo(), LD->isVolatile(),
8609                                  LD->isNonTemporal(), LD->isInvariant(),
8610                                  std::min(4U, LD->getAlignment() / 2));
8611
8612     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8613     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8614       std::swap (NewLD1, NewLD2);
8615     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8616     return Result;
8617   }
8618
8619   return SDValue();
8620 }
8621
8622 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8623 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8624 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8625   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8626   SDValue Op0 = N->getOperand(0);
8627   SDValue Op1 = N->getOperand(1);
8628   if (Op0.getOpcode() == ISD::BITCAST)
8629     Op0 = Op0.getOperand(0);
8630   if (Op1.getOpcode() == ISD::BITCAST)
8631     Op1 = Op1.getOperand(0);
8632   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8633       Op0.getNode() == Op1.getNode() &&
8634       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8635     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8636                        N->getValueType(0), Op0.getOperand(0));
8637   return SDValue();
8638 }
8639
8640 /// PerformSTORECombine - Target-specific dag combine xforms for
8641 /// ISD::STORE.
8642 static SDValue PerformSTORECombine(SDNode *N,
8643                                    TargetLowering::DAGCombinerInfo &DCI) {
8644   StoreSDNode *St = cast<StoreSDNode>(N);
8645   if (St->isVolatile())
8646     return SDValue();
8647
8648   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8649   // pack all of the elements in one place.  Next, store to memory in fewer
8650   // chunks.
8651   SDValue StVal = St->getValue();
8652   EVT VT = StVal.getValueType();
8653   if (St->isTruncatingStore() && VT.isVector()) {
8654     SelectionDAG &DAG = DCI.DAG;
8655     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8656     EVT StVT = St->getMemoryVT();
8657     unsigned NumElems = VT.getVectorNumElements();
8658     assert(StVT != VT && "Cannot truncate to the same type");
8659     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8660     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8661
8662     // From, To sizes and ElemCount must be pow of two
8663     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8664
8665     // We are going to use the original vector elt for storing.
8666     // Accumulated smaller vector elements must be a multiple of the store size.
8667     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8668
8669     unsigned SizeRatio  = FromEltSz / ToEltSz;
8670     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8671
8672     // Create a type on which we perform the shuffle.
8673     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8674                                      NumElems*SizeRatio);
8675     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8676
8677     SDLoc DL(St);
8678     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8679     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8680     for (unsigned i = 0; i < NumElems; ++i)
8681       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8682
8683     // Can't shuffle using an illegal type.
8684     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8685
8686     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8687                                 DAG.getUNDEF(WideVec.getValueType()),
8688                                 ShuffleVec.data());
8689     // At this point all of the data is stored at the bottom of the
8690     // register. We now need to save it to mem.
8691
8692     // Find the largest store unit
8693     MVT StoreType = MVT::i8;
8694     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8695          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8696       MVT Tp = (MVT::SimpleValueType)tp;
8697       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8698         StoreType = Tp;
8699     }
8700     // Didn't find a legal store type.
8701     if (!TLI.isTypeLegal(StoreType))
8702       return SDValue();
8703
8704     // Bitcast the original vector into a vector of store-size units
8705     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8706             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8707     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8708     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8709     SmallVector<SDValue, 8> Chains;
8710     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8711                                         TLI.getPointerTy());
8712     SDValue BasePtr = St->getBasePtr();
8713
8714     // Perform one or more big stores into memory.
8715     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8716     for (unsigned I = 0; I < E; I++) {
8717       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8718                                    StoreType, ShuffWide,
8719                                    DAG.getIntPtrConstant(I));
8720       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8721                                 St->getPointerInfo(), St->isVolatile(),
8722                                 St->isNonTemporal(), St->getAlignment());
8723       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8724                             Increment);
8725       Chains.push_back(Ch);
8726     }
8727     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8728   }
8729
8730   if (!ISD::isNormalStore(St))
8731     return SDValue();
8732
8733   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8734   // ARM stores of arguments in the same cache line.
8735   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8736       StVal.getNode()->hasOneUse()) {
8737     SelectionDAG  &DAG = DCI.DAG;
8738     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8739     SDLoc DL(St);
8740     SDValue BasePtr = St->getBasePtr();
8741     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8742                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8743                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8744                                   St->isNonTemporal(), St->getAlignment());
8745
8746     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8747                                     DAG.getConstant(4, MVT::i32));
8748     return DAG.getStore(NewST1.getValue(0), DL,
8749                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8750                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8751                         St->isNonTemporal(),
8752                         std::min(4U, St->getAlignment() / 2));
8753   }
8754
8755   if (StVal.getValueType() != MVT::i64 ||
8756       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8757     return SDValue();
8758
8759   // Bitcast an i64 store extracted from a vector to f64.
8760   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8761   SelectionDAG &DAG = DCI.DAG;
8762   SDLoc dl(StVal);
8763   SDValue IntVec = StVal.getOperand(0);
8764   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8765                                  IntVec.getValueType().getVectorNumElements());
8766   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8767   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8768                                Vec, StVal.getOperand(1));
8769   dl = SDLoc(N);
8770   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8771   // Make the DAGCombiner fold the bitcasts.
8772   DCI.AddToWorklist(Vec.getNode());
8773   DCI.AddToWorklist(ExtElt.getNode());
8774   DCI.AddToWorklist(V.getNode());
8775   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8776                       St->getPointerInfo(), St->isVolatile(),
8777                       St->isNonTemporal(), St->getAlignment(),
8778                       St->getAAInfo());
8779 }
8780
8781 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8782 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8783 /// i64 vector to have f64 elements, since the value can then be loaded
8784 /// directly into a VFP register.
8785 static bool hasNormalLoadOperand(SDNode *N) {
8786   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8787   for (unsigned i = 0; i < NumElts; ++i) {
8788     SDNode *Elt = N->getOperand(i).getNode();
8789     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8790       return true;
8791   }
8792   return false;
8793 }
8794
8795 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8796 /// ISD::BUILD_VECTOR.
8797 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8798                                           TargetLowering::DAGCombinerInfo &DCI,
8799                                           const ARMSubtarget *Subtarget) {
8800   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8801   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8802   // into a pair of GPRs, which is fine when the value is used as a scalar,
8803   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8804   SelectionDAG &DAG = DCI.DAG;
8805   if (N->getNumOperands() == 2) {
8806     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8807     if (RV.getNode())
8808       return RV;
8809   }
8810
8811   // Load i64 elements as f64 values so that type legalization does not split
8812   // them up into i32 values.
8813   EVT VT = N->getValueType(0);
8814   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8815     return SDValue();
8816   SDLoc dl(N);
8817   SmallVector<SDValue, 8> Ops;
8818   unsigned NumElts = VT.getVectorNumElements();
8819   for (unsigned i = 0; i < NumElts; ++i) {
8820     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8821     Ops.push_back(V);
8822     // Make the DAGCombiner fold the bitcast.
8823     DCI.AddToWorklist(V.getNode());
8824   }
8825   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8826   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8827   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8828 }
8829
8830 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8831 static SDValue
8832 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8833   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8834   // At that time, we may have inserted bitcasts from integer to float.
8835   // If these bitcasts have survived DAGCombine, change the lowering of this
8836   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8837   // force to use floating point types.
8838
8839   // Make sure we can change the type of the vector.
8840   // This is possible iff:
8841   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8842   //    1.1. Vector is used only once.
8843   //    1.2. Use is a bit convert to an integer type.
8844   // 2. The size of its operands are 32-bits (64-bits are not legal).
8845   EVT VT = N->getValueType(0);
8846   EVT EltVT = VT.getVectorElementType();
8847
8848   // Check 1.1. and 2.
8849   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8850     return SDValue();
8851
8852   // By construction, the input type must be float.
8853   assert(EltVT == MVT::f32 && "Unexpected type!");
8854
8855   // Check 1.2.
8856   SDNode *Use = *N->use_begin();
8857   if (Use->getOpcode() != ISD::BITCAST ||
8858       Use->getValueType(0).isFloatingPoint())
8859     return SDValue();
8860
8861   // Check profitability.
8862   // Model is, if more than half of the relevant operands are bitcast from
8863   // i32, turn the build_vector into a sequence of insert_vector_elt.
8864   // Relevant operands are everything that is not statically
8865   // (i.e., at compile time) bitcasted.
8866   unsigned NumOfBitCastedElts = 0;
8867   unsigned NumElts = VT.getVectorNumElements();
8868   unsigned NumOfRelevantElts = NumElts;
8869   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8870     SDValue Elt = N->getOperand(Idx);
8871     if (Elt->getOpcode() == ISD::BITCAST) {
8872       // Assume only bit cast to i32 will go away.
8873       if (Elt->getOperand(0).getValueType() == MVT::i32)
8874         ++NumOfBitCastedElts;
8875     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8876       // Constants are statically casted, thus do not count them as
8877       // relevant operands.
8878       --NumOfRelevantElts;
8879   }
8880
8881   // Check if more than half of the elements require a non-free bitcast.
8882   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8883     return SDValue();
8884
8885   SelectionDAG &DAG = DCI.DAG;
8886   // Create the new vector type.
8887   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8888   // Check if the type is legal.
8889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8890   if (!TLI.isTypeLegal(VecVT))
8891     return SDValue();
8892
8893   // Combine:
8894   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8895   // => BITCAST INSERT_VECTOR_ELT
8896   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8897   //                      (BITCAST EN), N.
8898   SDValue Vec = DAG.getUNDEF(VecVT);
8899   SDLoc dl(N);
8900   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8901     SDValue V = N->getOperand(Idx);
8902     if (V.getOpcode() == ISD::UNDEF)
8903       continue;
8904     if (V.getOpcode() == ISD::BITCAST &&
8905         V->getOperand(0).getValueType() == MVT::i32)
8906       // Fold obvious case.
8907       V = V.getOperand(0);
8908     else {
8909       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8910       // Make the DAGCombiner fold the bitcasts.
8911       DCI.AddToWorklist(V.getNode());
8912     }
8913     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8914     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8915   }
8916   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8917   // Make the DAGCombiner fold the bitcasts.
8918   DCI.AddToWorklist(Vec.getNode());
8919   return Vec;
8920 }
8921
8922 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8923 /// ISD::INSERT_VECTOR_ELT.
8924 static SDValue PerformInsertEltCombine(SDNode *N,
8925                                        TargetLowering::DAGCombinerInfo &DCI) {
8926   // Bitcast an i64 load inserted into a vector to f64.
8927   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8928   EVT VT = N->getValueType(0);
8929   SDNode *Elt = N->getOperand(1).getNode();
8930   if (VT.getVectorElementType() != MVT::i64 ||
8931       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8932     return SDValue();
8933
8934   SelectionDAG &DAG = DCI.DAG;
8935   SDLoc dl(N);
8936   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8937                                  VT.getVectorNumElements());
8938   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8939   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8940   // Make the DAGCombiner fold the bitcasts.
8941   DCI.AddToWorklist(Vec.getNode());
8942   DCI.AddToWorklist(V.getNode());
8943   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8944                                Vec, V, N->getOperand(2));
8945   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8946 }
8947
8948 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8949 /// ISD::VECTOR_SHUFFLE.
8950 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8951   // The LLVM shufflevector instruction does not require the shuffle mask
8952   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8953   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8954   // operands do not match the mask length, they are extended by concatenating
8955   // them with undef vectors.  That is probably the right thing for other
8956   // targets, but for NEON it is better to concatenate two double-register
8957   // size vector operands into a single quad-register size vector.  Do that
8958   // transformation here:
8959   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8960   //   shuffle(concat(v1, v2), undef)
8961   SDValue Op0 = N->getOperand(0);
8962   SDValue Op1 = N->getOperand(1);
8963   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8964       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8965       Op0.getNumOperands() != 2 ||
8966       Op1.getNumOperands() != 2)
8967     return SDValue();
8968   SDValue Concat0Op1 = Op0.getOperand(1);
8969   SDValue Concat1Op1 = Op1.getOperand(1);
8970   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8971       Concat1Op1.getOpcode() != ISD::UNDEF)
8972     return SDValue();
8973   // Skip the transformation if any of the types are illegal.
8974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8975   EVT VT = N->getValueType(0);
8976   if (!TLI.isTypeLegal(VT) ||
8977       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8978       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8979     return SDValue();
8980
8981   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8982                                   Op0.getOperand(0), Op1.getOperand(0));
8983   // Translate the shuffle mask.
8984   SmallVector<int, 16> NewMask;
8985   unsigned NumElts = VT.getVectorNumElements();
8986   unsigned HalfElts = NumElts/2;
8987   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8988   for (unsigned n = 0; n < NumElts; ++n) {
8989     int MaskElt = SVN->getMaskElt(n);
8990     int NewElt = -1;
8991     if (MaskElt < (int)HalfElts)
8992       NewElt = MaskElt;
8993     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8994       NewElt = HalfElts + MaskElt - NumElts;
8995     NewMask.push_back(NewElt);
8996   }
8997   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8998                               DAG.getUNDEF(VT), NewMask.data());
8999 }
9000
9001 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9002 /// NEON load/store intrinsics to merge base address updates.
9003 static SDValue CombineBaseUpdate(SDNode *N,
9004                                  TargetLowering::DAGCombinerInfo &DCI) {
9005   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9006     return SDValue();
9007
9008   SelectionDAG &DAG = DCI.DAG;
9009   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9010                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9011   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9012   SDValue Addr = N->getOperand(AddrOpIdx);
9013
9014   // Search for a use of the address operand that is an increment.
9015   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9016          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9017     SDNode *User = *UI;
9018     if (User->getOpcode() != ISD::ADD ||
9019         UI.getUse().getResNo() != Addr.getResNo())
9020       continue;
9021
9022     // Check that the add is independent of the load/store.  Otherwise, folding
9023     // it would create a cycle.
9024     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9025       continue;
9026
9027     // Find the new opcode for the updating load/store.
9028     bool isLoad = true;
9029     bool isLaneOp = false;
9030     unsigned NewOpc = 0;
9031     unsigned NumVecs = 0;
9032     if (isIntrinsic) {
9033       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9034       switch (IntNo) {
9035       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9036       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9037         NumVecs = 1; break;
9038       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9039         NumVecs = 2; break;
9040       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9041         NumVecs = 3; break;
9042       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9043         NumVecs = 4; break;
9044       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9045         NumVecs = 2; isLaneOp = true; break;
9046       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9047         NumVecs = 3; isLaneOp = true; break;
9048       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9049         NumVecs = 4; isLaneOp = true; break;
9050       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9051         NumVecs = 1; isLoad = false; break;
9052       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9053         NumVecs = 2; isLoad = false; break;
9054       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9055         NumVecs = 3; isLoad = false; break;
9056       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9057         NumVecs = 4; isLoad = false; break;
9058       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9059         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9060       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9061         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9062       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9063         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9064       }
9065     } else {
9066       isLaneOp = true;
9067       switch (N->getOpcode()) {
9068       default: llvm_unreachable("unexpected opcode for Neon base update");
9069       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9070       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9071       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9072       }
9073     }
9074
9075     // Find the size of memory referenced by the load/store.
9076     EVT VecTy;
9077     if (isLoad)
9078       VecTy = N->getValueType(0);
9079     else
9080       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9081     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9082     if (isLaneOp)
9083       NumBytes /= VecTy.getVectorNumElements();
9084
9085     // If the increment is a constant, it must match the memory ref size.
9086     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9087     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9088       uint64_t IncVal = CInc->getZExtValue();
9089       if (IncVal != NumBytes)
9090         continue;
9091     } else if (NumBytes >= 3 * 16) {
9092       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9093       // separate instructions that make it harder to use a non-constant update.
9094       continue;
9095     }
9096
9097     // Create the new updating load/store node.
9098     EVT Tys[6];
9099     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9100     unsigned n;
9101     for (n = 0; n < NumResultVecs; ++n)
9102       Tys[n] = VecTy;
9103     Tys[n++] = MVT::i32;
9104     Tys[n] = MVT::Other;
9105     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
9106     SmallVector<SDValue, 8> Ops;
9107     Ops.push_back(N->getOperand(0)); // incoming chain
9108     Ops.push_back(N->getOperand(AddrOpIdx));
9109     Ops.push_back(Inc);
9110     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9111       Ops.push_back(N->getOperand(i));
9112     }
9113     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9114     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9115                                            Ops, MemInt->getMemoryVT(),
9116                                            MemInt->getMemOperand());
9117
9118     // Update the uses.
9119     std::vector<SDValue> NewResults;
9120     for (unsigned i = 0; i < NumResultVecs; ++i) {
9121       NewResults.push_back(SDValue(UpdN.getNode(), i));
9122     }
9123     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9124     DCI.CombineTo(N, NewResults);
9125     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9126
9127     break;
9128   }
9129   return SDValue();
9130 }
9131
9132 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9133 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9134 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9135 /// return true.
9136 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9137   SelectionDAG &DAG = DCI.DAG;
9138   EVT VT = N->getValueType(0);
9139   // vldN-dup instructions only support 64-bit vectors for N > 1.
9140   if (!VT.is64BitVector())
9141     return false;
9142
9143   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9144   SDNode *VLD = N->getOperand(0).getNode();
9145   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9146     return false;
9147   unsigned NumVecs = 0;
9148   unsigned NewOpc = 0;
9149   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9150   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9151     NumVecs = 2;
9152     NewOpc = ARMISD::VLD2DUP;
9153   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9154     NumVecs = 3;
9155     NewOpc = ARMISD::VLD3DUP;
9156   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9157     NumVecs = 4;
9158     NewOpc = ARMISD::VLD4DUP;
9159   } else {
9160     return false;
9161   }
9162
9163   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9164   // numbers match the load.
9165   unsigned VLDLaneNo =
9166     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9167   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9168        UI != UE; ++UI) {
9169     // Ignore uses of the chain result.
9170     if (UI.getUse().getResNo() == NumVecs)
9171       continue;
9172     SDNode *User = *UI;
9173     if (User->getOpcode() != ARMISD::VDUPLANE ||
9174         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9175       return false;
9176   }
9177
9178   // Create the vldN-dup node.
9179   EVT Tys[5];
9180   unsigned n;
9181   for (n = 0; n < NumVecs; ++n)
9182     Tys[n] = VT;
9183   Tys[n] = MVT::Other;
9184   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9185   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9186   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9187   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9188                                            Ops, VLDMemInt->getMemoryVT(),
9189                                            VLDMemInt->getMemOperand());
9190
9191   // Update the uses.
9192   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9193        UI != UE; ++UI) {
9194     unsigned ResNo = UI.getUse().getResNo();
9195     // Ignore uses of the chain result.
9196     if (ResNo == NumVecs)
9197       continue;
9198     SDNode *User = *UI;
9199     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9200   }
9201
9202   // Now the vldN-lane intrinsic is dead except for its chain result.
9203   // Update uses of the chain.
9204   std::vector<SDValue> VLDDupResults;
9205   for (unsigned n = 0; n < NumVecs; ++n)
9206     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9207   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9208   DCI.CombineTo(VLD, VLDDupResults);
9209
9210   return true;
9211 }
9212
9213 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9214 /// ARMISD::VDUPLANE.
9215 static SDValue PerformVDUPLANECombine(SDNode *N,
9216                                       TargetLowering::DAGCombinerInfo &DCI) {
9217   SDValue Op = N->getOperand(0);
9218
9219   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9220   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9221   if (CombineVLDDUP(N, DCI))
9222     return SDValue(N, 0);
9223
9224   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9225   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9226   while (Op.getOpcode() == ISD::BITCAST)
9227     Op = Op.getOperand(0);
9228   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9229     return SDValue();
9230
9231   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9232   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9233   // The canonical VMOV for a zero vector uses a 32-bit element size.
9234   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9235   unsigned EltBits;
9236   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9237     EltSize = 8;
9238   EVT VT = N->getValueType(0);
9239   if (EltSize > VT.getVectorElementType().getSizeInBits())
9240     return SDValue();
9241
9242   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9243 }
9244
9245 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9246 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9247 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9248 {
9249   integerPart cN;
9250   integerPart c0 = 0;
9251   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9252        I != E; I++) {
9253     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9254     if (!C)
9255       return false;
9256
9257     bool isExact;
9258     APFloat APF = C->getValueAPF();
9259     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9260         != APFloat::opOK || !isExact)
9261       return false;
9262
9263     c0 = (I == 0) ? cN : c0;
9264     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9265       return false;
9266   }
9267   C = c0;
9268   return true;
9269 }
9270
9271 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9272 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9273 /// when the VMUL has a constant operand that is a power of 2.
9274 ///
9275 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9276 ///  vmul.f32        d16, d17, d16
9277 ///  vcvt.s32.f32    d16, d16
9278 /// becomes:
9279 ///  vcvt.s32.f32    d16, d16, #3
9280 static SDValue PerformVCVTCombine(SDNode *N,
9281                                   TargetLowering::DAGCombinerInfo &DCI,
9282                                   const ARMSubtarget *Subtarget) {
9283   SelectionDAG &DAG = DCI.DAG;
9284   SDValue Op = N->getOperand(0);
9285
9286   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9287       Op.getOpcode() != ISD::FMUL)
9288     return SDValue();
9289
9290   uint64_t C;
9291   SDValue N0 = Op->getOperand(0);
9292   SDValue ConstVec = Op->getOperand(1);
9293   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9294
9295   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9296       !isConstVecPow2(ConstVec, isSigned, C))
9297     return SDValue();
9298
9299   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9300   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9301   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9302     // These instructions only exist converting from f32 to i32. We can handle
9303     // smaller integers by generating an extra truncate, but larger ones would
9304     // be lossy.
9305     return SDValue();
9306   }
9307
9308   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9309     Intrinsic::arm_neon_vcvtfp2fxu;
9310   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9311   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9312                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9313                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9314                                  DAG.getConstant(Log2_64(C), MVT::i32));
9315
9316   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9317     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9318
9319   return FixConv;
9320 }
9321
9322 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9323 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9324 /// when the VDIV has a constant operand that is a power of 2.
9325 ///
9326 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9327 ///  vcvt.f32.s32    d16, d16
9328 ///  vdiv.f32        d16, d17, d16
9329 /// becomes:
9330 ///  vcvt.f32.s32    d16, d16, #3
9331 static SDValue PerformVDIVCombine(SDNode *N,
9332                                   TargetLowering::DAGCombinerInfo &DCI,
9333                                   const ARMSubtarget *Subtarget) {
9334   SelectionDAG &DAG = DCI.DAG;
9335   SDValue Op = N->getOperand(0);
9336   unsigned OpOpcode = Op.getNode()->getOpcode();
9337
9338   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9339       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9340     return SDValue();
9341
9342   uint64_t C;
9343   SDValue ConstVec = N->getOperand(1);
9344   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9345
9346   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9347       !isConstVecPow2(ConstVec, isSigned, C))
9348     return SDValue();
9349
9350   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9351   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9352   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9353     // These instructions only exist converting from i32 to f32. We can handle
9354     // smaller integers by generating an extra extend, but larger ones would
9355     // be lossy.
9356     return SDValue();
9357   }
9358
9359   SDValue ConvInput = Op.getOperand(0);
9360   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9361   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9362     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9363                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9364                             ConvInput);
9365
9366   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9367     Intrinsic::arm_neon_vcvtfxu2fp;
9368   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9369                      Op.getValueType(),
9370                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9371                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9372 }
9373
9374 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9375 /// operand of a vector shift operation, where all the elements of the
9376 /// build_vector must have the same constant integer value.
9377 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9378   // Ignore bit_converts.
9379   while (Op.getOpcode() == ISD::BITCAST)
9380     Op = Op.getOperand(0);
9381   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9382   APInt SplatBits, SplatUndef;
9383   unsigned SplatBitSize;
9384   bool HasAnyUndefs;
9385   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9386                                       HasAnyUndefs, ElementBits) ||
9387       SplatBitSize > ElementBits)
9388     return false;
9389   Cnt = SplatBits.getSExtValue();
9390   return true;
9391 }
9392
9393 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9394 /// operand of a vector shift left operation.  That value must be in the range:
9395 ///   0 <= Value < ElementBits for a left shift; or
9396 ///   0 <= Value <= ElementBits for a long left shift.
9397 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9398   assert(VT.isVector() && "vector shift count is not a vector type");
9399   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9400   if (! getVShiftImm(Op, ElementBits, Cnt))
9401     return false;
9402   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9403 }
9404
9405 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9406 /// operand of a vector shift right operation.  For a shift opcode, the value
9407 /// is positive, but for an intrinsic the value count must be negative. The
9408 /// absolute value must be in the range:
9409 ///   1 <= |Value| <= ElementBits for a right shift; or
9410 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9411 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9412                          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   if (isIntrinsic)
9418     Cnt = -Cnt;
9419   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9420 }
9421
9422 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9423 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9424   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9425   switch (IntNo) {
9426   default:
9427     // Don't do anything for most intrinsics.
9428     break;
9429
9430   // Vector shifts: check for immediate versions and lower them.
9431   // Note: This is done during DAG combining instead of DAG legalizing because
9432   // the build_vectors for 64-bit vector element shift counts are generally
9433   // not legal, and it is hard to see their values after they get legalized to
9434   // loads from a constant pool.
9435   case Intrinsic::arm_neon_vshifts:
9436   case Intrinsic::arm_neon_vshiftu:
9437   case Intrinsic::arm_neon_vrshifts:
9438   case Intrinsic::arm_neon_vrshiftu:
9439   case Intrinsic::arm_neon_vrshiftn:
9440   case Intrinsic::arm_neon_vqshifts:
9441   case Intrinsic::arm_neon_vqshiftu:
9442   case Intrinsic::arm_neon_vqshiftsu:
9443   case Intrinsic::arm_neon_vqshiftns:
9444   case Intrinsic::arm_neon_vqshiftnu:
9445   case Intrinsic::arm_neon_vqshiftnsu:
9446   case Intrinsic::arm_neon_vqrshiftns:
9447   case Intrinsic::arm_neon_vqrshiftnu:
9448   case Intrinsic::arm_neon_vqrshiftnsu: {
9449     EVT VT = N->getOperand(1).getValueType();
9450     int64_t Cnt;
9451     unsigned VShiftOpc = 0;
9452
9453     switch (IntNo) {
9454     case Intrinsic::arm_neon_vshifts:
9455     case Intrinsic::arm_neon_vshiftu:
9456       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9457         VShiftOpc = ARMISD::VSHL;
9458         break;
9459       }
9460       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9461         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9462                      ARMISD::VSHRs : ARMISD::VSHRu);
9463         break;
9464       }
9465       return SDValue();
9466
9467     case Intrinsic::arm_neon_vrshifts:
9468     case Intrinsic::arm_neon_vrshiftu:
9469       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9470         break;
9471       return SDValue();
9472
9473     case Intrinsic::arm_neon_vqshifts:
9474     case Intrinsic::arm_neon_vqshiftu:
9475       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9476         break;
9477       return SDValue();
9478
9479     case Intrinsic::arm_neon_vqshiftsu:
9480       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9481         break;
9482       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9483
9484     case Intrinsic::arm_neon_vrshiftn:
9485     case Intrinsic::arm_neon_vqshiftns:
9486     case Intrinsic::arm_neon_vqshiftnu:
9487     case Intrinsic::arm_neon_vqshiftnsu:
9488     case Intrinsic::arm_neon_vqrshiftns:
9489     case Intrinsic::arm_neon_vqrshiftnu:
9490     case Intrinsic::arm_neon_vqrshiftnsu:
9491       // Narrowing shifts require an immediate right shift.
9492       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9493         break;
9494       llvm_unreachable("invalid shift count for narrowing vector shift "
9495                        "intrinsic");
9496
9497     default:
9498       llvm_unreachable("unhandled vector shift");
9499     }
9500
9501     switch (IntNo) {
9502     case Intrinsic::arm_neon_vshifts:
9503     case Intrinsic::arm_neon_vshiftu:
9504       // Opcode already set above.
9505       break;
9506     case Intrinsic::arm_neon_vrshifts:
9507       VShiftOpc = ARMISD::VRSHRs; break;
9508     case Intrinsic::arm_neon_vrshiftu:
9509       VShiftOpc = ARMISD::VRSHRu; break;
9510     case Intrinsic::arm_neon_vrshiftn:
9511       VShiftOpc = ARMISD::VRSHRN; break;
9512     case Intrinsic::arm_neon_vqshifts:
9513       VShiftOpc = ARMISD::VQSHLs; break;
9514     case Intrinsic::arm_neon_vqshiftu:
9515       VShiftOpc = ARMISD::VQSHLu; break;
9516     case Intrinsic::arm_neon_vqshiftsu:
9517       VShiftOpc = ARMISD::VQSHLsu; break;
9518     case Intrinsic::arm_neon_vqshiftns:
9519       VShiftOpc = ARMISD::VQSHRNs; break;
9520     case Intrinsic::arm_neon_vqshiftnu:
9521       VShiftOpc = ARMISD::VQSHRNu; break;
9522     case Intrinsic::arm_neon_vqshiftnsu:
9523       VShiftOpc = ARMISD::VQSHRNsu; break;
9524     case Intrinsic::arm_neon_vqrshiftns:
9525       VShiftOpc = ARMISD::VQRSHRNs; break;
9526     case Intrinsic::arm_neon_vqrshiftnu:
9527       VShiftOpc = ARMISD::VQRSHRNu; break;
9528     case Intrinsic::arm_neon_vqrshiftnsu:
9529       VShiftOpc = ARMISD::VQRSHRNsu; break;
9530     }
9531
9532     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9533                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9534   }
9535
9536   case Intrinsic::arm_neon_vshiftins: {
9537     EVT VT = N->getOperand(1).getValueType();
9538     int64_t Cnt;
9539     unsigned VShiftOpc = 0;
9540
9541     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9542       VShiftOpc = ARMISD::VSLI;
9543     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9544       VShiftOpc = ARMISD::VSRI;
9545     else {
9546       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9547     }
9548
9549     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9550                        N->getOperand(1), N->getOperand(2),
9551                        DAG.getConstant(Cnt, MVT::i32));
9552   }
9553
9554   case Intrinsic::arm_neon_vqrshifts:
9555   case Intrinsic::arm_neon_vqrshiftu:
9556     // No immediate versions of these to check for.
9557     break;
9558   }
9559
9560   return SDValue();
9561 }
9562
9563 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9564 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9565 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9566 /// vector element shift counts are generally not legal, and it is hard to see
9567 /// their values after they get legalized to loads from a constant pool.
9568 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9569                                    const ARMSubtarget *ST) {
9570   EVT VT = N->getValueType(0);
9571   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9572     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9573     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9574     SDValue N1 = N->getOperand(1);
9575     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9576       SDValue N0 = N->getOperand(0);
9577       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9578           DAG.MaskedValueIsZero(N0.getOperand(0),
9579                                 APInt::getHighBitsSet(32, 16)))
9580         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9581     }
9582   }
9583
9584   // Nothing to be done for scalar shifts.
9585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9586   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9587     return SDValue();
9588
9589   assert(ST->hasNEON() && "unexpected vector shift");
9590   int64_t Cnt;
9591
9592   switch (N->getOpcode()) {
9593   default: llvm_unreachable("unexpected shift opcode");
9594
9595   case ISD::SHL:
9596     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9597       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9598                          DAG.getConstant(Cnt, MVT::i32));
9599     break;
9600
9601   case ISD::SRA:
9602   case ISD::SRL:
9603     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9604       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9605                             ARMISD::VSHRs : ARMISD::VSHRu);
9606       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9607                          DAG.getConstant(Cnt, MVT::i32));
9608     }
9609   }
9610   return SDValue();
9611 }
9612
9613 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9614 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9615 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9616                                     const ARMSubtarget *ST) {
9617   SDValue N0 = N->getOperand(0);
9618
9619   // Check for sign- and zero-extensions of vector extract operations of 8-
9620   // and 16-bit vector elements.  NEON supports these directly.  They are
9621   // handled during DAG combining because type legalization will promote them
9622   // to 32-bit types and it is messy to recognize the operations after that.
9623   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9624     SDValue Vec = N0.getOperand(0);
9625     SDValue Lane = N0.getOperand(1);
9626     EVT VT = N->getValueType(0);
9627     EVT EltVT = N0.getValueType();
9628     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9629
9630     if (VT == MVT::i32 &&
9631         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9632         TLI.isTypeLegal(Vec.getValueType()) &&
9633         isa<ConstantSDNode>(Lane)) {
9634
9635       unsigned Opc = 0;
9636       switch (N->getOpcode()) {
9637       default: llvm_unreachable("unexpected opcode");
9638       case ISD::SIGN_EXTEND:
9639         Opc = ARMISD::VGETLANEs;
9640         break;
9641       case ISD::ZERO_EXTEND:
9642       case ISD::ANY_EXTEND:
9643         Opc = ARMISD::VGETLANEu;
9644         break;
9645       }
9646       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9647     }
9648   }
9649
9650   return SDValue();
9651 }
9652
9653 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9654 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9655 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9656                                        const ARMSubtarget *ST) {
9657   // If the target supports NEON, try to use vmax/vmin instructions for f32
9658   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9659   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9660   // a NaN; only do the transformation when it matches that behavior.
9661
9662   // For now only do this when using NEON for FP operations; if using VFP, it
9663   // is not obvious that the benefit outweighs the cost of switching to the
9664   // NEON pipeline.
9665   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9666       N->getValueType(0) != MVT::f32)
9667     return SDValue();
9668
9669   SDValue CondLHS = N->getOperand(0);
9670   SDValue CondRHS = N->getOperand(1);
9671   SDValue LHS = N->getOperand(2);
9672   SDValue RHS = N->getOperand(3);
9673   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9674
9675   unsigned Opcode = 0;
9676   bool IsReversed;
9677   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9678     IsReversed = false; // x CC y ? x : y
9679   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9680     IsReversed = true ; // x CC y ? y : x
9681   } else {
9682     return SDValue();
9683   }
9684
9685   bool IsUnordered;
9686   switch (CC) {
9687   default: break;
9688   case ISD::SETOLT:
9689   case ISD::SETOLE:
9690   case ISD::SETLT:
9691   case ISD::SETLE:
9692   case ISD::SETULT:
9693   case ISD::SETULE:
9694     // If LHS is NaN, an ordered comparison will be false and the result will
9695     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9696     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9697     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9698     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9699       break;
9700     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9701     // will return -0, so vmin can only be used for unsafe math or if one of
9702     // the operands is known to be nonzero.
9703     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9704         !DAG.getTarget().Options.UnsafeFPMath &&
9705         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9706       break;
9707     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9708     break;
9709
9710   case ISD::SETOGT:
9711   case ISD::SETOGE:
9712   case ISD::SETGT:
9713   case ISD::SETGE:
9714   case ISD::SETUGT:
9715   case ISD::SETUGE:
9716     // If LHS is NaN, an ordered comparison will be false and the result will
9717     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9718     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9719     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9720     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9721       break;
9722     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9723     // will return +0, so vmax can only be used for unsafe math or if one of
9724     // the operands is known to be nonzero.
9725     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9726         !DAG.getTarget().Options.UnsafeFPMath &&
9727         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9728       break;
9729     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9730     break;
9731   }
9732
9733   if (!Opcode)
9734     return SDValue();
9735   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9736 }
9737
9738 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9739 SDValue
9740 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9741   SDValue Cmp = N->getOperand(4);
9742   if (Cmp.getOpcode() != ARMISD::CMPZ)
9743     // Only looking at EQ and NE cases.
9744     return SDValue();
9745
9746   EVT VT = N->getValueType(0);
9747   SDLoc dl(N);
9748   SDValue LHS = Cmp.getOperand(0);
9749   SDValue RHS = Cmp.getOperand(1);
9750   SDValue FalseVal = N->getOperand(0);
9751   SDValue TrueVal = N->getOperand(1);
9752   SDValue ARMcc = N->getOperand(2);
9753   ARMCC::CondCodes CC =
9754     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9755
9756   // Simplify
9757   //   mov     r1, r0
9758   //   cmp     r1, x
9759   //   mov     r0, y
9760   //   moveq   r0, x
9761   // to
9762   //   cmp     r0, x
9763   //   movne   r0, y
9764   //
9765   //   mov     r1, r0
9766   //   cmp     r1, x
9767   //   mov     r0, x
9768   //   movne   r0, y
9769   // to
9770   //   cmp     r0, x
9771   //   movne   r0, y
9772   /// FIXME: Turn this into a target neutral optimization?
9773   SDValue Res;
9774   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9775     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9776                       N->getOperand(3), Cmp);
9777   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9778     SDValue ARMcc;
9779     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9780     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9781                       N->getOperand(3), NewCmp);
9782   }
9783
9784   if (Res.getNode()) {
9785     APInt KnownZero, KnownOne;
9786     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9787     // Capture demanded bits information that would be otherwise lost.
9788     if (KnownZero == 0xfffffffe)
9789       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9790                         DAG.getValueType(MVT::i1));
9791     else if (KnownZero == 0xffffff00)
9792       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9793                         DAG.getValueType(MVT::i8));
9794     else if (KnownZero == 0xffff0000)
9795       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9796                         DAG.getValueType(MVT::i16));
9797   }
9798
9799   return Res;
9800 }
9801
9802 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9803                                              DAGCombinerInfo &DCI) const {
9804   switch (N->getOpcode()) {
9805   default: break;
9806   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9807   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9808   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9809   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9810   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9811   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9812   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9813   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9814   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9815   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9816   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9817   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9818   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9819   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9820   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9821   case ISD::FP_TO_SINT:
9822   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9823   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9824   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9825   case ISD::SHL:
9826   case ISD::SRA:
9827   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9828   case ISD::SIGN_EXTEND:
9829   case ISD::ZERO_EXTEND:
9830   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9831   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9832   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9833   case ARMISD::VLD2DUP:
9834   case ARMISD::VLD3DUP:
9835   case ARMISD::VLD4DUP:
9836     return CombineBaseUpdate(N, DCI);
9837   case ARMISD::BUILD_VECTOR:
9838     return PerformARMBUILD_VECTORCombine(N, DCI);
9839   case ISD::INTRINSIC_VOID:
9840   case ISD::INTRINSIC_W_CHAIN:
9841     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9842     case Intrinsic::arm_neon_vld1:
9843     case Intrinsic::arm_neon_vld2:
9844     case Intrinsic::arm_neon_vld3:
9845     case Intrinsic::arm_neon_vld4:
9846     case Intrinsic::arm_neon_vld2lane:
9847     case Intrinsic::arm_neon_vld3lane:
9848     case Intrinsic::arm_neon_vld4lane:
9849     case Intrinsic::arm_neon_vst1:
9850     case Intrinsic::arm_neon_vst2:
9851     case Intrinsic::arm_neon_vst3:
9852     case Intrinsic::arm_neon_vst4:
9853     case Intrinsic::arm_neon_vst2lane:
9854     case Intrinsic::arm_neon_vst3lane:
9855     case Intrinsic::arm_neon_vst4lane:
9856       return CombineBaseUpdate(N, DCI);
9857     default: break;
9858     }
9859     break;
9860   }
9861   return SDValue();
9862 }
9863
9864 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9865                                                           EVT VT) const {
9866   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9867 }
9868
9869 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9870                                                        unsigned,
9871                                                        unsigned,
9872                                                        bool *Fast) const {
9873   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9874   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9875
9876   switch (VT.getSimpleVT().SimpleTy) {
9877   default:
9878     return false;
9879   case MVT::i8:
9880   case MVT::i16:
9881   case MVT::i32: {
9882     // Unaligned access can use (for example) LRDB, LRDH, LDR
9883     if (AllowsUnaligned) {
9884       if (Fast)
9885         *Fast = Subtarget->hasV7Ops();
9886       return true;
9887     }
9888     return false;
9889   }
9890   case MVT::f64:
9891   case MVT::v2f64: {
9892     // For any little-endian targets with neon, we can support unaligned ld/st
9893     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9894     // A big-endian target may also explicitly support unaligned accesses
9895     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9896       if (Fast)
9897         *Fast = true;
9898       return true;
9899     }
9900     return false;
9901   }
9902   }
9903 }
9904
9905 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9906                        unsigned AlignCheck) {
9907   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9908           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9909 }
9910
9911 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9912                                            unsigned DstAlign, unsigned SrcAlign,
9913                                            bool IsMemset, bool ZeroMemset,
9914                                            bool MemcpyStrSrc,
9915                                            MachineFunction &MF) const {
9916   const Function *F = MF.getFunction();
9917
9918   // See if we can use NEON instructions for this...
9919   if ((!IsMemset || ZeroMemset) &&
9920       Subtarget->hasNEON() &&
9921       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9922                                        Attribute::NoImplicitFloat)) {
9923     bool Fast;
9924     if (Size >= 16 &&
9925         (memOpAlign(SrcAlign, DstAlign, 16) ||
9926          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9927       return MVT::v2f64;
9928     } else if (Size >= 8 &&
9929                (memOpAlign(SrcAlign, DstAlign, 8) ||
9930                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9931                  Fast))) {
9932       return MVT::f64;
9933     }
9934   }
9935
9936   // Lowering to i32/i16 if the size permits.
9937   if (Size >= 4)
9938     return MVT::i32;
9939   else if (Size >= 2)
9940     return MVT::i16;
9941
9942   // Let the target-independent logic figure it out.
9943   return MVT::Other;
9944 }
9945
9946 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9947   if (Val.getOpcode() != ISD::LOAD)
9948     return false;
9949
9950   EVT VT1 = Val.getValueType();
9951   if (!VT1.isSimple() || !VT1.isInteger() ||
9952       !VT2.isSimple() || !VT2.isInteger())
9953     return false;
9954
9955   switch (VT1.getSimpleVT().SimpleTy) {
9956   default: break;
9957   case MVT::i1:
9958   case MVT::i8:
9959   case MVT::i16:
9960     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9961     return true;
9962   }
9963
9964   return false;
9965 }
9966
9967 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9968   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9969     return false;
9970
9971   if (!isTypeLegal(EVT::getEVT(Ty1)))
9972     return false;
9973
9974   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9975
9976   // Assuming the caller doesn't have a zeroext or signext return parameter,
9977   // truncation all the way down to i1 is valid.
9978   return true;
9979 }
9980
9981
9982 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9983   if (V < 0)
9984     return false;
9985
9986   unsigned Scale = 1;
9987   switch (VT.getSimpleVT().SimpleTy) {
9988   default: return false;
9989   case MVT::i1:
9990   case MVT::i8:
9991     // Scale == 1;
9992     break;
9993   case MVT::i16:
9994     // Scale == 2;
9995     Scale = 2;
9996     break;
9997   case MVT::i32:
9998     // Scale == 4;
9999     Scale = 4;
10000     break;
10001   }
10002
10003   if ((V & (Scale - 1)) != 0)
10004     return false;
10005   V /= Scale;
10006   return V == (V & ((1LL << 5) - 1));
10007 }
10008
10009 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10010                                       const ARMSubtarget *Subtarget) {
10011   bool isNeg = false;
10012   if (V < 0) {
10013     isNeg = true;
10014     V = - V;
10015   }
10016
10017   switch (VT.getSimpleVT().SimpleTy) {
10018   default: return false;
10019   case MVT::i1:
10020   case MVT::i8:
10021   case MVT::i16:
10022   case MVT::i32:
10023     // + imm12 or - imm8
10024     if (isNeg)
10025       return V == (V & ((1LL << 8) - 1));
10026     return V == (V & ((1LL << 12) - 1));
10027   case MVT::f32:
10028   case MVT::f64:
10029     // Same as ARM mode. FIXME: NEON?
10030     if (!Subtarget->hasVFP2())
10031       return false;
10032     if ((V & 3) != 0)
10033       return false;
10034     V >>= 2;
10035     return V == (V & ((1LL << 8) - 1));
10036   }
10037 }
10038
10039 /// isLegalAddressImmediate - Return true if the integer value can be used
10040 /// as the offset of the target addressing mode for load / store of the
10041 /// given type.
10042 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10043                                     const ARMSubtarget *Subtarget) {
10044   if (V == 0)
10045     return true;
10046
10047   if (!VT.isSimple())
10048     return false;
10049
10050   if (Subtarget->isThumb1Only())
10051     return isLegalT1AddressImmediate(V, VT);
10052   else if (Subtarget->isThumb2())
10053     return isLegalT2AddressImmediate(V, VT, Subtarget);
10054
10055   // ARM mode.
10056   if (V < 0)
10057     V = - V;
10058   switch (VT.getSimpleVT().SimpleTy) {
10059   default: return false;
10060   case MVT::i1:
10061   case MVT::i8:
10062   case MVT::i32:
10063     // +- imm12
10064     return V == (V & ((1LL << 12) - 1));
10065   case MVT::i16:
10066     // +- imm8
10067     return V == (V & ((1LL << 8) - 1));
10068   case MVT::f32:
10069   case MVT::f64:
10070     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10071       return false;
10072     if ((V & 3) != 0)
10073       return false;
10074     V >>= 2;
10075     return V == (V & ((1LL << 8) - 1));
10076   }
10077 }
10078
10079 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10080                                                       EVT VT) const {
10081   int Scale = AM.Scale;
10082   if (Scale < 0)
10083     return false;
10084
10085   switch (VT.getSimpleVT().SimpleTy) {
10086   default: return false;
10087   case MVT::i1:
10088   case MVT::i8:
10089   case MVT::i16:
10090   case MVT::i32:
10091     if (Scale == 1)
10092       return true;
10093     // r + r << imm
10094     Scale = Scale & ~1;
10095     return Scale == 2 || Scale == 4 || Scale == 8;
10096   case MVT::i64:
10097     // r + r
10098     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10099       return true;
10100     return false;
10101   case MVT::isVoid:
10102     // Note, we allow "void" uses (basically, uses that aren't loads or
10103     // stores), because arm allows folding a scale into many arithmetic
10104     // operations.  This should be made more precise and revisited later.
10105
10106     // Allow r << imm, but the imm has to be a multiple of two.
10107     if (Scale & 1) return false;
10108     return isPowerOf2_32(Scale);
10109   }
10110 }
10111
10112 /// isLegalAddressingMode - Return true if the addressing mode represented
10113 /// by AM is legal for this target, for a load/store of the specified type.
10114 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10115                                               Type *Ty) const {
10116   EVT VT = getValueType(Ty, true);
10117   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10118     return false;
10119
10120   // Can never fold addr of global into load/store.
10121   if (AM.BaseGV)
10122     return false;
10123
10124   switch (AM.Scale) {
10125   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10126     break;
10127   case 1:
10128     if (Subtarget->isThumb1Only())
10129       return false;
10130     // FALL THROUGH.
10131   default:
10132     // ARM doesn't support any R+R*scale+imm addr modes.
10133     if (AM.BaseOffs)
10134       return false;
10135
10136     if (!VT.isSimple())
10137       return false;
10138
10139     if (Subtarget->isThumb2())
10140       return isLegalT2ScaledAddressingMode(AM, VT);
10141
10142     int Scale = AM.Scale;
10143     switch (VT.getSimpleVT().SimpleTy) {
10144     default: return false;
10145     case MVT::i1:
10146     case MVT::i8:
10147     case MVT::i32:
10148       if (Scale < 0) Scale = -Scale;
10149       if (Scale == 1)
10150         return true;
10151       // r + r << imm
10152       return isPowerOf2_32(Scale & ~1);
10153     case MVT::i16:
10154     case MVT::i64:
10155       // r + r
10156       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10157         return true;
10158       return false;
10159
10160     case MVT::isVoid:
10161       // Note, we allow "void" uses (basically, uses that aren't loads or
10162       // stores), because arm allows folding a scale into many arithmetic
10163       // operations.  This should be made more precise and revisited later.
10164
10165       // Allow r << imm, but the imm has to be a multiple of two.
10166       if (Scale & 1) return false;
10167       return isPowerOf2_32(Scale);
10168     }
10169   }
10170   return true;
10171 }
10172
10173 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10174 /// icmp immediate, that is the target has icmp instructions which can compare
10175 /// a register against the immediate without having to materialize the
10176 /// immediate into a register.
10177 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10178   // Thumb2 and ARM modes can use cmn for negative immediates.
10179   if (!Subtarget->isThumb())
10180     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10181   if (Subtarget->isThumb2())
10182     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10183   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10184   return Imm >= 0 && Imm <= 255;
10185 }
10186
10187 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10188 /// *or sub* immediate, that is the target has add or sub instructions which can
10189 /// add a register with the immediate without having to materialize the
10190 /// immediate into a register.
10191 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10192   // Same encoding for add/sub, just flip the sign.
10193   int64_t AbsImm = llvm::abs64(Imm);
10194   if (!Subtarget->isThumb())
10195     return ARM_AM::getSOImmVal(AbsImm) != -1;
10196   if (Subtarget->isThumb2())
10197     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10198   // Thumb1 only has 8-bit unsigned immediate.
10199   return AbsImm >= 0 && AbsImm <= 255;
10200 }
10201
10202 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10203                                       bool isSEXTLoad, SDValue &Base,
10204                                       SDValue &Offset, bool &isInc,
10205                                       SelectionDAG &DAG) {
10206   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10207     return false;
10208
10209   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10210     // AddressingMode 3
10211     Base = Ptr->getOperand(0);
10212     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10213       int RHSC = (int)RHS->getZExtValue();
10214       if (RHSC < 0 && RHSC > -256) {
10215         assert(Ptr->getOpcode() == ISD::ADD);
10216         isInc = false;
10217         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10218         return true;
10219       }
10220     }
10221     isInc = (Ptr->getOpcode() == ISD::ADD);
10222     Offset = Ptr->getOperand(1);
10223     return true;
10224   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10225     // AddressingMode 2
10226     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10227       int RHSC = (int)RHS->getZExtValue();
10228       if (RHSC < 0 && RHSC > -0x1000) {
10229         assert(Ptr->getOpcode() == ISD::ADD);
10230         isInc = false;
10231         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10232         Base = Ptr->getOperand(0);
10233         return true;
10234       }
10235     }
10236
10237     if (Ptr->getOpcode() == ISD::ADD) {
10238       isInc = true;
10239       ARM_AM::ShiftOpc ShOpcVal=
10240         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10241       if (ShOpcVal != ARM_AM::no_shift) {
10242         Base = Ptr->getOperand(1);
10243         Offset = Ptr->getOperand(0);
10244       } else {
10245         Base = Ptr->getOperand(0);
10246         Offset = Ptr->getOperand(1);
10247       }
10248       return true;
10249     }
10250
10251     isInc = (Ptr->getOpcode() == ISD::ADD);
10252     Base = Ptr->getOperand(0);
10253     Offset = Ptr->getOperand(1);
10254     return true;
10255   }
10256
10257   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10258   return false;
10259 }
10260
10261 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10262                                      bool isSEXTLoad, SDValue &Base,
10263                                      SDValue &Offset, bool &isInc,
10264                                      SelectionDAG &DAG) {
10265   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10266     return false;
10267
10268   Base = Ptr->getOperand(0);
10269   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10270     int RHSC = (int)RHS->getZExtValue();
10271     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10272       assert(Ptr->getOpcode() == ISD::ADD);
10273       isInc = false;
10274       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10275       return true;
10276     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10277       isInc = Ptr->getOpcode() == ISD::ADD;
10278       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10279       return true;
10280     }
10281   }
10282
10283   return false;
10284 }
10285
10286 /// getPreIndexedAddressParts - returns true by value, base pointer and
10287 /// offset pointer and addressing mode by reference if the node's address
10288 /// can be legally represented as pre-indexed load / store address.
10289 bool
10290 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10291                                              SDValue &Offset,
10292                                              ISD::MemIndexedMode &AM,
10293                                              SelectionDAG &DAG) const {
10294   if (Subtarget->isThumb1Only())
10295     return false;
10296
10297   EVT VT;
10298   SDValue Ptr;
10299   bool isSEXTLoad = false;
10300   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10301     Ptr = LD->getBasePtr();
10302     VT  = LD->getMemoryVT();
10303     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10304   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10305     Ptr = ST->getBasePtr();
10306     VT  = ST->getMemoryVT();
10307   } else
10308     return false;
10309
10310   bool isInc;
10311   bool isLegal = false;
10312   if (Subtarget->isThumb2())
10313     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10314                                        Offset, isInc, DAG);
10315   else
10316     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10317                                         Offset, isInc, DAG);
10318   if (!isLegal)
10319     return false;
10320
10321   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10322   return true;
10323 }
10324
10325 /// getPostIndexedAddressParts - returns true by value, base pointer and
10326 /// offset pointer and addressing mode by reference if this node can be
10327 /// combined with a load / store to form a post-indexed load / store.
10328 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10329                                                    SDValue &Base,
10330                                                    SDValue &Offset,
10331                                                    ISD::MemIndexedMode &AM,
10332                                                    SelectionDAG &DAG) const {
10333   if (Subtarget->isThumb1Only())
10334     return false;
10335
10336   EVT VT;
10337   SDValue Ptr;
10338   bool isSEXTLoad = false;
10339   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10340     VT  = LD->getMemoryVT();
10341     Ptr = LD->getBasePtr();
10342     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10343   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10344     VT  = ST->getMemoryVT();
10345     Ptr = ST->getBasePtr();
10346   } else
10347     return false;
10348
10349   bool isInc;
10350   bool isLegal = false;
10351   if (Subtarget->isThumb2())
10352     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10353                                        isInc, DAG);
10354   else
10355     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10356                                         isInc, DAG);
10357   if (!isLegal)
10358     return false;
10359
10360   if (Ptr != Base) {
10361     // Swap base ptr and offset to catch more post-index load / store when
10362     // it's legal. In Thumb2 mode, offset must be an immediate.
10363     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10364         !Subtarget->isThumb2())
10365       std::swap(Base, Offset);
10366
10367     // Post-indexed load / store update the base pointer.
10368     if (Ptr != Base)
10369       return false;
10370   }
10371
10372   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10373   return true;
10374 }
10375
10376 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10377                                                       APInt &KnownZero,
10378                                                       APInt &KnownOne,
10379                                                       const SelectionDAG &DAG,
10380                                                       unsigned Depth) const {
10381   unsigned BitWidth = KnownOne.getBitWidth();
10382   KnownZero = KnownOne = APInt(BitWidth, 0);
10383   switch (Op.getOpcode()) {
10384   default: break;
10385   case ARMISD::ADDC:
10386   case ARMISD::ADDE:
10387   case ARMISD::SUBC:
10388   case ARMISD::SUBE:
10389     // These nodes' second result is a boolean
10390     if (Op.getResNo() == 0)
10391       break;
10392     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10393     break;
10394   case ARMISD::CMOV: {
10395     // Bits are known zero/one if known on the LHS and RHS.
10396     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10397     if (KnownZero == 0 && KnownOne == 0) return;
10398
10399     APInt KnownZeroRHS, KnownOneRHS;
10400     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10401     KnownZero &= KnownZeroRHS;
10402     KnownOne  &= KnownOneRHS;
10403     return;
10404   }
10405   case ISD::INTRINSIC_W_CHAIN: {
10406     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10407     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10408     switch (IntID) {
10409     default: return;
10410     case Intrinsic::arm_ldaex:
10411     case Intrinsic::arm_ldrex: {
10412       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10413       unsigned MemBits = VT.getScalarType().getSizeInBits();
10414       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10415       return;
10416     }
10417     }
10418   }
10419   }
10420 }
10421
10422 //===----------------------------------------------------------------------===//
10423 //                           ARM Inline Assembly Support
10424 //===----------------------------------------------------------------------===//
10425
10426 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10427   // Looking for "rev" which is V6+.
10428   if (!Subtarget->hasV6Ops())
10429     return false;
10430
10431   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10432   std::string AsmStr = IA->getAsmString();
10433   SmallVector<StringRef, 4> AsmPieces;
10434   SplitString(AsmStr, AsmPieces, ";\n");
10435
10436   switch (AsmPieces.size()) {
10437   default: return false;
10438   case 1:
10439     AsmStr = AsmPieces[0];
10440     AsmPieces.clear();
10441     SplitString(AsmStr, AsmPieces, " \t,");
10442
10443     // rev $0, $1
10444     if (AsmPieces.size() == 3 &&
10445         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10446         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10447       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10448       if (Ty && Ty->getBitWidth() == 32)
10449         return IntrinsicLowering::LowerToByteSwap(CI);
10450     }
10451     break;
10452   }
10453
10454   return false;
10455 }
10456
10457 /// getConstraintType - Given a constraint letter, return the type of
10458 /// constraint it is for this target.
10459 ARMTargetLowering::ConstraintType
10460 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10461   if (Constraint.size() == 1) {
10462     switch (Constraint[0]) {
10463     default:  break;
10464     case 'l': return C_RegisterClass;
10465     case 'w': return C_RegisterClass;
10466     case 'h': return C_RegisterClass;
10467     case 'x': return C_RegisterClass;
10468     case 't': return C_RegisterClass;
10469     case 'j': return C_Other; // Constant for movw.
10470       // An address with a single base register. Due to the way we
10471       // currently handle addresses it is the same as an 'r' memory constraint.
10472     case 'Q': return C_Memory;
10473     }
10474   } else if (Constraint.size() == 2) {
10475     switch (Constraint[0]) {
10476     default: break;
10477     // All 'U+' constraints are addresses.
10478     case 'U': return C_Memory;
10479     }
10480   }
10481   return TargetLowering::getConstraintType(Constraint);
10482 }
10483
10484 /// Examine constraint type and operand type and determine a weight value.
10485 /// This object must already have been set up with the operand type
10486 /// and the current alternative constraint selected.
10487 TargetLowering::ConstraintWeight
10488 ARMTargetLowering::getSingleConstraintMatchWeight(
10489     AsmOperandInfo &info, const char *constraint) const {
10490   ConstraintWeight weight = CW_Invalid;
10491   Value *CallOperandVal = info.CallOperandVal;
10492     // If we don't have a value, we can't do a match,
10493     // but allow it at the lowest weight.
10494   if (!CallOperandVal)
10495     return CW_Default;
10496   Type *type = CallOperandVal->getType();
10497   // Look at the constraint type.
10498   switch (*constraint) {
10499   default:
10500     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10501     break;
10502   case 'l':
10503     if (type->isIntegerTy()) {
10504       if (Subtarget->isThumb())
10505         weight = CW_SpecificReg;
10506       else
10507         weight = CW_Register;
10508     }
10509     break;
10510   case 'w':
10511     if (type->isFloatingPointTy())
10512       weight = CW_Register;
10513     break;
10514   }
10515   return weight;
10516 }
10517
10518 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10519 RCPair
10520 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10521                                                 MVT VT) const {
10522   if (Constraint.size() == 1) {
10523     // GCC ARM Constraint Letters
10524     switch (Constraint[0]) {
10525     case 'l': // Low regs or general regs.
10526       if (Subtarget->isThumb())
10527         return RCPair(0U, &ARM::tGPRRegClass);
10528       return RCPair(0U, &ARM::GPRRegClass);
10529     case 'h': // High regs or no regs.
10530       if (Subtarget->isThumb())
10531         return RCPair(0U, &ARM::hGPRRegClass);
10532       break;
10533     case 'r':
10534       return RCPair(0U, &ARM::GPRRegClass);
10535     case 'w':
10536       if (VT == MVT::Other)
10537         break;
10538       if (VT == MVT::f32)
10539         return RCPair(0U, &ARM::SPRRegClass);
10540       if (VT.getSizeInBits() == 64)
10541         return RCPair(0U, &ARM::DPRRegClass);
10542       if (VT.getSizeInBits() == 128)
10543         return RCPair(0U, &ARM::QPRRegClass);
10544       break;
10545     case 'x':
10546       if (VT == MVT::Other)
10547         break;
10548       if (VT == MVT::f32)
10549         return RCPair(0U, &ARM::SPR_8RegClass);
10550       if (VT.getSizeInBits() == 64)
10551         return RCPair(0U, &ARM::DPR_8RegClass);
10552       if (VT.getSizeInBits() == 128)
10553         return RCPair(0U, &ARM::QPR_8RegClass);
10554       break;
10555     case 't':
10556       if (VT == MVT::f32)
10557         return RCPair(0U, &ARM::SPRRegClass);
10558       break;
10559     }
10560   }
10561   if (StringRef("{cc}").equals_lower(Constraint))
10562     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10563
10564   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10565 }
10566
10567 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10568 /// vector.  If it is invalid, don't add anything to Ops.
10569 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10570                                                      std::string &Constraint,
10571                                                      std::vector<SDValue>&Ops,
10572                                                      SelectionDAG &DAG) const {
10573   SDValue Result;
10574
10575   // Currently only support length 1 constraints.
10576   if (Constraint.length() != 1) return;
10577
10578   char ConstraintLetter = Constraint[0];
10579   switch (ConstraintLetter) {
10580   default: break;
10581   case 'j':
10582   case 'I': case 'J': case 'K': case 'L':
10583   case 'M': case 'N': case 'O':
10584     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10585     if (!C)
10586       return;
10587
10588     int64_t CVal64 = C->getSExtValue();
10589     int CVal = (int) CVal64;
10590     // None of these constraints allow values larger than 32 bits.  Check
10591     // that the value fits in an int.
10592     if (CVal != CVal64)
10593       return;
10594
10595     switch (ConstraintLetter) {
10596       case 'j':
10597         // Constant suitable for movw, must be between 0 and
10598         // 65535.
10599         if (Subtarget->hasV6T2Ops())
10600           if (CVal >= 0 && CVal <= 65535)
10601             break;
10602         return;
10603       case 'I':
10604         if (Subtarget->isThumb1Only()) {
10605           // This must be a constant between 0 and 255, for ADD
10606           // immediates.
10607           if (CVal >= 0 && CVal <= 255)
10608             break;
10609         } else if (Subtarget->isThumb2()) {
10610           // A constant that can be used as an immediate value in a
10611           // data-processing instruction.
10612           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10613             break;
10614         } else {
10615           // A constant that can be used as an immediate value in a
10616           // data-processing instruction.
10617           if (ARM_AM::getSOImmVal(CVal) != -1)
10618             break;
10619         }
10620         return;
10621
10622       case 'J':
10623         if (Subtarget->isThumb()) {  // FIXME thumb2
10624           // This must be a constant between -255 and -1, for negated ADD
10625           // immediates. This can be used in GCC with an "n" modifier that
10626           // prints the negated value, for use with SUB instructions. It is
10627           // not useful otherwise but is implemented for compatibility.
10628           if (CVal >= -255 && CVal <= -1)
10629             break;
10630         } else {
10631           // This must be a constant between -4095 and 4095. It is not clear
10632           // what this constraint is intended for. Implemented for
10633           // compatibility with GCC.
10634           if (CVal >= -4095 && CVal <= 4095)
10635             break;
10636         }
10637         return;
10638
10639       case 'K':
10640         if (Subtarget->isThumb1Only()) {
10641           // A 32-bit value where only one byte has a nonzero value. Exclude
10642           // zero to match GCC. This constraint is used by GCC internally for
10643           // constants that can be loaded with a move/shift combination.
10644           // It is not useful otherwise but is implemented for compatibility.
10645           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10646             break;
10647         } else if (Subtarget->isThumb2()) {
10648           // A constant whose bitwise inverse can be used as an immediate
10649           // value in a data-processing instruction. This can be used in GCC
10650           // with a "B" modifier that prints the inverted value, for use with
10651           // BIC and MVN instructions. It is not useful otherwise but is
10652           // implemented for compatibility.
10653           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10654             break;
10655         } else {
10656           // A constant whose bitwise inverse can be used as an immediate
10657           // value in a data-processing instruction. This can be used in GCC
10658           // with a "B" modifier that prints the inverted value, for use with
10659           // BIC and MVN instructions. It is not useful otherwise but is
10660           // implemented for compatibility.
10661           if (ARM_AM::getSOImmVal(~CVal) != -1)
10662             break;
10663         }
10664         return;
10665
10666       case 'L':
10667         if (Subtarget->isThumb1Only()) {
10668           // This must be a constant between -7 and 7,
10669           // for 3-operand ADD/SUB immediate instructions.
10670           if (CVal >= -7 && CVal < 7)
10671             break;
10672         } else if (Subtarget->isThumb2()) {
10673           // A constant whose negation can be used as an immediate value in a
10674           // data-processing instruction. This can be used in GCC with an "n"
10675           // modifier that prints the negated value, for use with SUB
10676           // instructions. It is not useful otherwise but is implemented for
10677           // compatibility.
10678           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10679             break;
10680         } else {
10681           // A constant whose negation can be used as an immediate value in a
10682           // data-processing instruction. This can be used in GCC with an "n"
10683           // modifier that prints the negated value, for use with SUB
10684           // instructions. It is not useful otherwise but is implemented for
10685           // compatibility.
10686           if (ARM_AM::getSOImmVal(-CVal) != -1)
10687             break;
10688         }
10689         return;
10690
10691       case 'M':
10692         if (Subtarget->isThumb()) { // FIXME thumb2
10693           // This must be a multiple of 4 between 0 and 1020, for
10694           // ADD sp + immediate.
10695           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10696             break;
10697         } else {
10698           // A power of two or a constant between 0 and 32.  This is used in
10699           // GCC for the shift amount on shifted register operands, but it is
10700           // useful in general for any shift amounts.
10701           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10702             break;
10703         }
10704         return;
10705
10706       case 'N':
10707         if (Subtarget->isThumb()) {  // FIXME thumb2
10708           // This must be a constant between 0 and 31, for shift amounts.
10709           if (CVal >= 0 && CVal <= 31)
10710             break;
10711         }
10712         return;
10713
10714       case 'O':
10715         if (Subtarget->isThumb()) {  // FIXME thumb2
10716           // This must be a multiple of 4 between -508 and 508, for
10717           // ADD/SUB sp = sp + immediate.
10718           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10719             break;
10720         }
10721         return;
10722     }
10723     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10724     break;
10725   }
10726
10727   if (Result.getNode()) {
10728     Ops.push_back(Result);
10729     return;
10730   }
10731   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10732 }
10733
10734 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10735   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10736   unsigned Opcode = Op->getOpcode();
10737   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10738          "Invalid opcode for Div/Rem lowering");
10739   bool isSigned = (Opcode == ISD::SDIVREM);
10740   EVT VT = Op->getValueType(0);
10741   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10742
10743   RTLIB::Libcall LC;
10744   switch (VT.getSimpleVT().SimpleTy) {
10745   default: llvm_unreachable("Unexpected request for libcall!");
10746   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10747   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10748   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10749   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10750   }
10751
10752   SDValue InChain = DAG.getEntryNode();
10753
10754   TargetLowering::ArgListTy Args;
10755   TargetLowering::ArgListEntry Entry;
10756   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10757     EVT ArgVT = Op->getOperand(i).getValueType();
10758     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10759     Entry.Node = Op->getOperand(i);
10760     Entry.Ty = ArgTy;
10761     Entry.isSExt = isSigned;
10762     Entry.isZExt = !isSigned;
10763     Args.push_back(Entry);
10764   }
10765
10766   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10767                                          getPointerTy());
10768
10769   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10770
10771   SDLoc dl(Op);
10772   TargetLowering::CallLoweringInfo CLI(DAG);
10773   CLI.setDebugLoc(dl).setChain(InChain)
10774     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10775     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10776
10777   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10778   return CallInfo.first;
10779 }
10780
10781 SDValue
10782 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10783   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10784   SDLoc DL(Op);
10785
10786   // Get the inputs.
10787   SDValue Chain = Op.getOperand(0);
10788   SDValue Size  = Op.getOperand(1);
10789
10790   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10791                               DAG.getConstant(2, MVT::i32));
10792
10793   SDValue Flag;
10794   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10795   Flag = Chain.getValue(1);
10796
10797   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10798   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10799
10800   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10801   Chain = NewSP.getValue(1);
10802
10803   SDValue Ops[2] = { NewSP, Chain };
10804   return DAG.getMergeValues(Ops, DL);
10805 }
10806
10807 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10808   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10809          "Unexpected type for custom-lowering FP_EXTEND");
10810
10811   RTLIB::Libcall LC;
10812   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10813
10814   SDValue SrcVal = Op.getOperand(0);
10815   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10816                      /*isSigned*/ false, SDLoc(Op)).first;
10817 }
10818
10819 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10820   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10821          Subtarget->isFPOnlySP() &&
10822          "Unexpected type for custom-lowering FP_ROUND");
10823
10824   RTLIB::Libcall LC;
10825   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10826
10827   SDValue SrcVal = Op.getOperand(0);
10828   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10829                      /*isSigned*/ false, SDLoc(Op)).first;
10830 }
10831
10832 bool
10833 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10834   // The ARM target isn't yet aware of offsets.
10835   return false;
10836 }
10837
10838 bool ARM::isBitFieldInvertedMask(unsigned v) {
10839   if (v == 0xffffffff)
10840     return false;
10841
10842   // there can be 1's on either or both "outsides", all the "inside"
10843   // bits must be 0's
10844   unsigned TO = CountTrailingOnes_32(v);
10845   unsigned LO = CountLeadingOnes_32(v);
10846   v = (v >> TO) << TO;
10847   v = (v << LO) >> LO;
10848   return v == 0;
10849 }
10850
10851 /// isFPImmLegal - Returns true if the target can instruction select the
10852 /// specified FP immediate natively. If false, the legalizer will
10853 /// materialize the FP immediate as a load from a constant pool.
10854 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10855   if (!Subtarget->hasVFP3())
10856     return false;
10857   if (VT == MVT::f32)
10858     return ARM_AM::getFP32Imm(Imm) != -1;
10859   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10860     return ARM_AM::getFP64Imm(Imm) != -1;
10861   return false;
10862 }
10863
10864 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10865 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10866 /// specified in the intrinsic calls.
10867 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10868                                            const CallInst &I,
10869                                            unsigned Intrinsic) const {
10870   switch (Intrinsic) {
10871   case Intrinsic::arm_neon_vld1:
10872   case Intrinsic::arm_neon_vld2:
10873   case Intrinsic::arm_neon_vld3:
10874   case Intrinsic::arm_neon_vld4:
10875   case Intrinsic::arm_neon_vld2lane:
10876   case Intrinsic::arm_neon_vld3lane:
10877   case Intrinsic::arm_neon_vld4lane: {
10878     Info.opc = ISD::INTRINSIC_W_CHAIN;
10879     // Conservatively set memVT to the entire set of vectors loaded.
10880     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10881     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10882     Info.ptrVal = I.getArgOperand(0);
10883     Info.offset = 0;
10884     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10885     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10886     Info.vol = false; // volatile loads with NEON intrinsics not supported
10887     Info.readMem = true;
10888     Info.writeMem = false;
10889     return true;
10890   }
10891   case Intrinsic::arm_neon_vst1:
10892   case Intrinsic::arm_neon_vst2:
10893   case Intrinsic::arm_neon_vst3:
10894   case Intrinsic::arm_neon_vst4:
10895   case Intrinsic::arm_neon_vst2lane:
10896   case Intrinsic::arm_neon_vst3lane:
10897   case Intrinsic::arm_neon_vst4lane: {
10898     Info.opc = ISD::INTRINSIC_VOID;
10899     // Conservatively set memVT to the entire set of vectors stored.
10900     unsigned NumElts = 0;
10901     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10902       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10903       if (!ArgTy->isVectorTy())
10904         break;
10905       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10906     }
10907     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10908     Info.ptrVal = I.getArgOperand(0);
10909     Info.offset = 0;
10910     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10911     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10912     Info.vol = false; // volatile stores with NEON intrinsics not supported
10913     Info.readMem = false;
10914     Info.writeMem = true;
10915     return true;
10916   }
10917   case Intrinsic::arm_ldaex:
10918   case Intrinsic::arm_ldrex: {
10919     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10920     Info.opc = ISD::INTRINSIC_W_CHAIN;
10921     Info.memVT = MVT::getVT(PtrTy->getElementType());
10922     Info.ptrVal = I.getArgOperand(0);
10923     Info.offset = 0;
10924     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10925     Info.vol = true;
10926     Info.readMem = true;
10927     Info.writeMem = false;
10928     return true;
10929   }
10930   case Intrinsic::arm_stlex:
10931   case Intrinsic::arm_strex: {
10932     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10933     Info.opc = ISD::INTRINSIC_W_CHAIN;
10934     Info.memVT = MVT::getVT(PtrTy->getElementType());
10935     Info.ptrVal = I.getArgOperand(1);
10936     Info.offset = 0;
10937     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10938     Info.vol = true;
10939     Info.readMem = false;
10940     Info.writeMem = true;
10941     return true;
10942   }
10943   case Intrinsic::arm_stlexd:
10944   case Intrinsic::arm_strexd: {
10945     Info.opc = ISD::INTRINSIC_W_CHAIN;
10946     Info.memVT = MVT::i64;
10947     Info.ptrVal = I.getArgOperand(2);
10948     Info.offset = 0;
10949     Info.align = 8;
10950     Info.vol = true;
10951     Info.readMem = false;
10952     Info.writeMem = true;
10953     return true;
10954   }
10955   case Intrinsic::arm_ldaexd:
10956   case Intrinsic::arm_ldrexd: {
10957     Info.opc = ISD::INTRINSIC_W_CHAIN;
10958     Info.memVT = MVT::i64;
10959     Info.ptrVal = I.getArgOperand(0);
10960     Info.offset = 0;
10961     Info.align = 8;
10962     Info.vol = true;
10963     Info.readMem = true;
10964     Info.writeMem = false;
10965     return true;
10966   }
10967   default:
10968     break;
10969   }
10970
10971   return false;
10972 }
10973
10974 /// \brief Returns true if it is beneficial to convert a load of a constant
10975 /// to just the constant itself.
10976 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10977                                                           Type *Ty) const {
10978   assert(Ty->isIntegerTy());
10979
10980   unsigned Bits = Ty->getPrimitiveSizeInBits();
10981   if (Bits == 0 || Bits > 32)
10982     return false;
10983   return true;
10984 }
10985
10986 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10987   // Loads and stores less than 64-bits are already atomic; ones above that
10988   // are doomed anyway, so defer to the default libcall and blame the OS when
10989   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10990   // anything for those.
10991   bool IsMClass = Subtarget->isMClass();
10992   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10993     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10994     return Size == 64 && !IsMClass;
10995   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10996     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10997   }
10998
10999   // For the real atomic operations, we have ldrex/strex up to 32 bits,
11000   // and up to 64 bits on the non-M profiles
11001   unsigned AtomicLimit = IsMClass ? 32 : 64;
11002   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
11003 }
11004
11005 // This has so far only been implemented for MachO.
11006 bool ARMTargetLowering::useLoadStackGuardNode() const {
11007   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11008 }
11009
11010 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11011                                          AtomicOrdering Ord) const {
11012   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11013   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11014   bool IsAcquire = isAtLeastAcquire(Ord);
11015
11016   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11017   // intrinsic must return {i32, i32} and we have to recombine them into a
11018   // single i64 here.
11019   if (ValTy->getPrimitiveSizeInBits() == 64) {
11020     Intrinsic::ID Int =
11021         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11022     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11023
11024     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11025     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11026
11027     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11028     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11029     if (!Subtarget->isLittle())
11030       std::swap (Lo, Hi);
11031     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11032     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11033     return Builder.CreateOr(
11034         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11035   }
11036
11037   Type *Tys[] = { Addr->getType() };
11038   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11039   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11040
11041   return Builder.CreateTruncOrBitCast(
11042       Builder.CreateCall(Ldrex, Addr),
11043       cast<PointerType>(Addr->getType())->getElementType());
11044 }
11045
11046 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11047                                                Value *Addr,
11048                                                AtomicOrdering Ord) const {
11049   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11050   bool IsRelease = isAtLeastRelease(Ord);
11051
11052   // Since the intrinsics must have legal type, the i64 intrinsics take two
11053   // parameters: "i32, i32". We must marshal Val into the appropriate form
11054   // before the call.
11055   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11056     Intrinsic::ID Int =
11057         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11058     Function *Strex = Intrinsic::getDeclaration(M, Int);
11059     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11060
11061     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11062     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11063     if (!Subtarget->isLittle())
11064       std::swap (Lo, Hi);
11065     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11066     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11067   }
11068
11069   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11070   Type *Tys[] = { Addr->getType() };
11071   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11072
11073   return Builder.CreateCall2(
11074       Strex, Builder.CreateZExtOrBitCast(
11075                  Val, Strex->getFunctionType()->getParamType(0)),
11076       Addr);
11077 }
11078
11079 enum HABaseType {
11080   HA_UNKNOWN = 0,
11081   HA_FLOAT,
11082   HA_DOUBLE,
11083   HA_VECT64,
11084   HA_VECT128
11085 };
11086
11087 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11088                                    uint64_t &Members) {
11089   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11090     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11091       uint64_t SubMembers = 0;
11092       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11093         return false;
11094       Members += SubMembers;
11095     }
11096   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11097     uint64_t SubMembers = 0;
11098     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11099       return false;
11100     Members += SubMembers * AT->getNumElements();
11101   } else if (Ty->isFloatTy()) {
11102     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11103       return false;
11104     Members = 1;
11105     Base = HA_FLOAT;
11106   } else if (Ty->isDoubleTy()) {
11107     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11108       return false;
11109     Members = 1;
11110     Base = HA_DOUBLE;
11111   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11112     Members = 1;
11113     switch (Base) {
11114     case HA_FLOAT:
11115     case HA_DOUBLE:
11116       return false;
11117     case HA_VECT64:
11118       return VT->getBitWidth() == 64;
11119     case HA_VECT128:
11120       return VT->getBitWidth() == 128;
11121     case HA_UNKNOWN:
11122       switch (VT->getBitWidth()) {
11123       case 64:
11124         Base = HA_VECT64;
11125         return true;
11126       case 128:
11127         Base = HA_VECT128;
11128         return true;
11129       default:
11130         return false;
11131       }
11132     }
11133   }
11134
11135   return (Members > 0 && Members <= 4);
11136 }
11137
11138 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11139 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11140     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11141   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11142       CallingConv::ARM_AAPCS_VFP)
11143     return false;
11144
11145   HABaseType Base = HA_UNKNOWN;
11146   uint64_t Members = 0;
11147   bool result = isHomogeneousAggregate(Ty, Base, Members);
11148   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11149   return result;
11150 }