Add AtomicExpandPass::bracketInstWithFences, and use it whenever getInsertFencesForAt...
[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/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "arm-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59
60 cl::opt<bool>
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62   cl::desc("Generate calls via indirect call instructions"),
63   cl::init(false));
64
65 static cl::opt<bool>
66 ARMInterworking("arm-interworking", cl::Hidden,
67   cl::desc("Enable / disable ARM interworking (for debugging only)"),
68   cl::init(true));
69
70 namespace {
71   class ARMCCState : public CCState {
72   public:
73     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75                ParmContext PC)
76         : CCState(CC, isVarArg, MF, locs, C) {
77       assert(((PC == Call) || (PC == Prologue)) &&
78              "ARMCCState users must specify whether their context is call"
79              "or prologue generation.");
80       CallOrPrologue = PC;
81     }
82   };
83 }
84
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87   ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 };
89
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91                                        MVT PromotedBitwiseVT) {
92   if (VT != PromotedLdStVT) {
93     setOperationAction(ISD::LOAD, VT, Promote);
94     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95
96     setOperationAction(ISD::STORE, VT, Promote);
97     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98   }
99
100   MVT ElemTy = VT.getVectorElementType();
101   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102     setOperationAction(ISD::SETCC, VT, Custom);
103   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105   if (ElemTy == MVT::i32) {
106     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110   } else {
111     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115   }
116   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
117   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
118   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
119   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120   setOperationAction(ISD::SELECT,            VT, Expand);
121   setOperationAction(ISD::SELECT_CC,         VT, Expand);
122   setOperationAction(ISD::VSELECT,           VT, Expand);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124   if (VT.isInteger()) {
125     setOperationAction(ISD::SHL, VT, Custom);
126     setOperationAction(ISD::SRA, VT, Custom);
127     setOperationAction(ISD::SRL, VT, Custom);
128   }
129
130   // Promote all bit-wise operations.
131   if (VT.isInteger() && VT != PromotedBitwiseVT) {
132     setOperationAction(ISD::AND, VT, Promote);
133     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134     setOperationAction(ISD::OR,  VT, Promote);
135     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
136     setOperationAction(ISD::XOR, VT, Promote);
137     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138   }
139
140   // Neon does not support vector divide/remainder operations.
141   setOperationAction(ISD::SDIV, VT, Expand);
142   setOperationAction(ISD::UDIV, VT, Expand);
143   setOperationAction(ISD::FDIV, VT, Expand);
144   setOperationAction(ISD::SREM, VT, Expand);
145   setOperationAction(ISD::UREM, VT, Expand);
146   setOperationAction(ISD::FREM, VT, Expand);
147 }
148
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150   addRegisterClass(VT, &ARM::DPRRegClass);
151   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 }
153
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155   addRegisterClass(VT, &ARM::DPairRegClass);
156   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 }
158
159 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
160   if (TT.isOSBinFormatMachO())
161     return new TargetLoweringObjectFileMachO();
162   if (TT.isOSWindows())
163     return new TargetLoweringObjectFileCOFF();
164   return new ARMElfTargetObjectFile();
165 }
166
167 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
168     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
169   Subtarget = &TM.getSubtarget<ARMSubtarget>();
170   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
171   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
179       // Single-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184
185       // Double-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190
191       // Single-precision comparisons.
192       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
199       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
200
201       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
208       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
209
210       // Double-precision comparisons.
211       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
218       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
219
220       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
227       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
228
229       // Floating-point to integer conversions.
230       // i64 conversions are done via library routines even when generating VFP
231       // instructions, so use the same ones.
232       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236
237       // Conversions between floating types.
238       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
240
241       // Integer to floating-point conversions.
242       // i64 conversions are done via library routines even when generating VFP
243       // instructions, so use the same ones.
244       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245       // e.g., __floatunsidf vs. __floatunssidfvfp.
246       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250     }
251   }
252
253   // These libcalls are not available in 32-bit.
254   setLibcallName(RTLIB::SHL_I128, nullptr);
255   setLibcallName(RTLIB::SRL_I128, nullptr);
256   setLibcallName(RTLIB::SRA_I128, nullptr);
257
258   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
259       !Subtarget->isTargetWindows()) {
260     static const struct {
261       const RTLIB::Libcall Op;
262       const char * const Name;
263       const CallingConv::ID CC;
264       const ISD::CondCode Cond;
265     } LibraryCalls[] = {
266       // Double-precision floating-point arithmetic helper functions
267       // RTABI chapter 4.1.2, Table 2
268       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272
273       // Double-precision floating-point comparison helper functions
274       // RTABI chapter 4.1.2, Table 3
275       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
277       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283
284       // Single-precision floating-point arithmetic helper functions
285       // RTABI chapter 4.1.2, Table 4
286       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290
291       // Single-precision floating-point comparison helper functions
292       // RTABI chapter 4.1.2, Table 5
293       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
295       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
300       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301
302       // Floating-point to integer conversions.
303       // RTABI chapter 4.1.2, Table 6
304       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Conversions between floating types.
314       // RTABI chapter 4.1.2, Table 7
315       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Integer to floating-point conversions.
320       // RTABI chapter 4.1.2, Table 8
321       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329
330       // Long long helper functions
331       // RTABI chapter 4.2, Table 9
332       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Integer division functions
338       // RTABI chapter 4.3.1
339       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347
348       // Memory operations
349       // RTABI chapter 4.3.4
350       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353     };
354
355     for (const auto &LC : LibraryCalls) {
356       setLibcallName(LC.Op, LC.Name);
357       setLibcallCallingConv(LC.Op, LC.CC);
358       if (LC.Cond != ISD::SETCC_INVALID)
359         setCmpLibcallCC(LC.Op, LC.Cond);
360     }
361   }
362
363   if (Subtarget->isTargetWindows()) {
364     static const struct {
365       const RTLIB::Libcall Op;
366       const char * const Name;
367       const CallingConv::ID CC;
368     } LibraryCalls[] = {
369       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
376       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
377     };
378
379     for (const auto &LC : LibraryCalls) {
380       setLibcallName(LC.Op, LC.Name);
381       setLibcallCallingConv(LC.Op, LC.CC);
382     }
383   }
384
385   // Use divmod compiler-rt calls for iOS 5.0 and later.
386   if (Subtarget->getTargetTriple().isiOS() &&
387       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
388     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
389     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
390   }
391
392   // The half <-> float conversion functions are always soft-float, but are
393   // needed for some targets which use a hard-float calling convention by
394   // default.
395   if (Subtarget->isAAPCS_ABI()) {
396     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
398     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
399   } else {
400     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
402     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
403   }
404
405   if (Subtarget->isThumb1Only())
406     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
407   else
408     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
409   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
410       !Subtarget->isThumb1Only()) {
411     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
412     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
413   }
414
415   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
416        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
417     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
418          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
419       setTruncStoreAction((MVT::SimpleValueType)VT,
420                           (MVT::SimpleValueType)InnerVT, Expand);
421     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
423     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
424
425     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
426     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
427     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
428     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
429
430     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
431   }
432
433   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453     // supported for v4f32.
454     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457     // FIXME: Code duplication: FDIV and FREM are expanded always, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461     // FIXME: Create unittest.
462     // In another words, find a way when "copysign" appears in DAG with vector
463     // operands.
464     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465     // FIXME: Code duplication: SETCC has custom operation action, see
466     // ARMTargetLowering::addTypeForNEON method for details.
467     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FNEG and for FABS.
469     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488
489     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504
505     // Mark v2f32 intrinsics.
506     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
545     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
546
547     // NEON does not have single instruction CTPOP for vectors with element
548     // types wider than 8-bits.  However, custom lowering can leverage the
549     // v8i8/v16i8 vcnt instruction.
550     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
554
555     // NEON only has FMA instructions as of VFP4.
556     if (!Subtarget->hasVFP4()) {
557       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
558       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
559     }
560
561     setTargetDAGCombine(ISD::INTRINSIC_VOID);
562     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
563     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564     setTargetDAGCombine(ISD::SHL);
565     setTargetDAGCombine(ISD::SRL);
566     setTargetDAGCombine(ISD::SRA);
567     setTargetDAGCombine(ISD::SIGN_EXTEND);
568     setTargetDAGCombine(ISD::ZERO_EXTEND);
569     setTargetDAGCombine(ISD::ANY_EXTEND);
570     setTargetDAGCombine(ISD::SELECT_CC);
571     setTargetDAGCombine(ISD::BUILD_VECTOR);
572     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
573     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
574     setTargetDAGCombine(ISD::STORE);
575     setTargetDAGCombine(ISD::FP_TO_SINT);
576     setTargetDAGCombine(ISD::FP_TO_UINT);
577     setTargetDAGCombine(ISD::FDIV);
578
579     // It is legal to extload from v4i8 to v4i16 or v4i32.
580     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
581                   MVT::v4i16, MVT::v2i16,
582                   MVT::v2i32};
583     for (unsigned i = 0; i < 6; ++i) {
584       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
585       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
586       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
587     }
588   }
589
590   // ARM and Thumb2 support UMLAL/SMLAL.
591   if (!Subtarget->isThumb1Only())
592     setTargetDAGCombine(ISD::ADDC);
593
594   if (Subtarget->isFPOnlySP()) {
595     // When targetting a floating-point unit with only single-precision
596     // operations, f64 is legal for the few double-precision instructions which
597     // are present However, no double-precision operations other than moves,
598     // loads and stores are provided by the hardware.
599     setOperationAction(ISD::FADD,       MVT::f64, Expand);
600     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
601     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
602     setOperationAction(ISD::FMA,        MVT::f64, Expand);
603     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
604     setOperationAction(ISD::FREM,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
606     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
607     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
608     setOperationAction(ISD::FABS,       MVT::f64, Expand);
609     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
610     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
611     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
612     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
613     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
614     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
615     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
616     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
617     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
618     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
619     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
620     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
621     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
622     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
623     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
624     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
625     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
626   }
627
628   computeRegisterProperties();
629
630   // ARM does not have floating-point extending loads.
631   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
632   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
633
634   // ... or truncating stores
635   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
636   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
637   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
638
639   // ARM does not have i1 sign extending load.
640   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
641
642   // ARM supports all 4 flavors of integer indexed load / store.
643   if (!Subtarget->isThumb1Only()) {
644     for (unsigned im = (unsigned)ISD::PRE_INC;
645          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
646       setIndexedLoadAction(im,  MVT::i1,  Legal);
647       setIndexedLoadAction(im,  MVT::i8,  Legal);
648       setIndexedLoadAction(im,  MVT::i16, Legal);
649       setIndexedLoadAction(im,  MVT::i32, Legal);
650       setIndexedStoreAction(im, MVT::i1,  Legal);
651       setIndexedStoreAction(im, MVT::i8,  Legal);
652       setIndexedStoreAction(im, MVT::i16, Legal);
653       setIndexedStoreAction(im, MVT::i32, Legal);
654     }
655   }
656
657   setOperationAction(ISD::SADDO, MVT::i32, Custom);
658   setOperationAction(ISD::UADDO, MVT::i32, Custom);
659   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
660   setOperationAction(ISD::USUBO, MVT::i32, Custom);
661
662   // i64 operation support.
663   setOperationAction(ISD::MUL,     MVT::i64, Expand);
664   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
665   if (Subtarget->isThumb1Only()) {
666     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
667     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
668   }
669   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
670       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
671     setOperationAction(ISD::MULHS, MVT::i32, Expand);
672
673   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
674   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
675   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
676   setOperationAction(ISD::SRL,       MVT::i64, Custom);
677   setOperationAction(ISD::SRA,       MVT::i64, Custom);
678
679   if (!Subtarget->isThumb1Only()) {
680     // FIXME: We should do this for Thumb1 as well.
681     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
682     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
683     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
684     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
685   }
686
687   // ARM does not have ROTL.
688   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
689   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
690   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
691   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
692     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
693
694   // These just redirect to CTTZ and CTLZ on ARM.
695   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
696   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
697
698   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
699
700   // Only ARMv6 has BSWAP.
701   if (!Subtarget->hasV6Ops())
702     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
703
704   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
705       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
706     // These are expanded into libcalls if the cpu doesn't have HW divider.
707     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
708     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
709   }
710
711   // FIXME: Also set divmod for SREM on EABI
712   setOperationAction(ISD::SREM,  MVT::i32, Expand);
713   setOperationAction(ISD::UREM,  MVT::i32, Expand);
714   // Register based DivRem for AEABI (RTABI 4.2)
715   if (Subtarget->isTargetAEABI()) {
716     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
717     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
718     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
719     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
720     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
721     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
722     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
723     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
724
725     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
733
734     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
735     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
736   } else {
737     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
738     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
739   }
740
741   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
742   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
743   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
744   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
745   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
746
747   setOperationAction(ISD::TRAP, MVT::Other, Legal);
748
749   // Use the default implementation.
750   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
751   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
752   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
753   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
754   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
755   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
756
757   if (!Subtarget->isTargetMachO()) {
758     // Non-MachO platforms may return values in these registers via the
759     // personality function.
760     setExceptionPointerRegister(ARM::R0);
761     setExceptionSelectorRegister(ARM::R1);
762   }
763
764   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
765     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
766   else
767     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
768
769   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
770   // the default expansion. If we are targeting a single threaded system,
771   // then set them all for expand so we can lower them later into their
772   // non-atomic form.
773   if (TM.Options.ThreadModel == ThreadModel::Single)
774     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
775   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777     // to ldrex/strex loops already.
778     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
779
780     // On v8, we have particularly efficient implementations of atomic fences
781     // if they can be combined with nearby atomic loads and stores.
782     if (!Subtarget->hasV8Ops()) {
783       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
784       setInsertFencesForAtomic(true);
785     }
786   } else {
787     // If there's anything we can use as a barrier, go through custom lowering
788     // for ATOMIC_FENCE.
789     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
790                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
791
792     // Set them all for expansion, which will force libcalls.
793     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806     // Unordered/Monotonic case.
807     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
809   }
810
811   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
812
813   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814   if (!Subtarget->hasV6Ops()) {
815     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
817   }
818   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
819
820   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821       !Subtarget->isThumb1Only()) {
822     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823     // iff target supports vfp2.
824     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
826   }
827
828   // We want to custom lower some of our intrinsics.
829   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830   if (Subtarget->isTargetDarwin()) {
831     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
834   }
835
836   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
837   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
838   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
839   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
840   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
841   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
842   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
845
846   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
847   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
848   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
849   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
850   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
851
852   // We don't support sin/cos/fmod/copysign/pow
853   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
854   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
855   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
856   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
857   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
858   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
859   setOperationAction(ISD::FREM,      MVT::f64, Expand);
860   setOperationAction(ISD::FREM,      MVT::f32, Expand);
861   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862       !Subtarget->isThumb1Only()) {
863     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
865   }
866   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
867   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
868
869   if (!Subtarget->hasVFP4()) {
870     setOperationAction(ISD::FMA, MVT::f64, Expand);
871     setOperationAction(ISD::FMA, MVT::f32, Expand);
872   }
873
874   // Various VFP goodness
875   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877     if (Subtarget->hasVFP2()) {
878       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
882     }
883
884     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
885     if (!Subtarget->hasV8Ops()) {
886       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
887       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
888     }
889
890     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
891     if (!Subtarget->hasFP16()) {
892       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
893       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
894     }
895   }
896
897   // Combine sin / cos into one node or libcall if possible.
898   if (Subtarget->hasSinCos()) {
899     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
900     setLibcallName(RTLIB::SINCOS_F64, "sincos");
901     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
902       // For iOS, we don't want to the normal expansion of a libcall to
903       // sincos. We want to issue a libcall to __sincos_stret.
904       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
905       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
906     }
907   }
908
909   // ARMv8 implements a lot of rounding-like FP operations.
910   if (Subtarget->hasV8Ops()) {
911     static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
912     for (const auto Ty : RoundingTypes) {
913       setOperationAction(ISD::FFLOOR, Ty, Legal);
914       setOperationAction(ISD::FCEIL, Ty, Legal);
915       setOperationAction(ISD::FROUND, Ty, Legal);
916       setOperationAction(ISD::FTRUNC, Ty, Legal);
917       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
918       setOperationAction(ISD::FRINT, Ty, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass*, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
971   const TargetRegisterClass *RRC = nullptr;
972   uint8_t Cost = 1;
973   switch (VT.SimpleTy) {
974   default:
975     return TargetLowering::findRepresentativeClass(VT);
976   // Use DPR as representative register class for all floating point
977   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978   // the cost is 1 for both f32 and f64.
979   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981     RRC = &ARM::DPRRegClass;
982     // When NEON is used for SP, only half of the register file is available
983     // because operations that define both SP and DP results will be constrained
984     // to the VFP2 class (D0-D15). We currently model this constraint prior to
985     // coalescing by double-counting the SP regs. See the FIXME above.
986     if (Subtarget->useNEONForSinglePrecisionFP())
987       Cost = 2;
988     break;
989   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990   case MVT::v4f32: case MVT::v2f64:
991     RRC = &ARM::DPRRegClass;
992     Cost = 2;
993     break;
994   case MVT::v4i64:
995     RRC = &ARM::DPRRegClass;
996     Cost = 4;
997     break;
998   case MVT::v8i64:
999     RRC = &ARM::DPRRegClass;
1000     Cost = 8;
1001     break;
1002   }
1003   return std::make_pair(RRC, Cost);
1004 }
1005
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007   switch (Opcode) {
1008   default: return nullptr;
1009   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1010   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1011   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1012   case ARMISD::CALL:          return "ARMISD::CALL";
1013   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1014   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1015   case ARMISD::tCALL:         return "ARMISD::tCALL";
1016   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1017   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1018   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1019   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1020   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1021   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1022   case ARMISD::CMP:           return "ARMISD::CMP";
1023   case ARMISD::CMN:           return "ARMISD::CMN";
1024   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1025   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1026   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1027   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1028   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1029
1030   case ARMISD::CMOV:          return "ARMISD::CMOV";
1031
1032   case ARMISD::RBIT:          return "ARMISD::RBIT";
1033
1034   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1035   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1036   case ARMISD::SITOF:         return "ARMISD::SITOF";
1037   case ARMISD::UITOF:         return "ARMISD::UITOF";
1038
1039   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1040   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1041   case ARMISD::RRX:           return "ARMISD::RRX";
1042
1043   case ARMISD::ADDC:          return "ARMISD::ADDC";
1044   case ARMISD::ADDE:          return "ARMISD::ADDE";
1045   case ARMISD::SUBC:          return "ARMISD::SUBC";
1046   case ARMISD::SUBE:          return "ARMISD::SUBE";
1047
1048   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1049   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1050
1051   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1052   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1053
1054   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1055
1056   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1057
1058   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1059
1060   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1061
1062   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1063
1064   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1065
1066   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1067   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1068   case ARMISD::VCGE:          return "ARMISD::VCGE";
1069   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1070   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1071   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1072   case ARMISD::VCGT:          return "ARMISD::VCGT";
1073   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1074   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1075   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1076   case ARMISD::VTST:          return "ARMISD::VTST";
1077
1078   case ARMISD::VSHL:          return "ARMISD::VSHL";
1079   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1080   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII =
1197       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1198   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1199
1200   if (MCID.getNumDefs() == 0)
1201     return Sched::RegPressure;
1202   if (!Itins->isEmpty() &&
1203       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1204     return Sched::ILP;
1205
1206   return Sched::RegPressure;
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 // Lowering Code
1211 //===----------------------------------------------------------------------===//
1212
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1215   switch (CC) {
1216   default: llvm_unreachable("Unknown condition code!");
1217   case ISD::SETNE:  return ARMCC::NE;
1218   case ISD::SETEQ:  return ARMCC::EQ;
1219   case ISD::SETGT:  return ARMCC::GT;
1220   case ISD::SETGE:  return ARMCC::GE;
1221   case ISD::SETLT:  return ARMCC::LT;
1222   case ISD::SETLE:  return ARMCC::LE;
1223   case ISD::SETUGT: return ARMCC::HI;
1224   case ISD::SETUGE: return ARMCC::HS;
1225   case ISD::SETULT: return ARMCC::LO;
1226   case ISD::SETULE: return ARMCC::LS;
1227   }
1228 }
1229
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232                         ARMCC::CondCodes &CondCode2) {
1233   CondCode2 = ARMCC::AL;
1234   switch (CC) {
1235   default: llvm_unreachable("Unknown FP condition!");
1236   case ISD::SETEQ:
1237   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1238   case ISD::SETGT:
1239   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1240   case ISD::SETGE:
1241   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245   case ISD::SETO:   CondCode = ARMCC::VC; break;
1246   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1247   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1250   case ISD::SETLT:
1251   case ISD::SETULT: CondCode = ARMCC::LT; break;
1252   case ISD::SETLE:
1253   case ISD::SETULE: CondCode = ARMCC::LE; break;
1254   case ISD::SETNE:
1255   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1256   }
1257 }
1258
1259 //===----------------------------------------------------------------------===//
1260 //                      Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1262
1263 #include "ARMGenCallingConv.inc"
1264
1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1266 /// account presence of floating point hardware and calling convention
1267 /// limitations, such as support for variadic functions.
1268 CallingConv::ID
1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1270                                            bool isVarArg) const {
1271   switch (CC) {
1272   default:
1273     llvm_unreachable("Unsupported calling convention");
1274   case CallingConv::ARM_AAPCS:
1275   case CallingConv::ARM_APCS:
1276   case CallingConv::GHC:
1277     return CC;
1278   case CallingConv::ARM_AAPCS_VFP:
1279     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1280   case CallingConv::C:
1281     if (!Subtarget->isAAPCS_ABI())
1282       return CallingConv::ARM_APCS;
1283     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1284              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1285              !isVarArg)
1286       return CallingConv::ARM_AAPCS_VFP;
1287     else
1288       return CallingConv::ARM_AAPCS;
1289   case CallingConv::Fast:
1290     if (!Subtarget->isAAPCS_ABI()) {
1291       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292         return CallingConv::Fast;
1293       return CallingConv::ARM_APCS;
1294     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295       return CallingConv::ARM_AAPCS_VFP;
1296     else
1297       return CallingConv::ARM_AAPCS;
1298   }
1299 }
1300
1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1302 /// CallingConvention.
1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1304                                                  bool Return,
1305                                                  bool isVarArg) const {
1306   switch (getEffectiveCallingConv(CC, isVarArg)) {
1307   default:
1308     llvm_unreachable("Unsupported calling convention");
1309   case CallingConv::ARM_APCS:
1310     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1311   case CallingConv::ARM_AAPCS:
1312     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1313   case CallingConv::ARM_AAPCS_VFP:
1314     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1315   case CallingConv::Fast:
1316     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1317   case CallingConv::GHC:
1318     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1319   }
1320 }
1321
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1324 SDValue
1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1326                                    CallingConv::ID CallConv, bool isVarArg,
1327                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1328                                    SDLoc dl, SelectionDAG &DAG,
1329                                    SmallVectorImpl<SDValue> &InVals,
1330                                    bool isThisReturn, SDValue ThisVal) const {
1331
1332   // Assign locations to each value returned by this call.
1333   SmallVector<CCValAssign, 16> RVLocs;
1334   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1335                     *DAG.getContext(), Call);
1336   CCInfo.AnalyzeCallResult(Ins,
1337                            CCAssignFnForNode(CallConv, /* Return*/ true,
1338                                              isVarArg));
1339
1340   // Copy all of the result registers out of their specified physreg.
1341   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1342     CCValAssign VA = RVLocs[i];
1343
1344     // Pass 'this' value directly from the argument to return value, to avoid
1345     // reg unit interference
1346     if (i == 0 && isThisReturn) {
1347       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1348              "unexpected return calling convention register assignment");
1349       InVals.push_back(ThisVal);
1350       continue;
1351     }
1352
1353     SDValue Val;
1354     if (VA.needsCustom()) {
1355       // Handle f64 or half of a v2f64.
1356       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1357                                       InFlag);
1358       Chain = Lo.getValue(1);
1359       InFlag = Lo.getValue(2);
1360       VA = RVLocs[++i]; // skip ahead to next loc
1361       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1362                                       InFlag);
1363       Chain = Hi.getValue(1);
1364       InFlag = Hi.getValue(2);
1365       if (!Subtarget->isLittle())
1366         std::swap (Lo, Hi);
1367       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1368
1369       if (VA.getLocVT() == MVT::v2f64) {
1370         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1371         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1372                           DAG.getConstant(0, MVT::i32));
1373
1374         VA = RVLocs[++i]; // skip ahead to next loc
1375         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376         Chain = Lo.getValue(1);
1377         InFlag = Lo.getValue(2);
1378         VA = RVLocs[++i]; // skip ahead to next loc
1379         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1380         Chain = Hi.getValue(1);
1381         InFlag = Hi.getValue(2);
1382         if (!Subtarget->isLittle())
1383           std::swap (Lo, Hi);
1384         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1385         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386                           DAG.getConstant(1, MVT::i32));
1387       }
1388     } else {
1389       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1390                                InFlag);
1391       Chain = Val.getValue(1);
1392       InFlag = Val.getValue(2);
1393     }
1394
1395     switch (VA.getLocInfo()) {
1396     default: llvm_unreachable("Unknown loc info!");
1397     case CCValAssign::Full: break;
1398     case CCValAssign::BCvt:
1399       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1400       break;
1401     }
1402
1403     InVals.push_back(Val);
1404   }
1405
1406   return Chain;
1407 }
1408
1409 /// LowerMemOpCallTo - Store the argument to the stack.
1410 SDValue
1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1412                                     SDValue StackPtr, SDValue Arg,
1413                                     SDLoc dl, SelectionDAG &DAG,
1414                                     const CCValAssign &VA,
1415                                     ISD::ArgFlagsTy Flags) const {
1416   unsigned LocMemOffset = VA.getLocMemOffset();
1417   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1419   return DAG.getStore(Chain, dl, Arg, PtrOff,
1420                       MachinePointerInfo::getStack(LocMemOffset),
1421                       false, false, 0);
1422 }
1423
1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1425                                          SDValue Chain, SDValue &Arg,
1426                                          RegsToPassVector &RegsToPass,
1427                                          CCValAssign &VA, CCValAssign &NextVA,
1428                                          SDValue &StackPtr,
1429                                          SmallVectorImpl<SDValue> &MemOpChains,
1430                                          ISD::ArgFlagsTy Flags) const {
1431
1432   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1433                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1434   unsigned id = Subtarget->isLittle() ? 0 : 1;
1435   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1436
1437   if (NextVA.isRegLoc())
1438     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1439   else {
1440     assert(NextVA.isMemLoc());
1441     if (!StackPtr.getNode())
1442       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1443
1444     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1445                                            dl, DAG, NextVA,
1446                                            Flags));
1447   }
1448 }
1449
1450 /// LowerCall - Lowering a call into a callseq_start <-
1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1452 /// nodes.
1453 SDValue
1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1455                              SmallVectorImpl<SDValue> &InVals) const {
1456   SelectionDAG &DAG                     = CLI.DAG;
1457   SDLoc &dl                          = CLI.DL;
1458   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1459   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1460   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1461   SDValue Chain                         = CLI.Chain;
1462   SDValue Callee                        = CLI.Callee;
1463   bool &isTailCall                      = CLI.IsTailCall;
1464   CallingConv::ID CallConv              = CLI.CallConv;
1465   bool doesNotRet                       = CLI.DoesNotReturn;
1466   bool isVarArg                         = CLI.IsVarArg;
1467
1468   MachineFunction &MF = DAG.getMachineFunction();
1469   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1470   bool isThisReturn   = false;
1471   bool isSibCall      = false;
1472
1473   // Disable tail calls if they're not supported.
1474   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1475     isTailCall = false;
1476
1477   if (isTailCall) {
1478     // Check if it's really possible to do a tail call.
1479     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1480                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1481                                                    Outs, OutVals, Ins, DAG);
1482     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1483       report_fatal_error("failed to perform tail call elimination on a call "
1484                          "site marked musttail");
1485     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1486     // detected sibcalls.
1487     if (isTailCall) {
1488       ++NumTailCalls;
1489       isSibCall = true;
1490     }
1491   }
1492
1493   // Analyze operands of the call, assigning locations to each operand.
1494   SmallVector<CCValAssign, 16> ArgLocs;
1495   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1496                     *DAG.getContext(), Call);
1497   CCInfo.AnalyzeCallOperands(Outs,
1498                              CCAssignFnForNode(CallConv, /* Return*/ false,
1499                                                isVarArg));
1500
1501   // Get a count of how many bytes are to be pushed on the stack.
1502   unsigned NumBytes = CCInfo.getNextStackOffset();
1503
1504   // For tail calls, memory operands are available in our caller's stack.
1505   if (isSibCall)
1506     NumBytes = 0;
1507
1508   // Adjust the stack pointer for the new arguments...
1509   // These operations are automatically eliminated by the prolog/epilog pass
1510   if (!isSibCall)
1511     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1512                                  dl);
1513
1514   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1515
1516   RegsToPassVector RegsToPass;
1517   SmallVector<SDValue, 8> MemOpChains;
1518
1519   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1520   // of tail call optimization, arguments are handled later.
1521   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1522        i != e;
1523        ++i, ++realArgIdx) {
1524     CCValAssign &VA = ArgLocs[i];
1525     SDValue Arg = OutVals[realArgIdx];
1526     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1527     bool isByVal = Flags.isByVal();
1528
1529     // Promote the value if needed.
1530     switch (VA.getLocInfo()) {
1531     default: llvm_unreachable("Unknown loc info!");
1532     case CCValAssign::Full: break;
1533     case CCValAssign::SExt:
1534       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1535       break;
1536     case CCValAssign::ZExt:
1537       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::AExt:
1540       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1541       break;
1542     case CCValAssign::BCvt:
1543       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1544       break;
1545     }
1546
1547     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1548     if (VA.needsCustom()) {
1549       if (VA.getLocVT() == MVT::v2f64) {
1550         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1551                                   DAG.getConstant(0, MVT::i32));
1552         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553                                   DAG.getConstant(1, MVT::i32));
1554
1555         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1556                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1557
1558         VA = ArgLocs[++i]; // skip ahead to next loc
1559         if (VA.isRegLoc()) {
1560           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1561                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1562         } else {
1563           assert(VA.isMemLoc());
1564
1565           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1566                                                  dl, DAG, VA, Flags));
1567         }
1568       } else {
1569         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1570                          StackPtr, MemOpChains, Flags);
1571       }
1572     } else if (VA.isRegLoc()) {
1573       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1574         assert(VA.getLocVT() == MVT::i32 &&
1575                "unexpected calling convention register assignment");
1576         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1577                "unexpected use of 'returned'");
1578         isThisReturn = true;
1579       }
1580       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1581     } else if (isByVal) {
1582       assert(VA.isMemLoc());
1583       unsigned offset = 0;
1584
1585       // True if this byval aggregate will be split between registers
1586       // and memory.
1587       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1588       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1589
1590       if (CurByValIdx < ByValArgsCount) {
1591
1592         unsigned RegBegin, RegEnd;
1593         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1594
1595         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1596         unsigned int i, j;
1597         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1598           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1599           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1600           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1601                                      MachinePointerInfo(),
1602                                      false, false, false,
1603                                      DAG.InferPtrAlignment(AddArg));
1604           MemOpChains.push_back(Load.getValue(1));
1605           RegsToPass.push_back(std::make_pair(j, Load));
1606         }
1607
1608         // If parameter size outsides register area, "offset" value
1609         // helps us to calculate stack slot for remained part properly.
1610         offset = RegEnd - RegBegin;
1611
1612         CCInfo.nextInRegsParam();
1613       }
1614
1615       if (Flags.getByValSize() > 4*offset) {
1616         unsigned LocMemOffset = VA.getLocMemOffset();
1617         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1618         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1619                                   StkPtrOff);
1620         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1621         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1622         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1623                                            MVT::i32);
1624         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1625
1626         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1627         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1628         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1629                                           Ops));
1630       }
1631     } else if (!isSibCall) {
1632       assert(VA.isMemLoc());
1633
1634       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1635                                              dl, DAG, VA, Flags));
1636     }
1637   }
1638
1639   if (!MemOpChains.empty())
1640     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1641
1642   // Build a sequence of copy-to-reg nodes chained together with token chain
1643   // and flag operands which copy the outgoing args into the appropriate regs.
1644   SDValue InFlag;
1645   // Tail call byval lowering might overwrite argument registers so in case of
1646   // tail call optimization the copies to registers are lowered later.
1647   if (!isTailCall)
1648     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1649       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1650                                RegsToPass[i].second, InFlag);
1651       InFlag = Chain.getValue(1);
1652     }
1653
1654   // For tail calls lower the arguments to the 'real' stack slot.
1655   if (isTailCall) {
1656     // Force all the incoming stack arguments to be loaded from the stack
1657     // before any new outgoing arguments are stored to the stack, because the
1658     // outgoing stack slots may alias the incoming argument stack slots, and
1659     // the alias isn't otherwise explicit. This is slightly more conservative
1660     // than necessary, because it means that each store effectively depends
1661     // on every argument instead of just those arguments it would clobber.
1662
1663     // Do not flag preceding copytoreg stuff together with the following stuff.
1664     InFlag = SDValue();
1665     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667                                RegsToPass[i].second, InFlag);
1668       InFlag = Chain.getValue(1);
1669     }
1670     InFlag = SDValue();
1671   }
1672
1673   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1674   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1675   // node so that legalize doesn't hack it.
1676   bool isDirect = false;
1677   bool isARMFunc = false;
1678   bool isLocalARMFunc = false;
1679   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1680
1681   if (EnableARMLongCalls) {
1682     assert((Subtarget->isTargetWindows() ||
1683             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1684            "long-calls with non-static relocation model!");
1685     // Handle a global address or an external symbol. If it's not one of
1686     // those, the target's already in a register, so we don't need to do
1687     // anything extra.
1688     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689       const GlobalValue *GV = G->getGlobal();
1690       // Create a constant pool entry for the callee address
1691       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1692       ARMConstantPoolValue *CPV =
1693         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1694
1695       // Get the address of the callee into a register
1696       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698       Callee = DAG.getLoad(getPointerTy(), dl,
1699                            DAG.getEntryNode(), CPAddr,
1700                            MachinePointerInfo::getConstantPool(),
1701                            false, false, false, 0);
1702     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1703       const char *Sym = S->getSymbol();
1704
1705       // Create a constant pool entry for the callee address
1706       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707       ARMConstantPoolValue *CPV =
1708         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1709                                       ARMPCLabelIndex, 0);
1710       // Get the address of the callee into a register
1711       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713       Callee = DAG.getLoad(getPointerTy(), dl,
1714                            DAG.getEntryNode(), CPAddr,
1715                            MachinePointerInfo::getConstantPool(),
1716                            false, false, false, 0);
1717     }
1718   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1719     const GlobalValue *GV = G->getGlobal();
1720     isDirect = true;
1721     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1722     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1723                    getTargetMachine().getRelocationModel() != Reloc::Static;
1724     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1725     // ARM call to a local ARM function is predicable.
1726     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1727     // tBX takes a register source operand.
1728     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1730       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1731                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1732                                                       0, ARMII::MO_NONLAZY));
1733       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1734                            MachinePointerInfo::getGOT(), false, false, true, 0);
1735     } else if (Subtarget->isTargetCOFF()) {
1736       assert(Subtarget->isTargetWindows() &&
1737              "Windows is the only supported COFF target");
1738       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1739                                  ? ARMII::MO_DLLIMPORT
1740                                  : ARMII::MO_NO_FLAG;
1741       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1742                                           TargetFlags);
1743       if (GV->hasDLLImportStorageClass())
1744         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1745                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1746                                          Callee), MachinePointerInfo::getGOT(),
1747                              false, false, false, 0);
1748     } else {
1749       // On ELF targets for PIC code, direct calls should go through the PLT
1750       unsigned OpFlags = 0;
1751       if (Subtarget->isTargetELF() &&
1752           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1753         OpFlags = ARMII::MO_PLT;
1754       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1755     }
1756   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1757     isDirect = true;
1758     bool isStub = Subtarget->isTargetMachO() &&
1759                   getTargetMachine().getRelocationModel() != Reloc::Static;
1760     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1761     // tBX takes a register source operand.
1762     const char *Sym = S->getSymbol();
1763     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1764       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765       ARMConstantPoolValue *CPV =
1766         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1767                                       ARMPCLabelIndex, 4);
1768       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1769       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1770       Callee = DAG.getLoad(getPointerTy(), dl,
1771                            DAG.getEntryNode(), CPAddr,
1772                            MachinePointerInfo::getConstantPool(),
1773                            false, false, false, 0);
1774       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1775       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1776                            getPointerTy(), Callee, PICLabel);
1777     } else {
1778       unsigned OpFlags = 0;
1779       // On ELF targets for PIC code, direct calls should go through the PLT
1780       if (Subtarget->isTargetELF() &&
1781                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1782         OpFlags = ARMII::MO_PLT;
1783       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1784     }
1785   }
1786
1787   // FIXME: handle tail calls differently.
1788   unsigned CallOpc;
1789   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1790       AttributeSet::FunctionIndex, Attribute::MinSize);
1791   if (Subtarget->isThumb()) {
1792     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1793       CallOpc = ARMISD::CALL_NOLINK;
1794     else
1795       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1796   } else {
1797     if (!isDirect && !Subtarget->hasV5TOps())
1798       CallOpc = ARMISD::CALL_NOLINK;
1799     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1800                // Emit regular call when code size is the priority
1801                !HasMinSizeAttr)
1802       // "mov lr, pc; b _foo" to avoid confusing the RSP
1803       CallOpc = ARMISD::CALL_NOLINK;
1804     else
1805       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1806   }
1807
1808   std::vector<SDValue> Ops;
1809   Ops.push_back(Chain);
1810   Ops.push_back(Callee);
1811
1812   // Add argument registers to the end of the list so that they are known live
1813   // into the call.
1814   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1815     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1816                                   RegsToPass[i].second.getValueType()));
1817
1818   // Add a register mask operand representing the call-preserved registers.
1819   if (!isTailCall) {
1820     const uint32_t *Mask;
1821     const TargetRegisterInfo *TRI =
1822         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1823     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1824     if (isThisReturn) {
1825       // For 'this' returns, use the R0-preserving mask if applicable
1826       Mask = ARI->getThisReturnPreservedMask(CallConv);
1827       if (!Mask) {
1828         // Set isThisReturn to false if the calling convention is not one that
1829         // allows 'returned' to be modeled in this way, so LowerCallResult does
1830         // not try to pass 'this' straight through
1831         isThisReturn = false;
1832         Mask = ARI->getCallPreservedMask(CallConv);
1833       }
1834     } else
1835       Mask = ARI->getCallPreservedMask(CallConv);
1836
1837     assert(Mask && "Missing call preserved mask for calling convention");
1838     Ops.push_back(DAG.getRegisterMask(Mask));
1839   }
1840
1841   if (InFlag.getNode())
1842     Ops.push_back(InFlag);
1843
1844   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845   if (isTailCall)
1846     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1847
1848   // Returns a chain and a flag for retval copy to use.
1849   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850   InFlag = Chain.getValue(1);
1851
1852   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1854   if (!Ins.empty())
1855     InFlag = Chain.getValue(1);
1856
1857   // Handle result values, copying them out of physregs into vregs that we
1858   // return.
1859   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860                          InVals, isThisReturn,
1861                          isThisReturn ? OutVals[0] : SDValue());
1862 }
1863
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack.  Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1867 /// this.
1868 void
1869 ARMTargetLowering::HandleByVal(
1870     CCState *State, unsigned &size, unsigned Align) const {
1871   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1872   assert((State->getCallOrPrologue() == Prologue ||
1873           State->getCallOrPrologue() == Call) &&
1874          "unhandled ParmContext");
1875
1876   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1877     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1878       unsigned AlignInRegs = Align / 4;
1879       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1880       for (unsigned i = 0; i < Waste; ++i)
1881         reg = State->AllocateReg(GPRArgRegs, 4);
1882     }
1883     if (reg != 0) {
1884       unsigned excess = 4 * (ARM::R4 - reg);
1885
1886       // Special case when NSAA != SP and parameter size greater than size of
1887       // all remained GPR regs. In that case we can't split parameter, we must
1888       // send it to stack. We also must set NCRN to R4, so waste all
1889       // remained registers.
1890       const unsigned NSAAOffset = State->getNextStackOffset();
1891       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1892         while (State->AllocateReg(GPRArgRegs, 4))
1893           ;
1894         return;
1895       }
1896
1897       // First register for byval parameter is the first register that wasn't
1898       // allocated before this method call, so it would be "reg".
1899       // If parameter is small enough to be saved in range [reg, r4), then
1900       // the end (first after last) register would be reg + param-size-in-regs,
1901       // else parameter would be splitted between registers and stack,
1902       // end register would be r4 in this case.
1903       unsigned ByValRegBegin = reg;
1904       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1905       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1906       // Note, first register is allocated in the beginning of function already,
1907       // allocate remained amount of registers we need.
1908       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1909         State->AllocateReg(GPRArgRegs, 4);
1910       // A byval parameter that is split between registers and memory needs its
1911       // size truncated here.
1912       // In the case where the entire structure fits in registers, we set the
1913       // size in memory to zero.
1914       if (size < excess)
1915         size = 0;
1916       else
1917         size -= excess;
1918     }
1919   }
1920 }
1921
1922 /// MatchingStackOffset - Return true if the given stack call argument is
1923 /// already available in the same position (relatively) of the caller's
1924 /// incoming argument stack.
1925 static
1926 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1927                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1928                          const TargetInstrInfo *TII) {
1929   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1930   int FI = INT_MAX;
1931   if (Arg.getOpcode() == ISD::CopyFromReg) {
1932     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1933     if (!TargetRegisterInfo::isVirtualRegister(VR))
1934       return false;
1935     MachineInstr *Def = MRI->getVRegDef(VR);
1936     if (!Def)
1937       return false;
1938     if (!Flags.isByVal()) {
1939       if (!TII->isLoadFromStackSlot(Def, FI))
1940         return false;
1941     } else {
1942       return false;
1943     }
1944   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1945     if (Flags.isByVal())
1946       // ByVal argument is passed in as a pointer but it's now being
1947       // dereferenced. e.g.
1948       // define @foo(%struct.X* %A) {
1949       //   tail call @bar(%struct.X* byval %A)
1950       // }
1951       return false;
1952     SDValue Ptr = Ld->getBasePtr();
1953     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1954     if (!FINode)
1955       return false;
1956     FI = FINode->getIndex();
1957   } else
1958     return false;
1959
1960   assert(FI != INT_MAX);
1961   if (!MFI->isFixedObjectIndex(FI))
1962     return false;
1963   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1964 }
1965
1966 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1967 /// for tail call optimization. Targets which want to do tail call
1968 /// optimization should implement this function.
1969 bool
1970 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1971                                                      CallingConv::ID CalleeCC,
1972                                                      bool isVarArg,
1973                                                      bool isCalleeStructRet,
1974                                                      bool isCallerStructRet,
1975                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                     const SmallVectorImpl<SDValue> &OutVals,
1977                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1978                                                      SelectionDAG& DAG) const {
1979   const Function *CallerF = DAG.getMachineFunction().getFunction();
1980   CallingConv::ID CallerCC = CallerF->getCallingConv();
1981   bool CCMatch = CallerCC == CalleeCC;
1982
1983   // Look for obvious safe cases to perform tail call optimization that do not
1984   // require ABI changes. This is what gcc calls sibcall.
1985
1986   // Do not sibcall optimize vararg calls unless the call site is not passing
1987   // any arguments.
1988   if (isVarArg && !Outs.empty())
1989     return false;
1990
1991   // Exception-handling functions need a special set of instructions to indicate
1992   // a return to the hardware. Tail-calling another function would probably
1993   // break this.
1994   if (CallerF->hasFnAttribute("interrupt"))
1995     return false;
1996
1997   // Also avoid sibcall optimization if either caller or callee uses struct
1998   // return semantics.
1999   if (isCalleeStructRet || isCallerStructRet)
2000     return false;
2001
2002   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2003   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2004   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2005   // support in the assembler and linker to be used. This would need to be
2006   // fixed to fully support tail calls in Thumb1.
2007   //
2008   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2009   // LR.  This means if we need to reload LR, it takes an extra instructions,
2010   // which outweighs the value of the tail call; but here we don't know yet
2011   // whether LR is going to be used.  Probably the right approach is to
2012   // generate the tail call here and turn it back into CALL/RET in
2013   // emitEpilogue if LR is used.
2014
2015   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2016   // but we need to make sure there are enough registers; the only valid
2017   // registers are the 4 used for parameters.  We don't currently do this
2018   // case.
2019   if (Subtarget->isThumb1Only())
2020     return false;
2021
2022   // Externally-defined functions with weak linkage should not be
2023   // tail-called on ARM when the OS does not support dynamic
2024   // pre-emption of symbols, as the AAELF spec requires normal calls
2025   // to undefined weak functions to be replaced with a NOP or jump to the
2026   // next instruction. The behaviour of branch instructions in this
2027   // situation (as used for tail calls) is implementation-defined, so we
2028   // cannot rely on the linker replacing the tail call with a return.
2029   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2030     const GlobalValue *GV = G->getGlobal();
2031     if (GV->hasExternalWeakLinkage())
2032       return false;
2033   }
2034
2035   // If the calling conventions do not match, then we'd better make sure the
2036   // results are returned in the same way as what the caller expects.
2037   if (!CCMatch) {
2038     SmallVector<CCValAssign, 16> RVLocs1;
2039     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2040                        *DAG.getContext(), Call);
2041     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2042
2043     SmallVector<CCValAssign, 16> RVLocs2;
2044     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2045                        *DAG.getContext(), Call);
2046     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2047
2048     if (RVLocs1.size() != RVLocs2.size())
2049       return false;
2050     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2051       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2052         return false;
2053       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2054         return false;
2055       if (RVLocs1[i].isRegLoc()) {
2056         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2057           return false;
2058       } else {
2059         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2060           return false;
2061       }
2062     }
2063   }
2064
2065   // If Caller's vararg or byval argument has been split between registers and
2066   // stack, do not perform tail call, since part of the argument is in caller's
2067   // local frame.
2068   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2069                                       getInfo<ARMFunctionInfo>();
2070   if (AFI_Caller->getArgRegsSaveSize())
2071     return false;
2072
2073   // If the callee takes no arguments then go on to check the results of the
2074   // call.
2075   if (!Outs.empty()) {
2076     // Check if stack adjustment is needed. For now, do not do this if any
2077     // argument is passed on the stack.
2078     SmallVector<CCValAssign, 16> ArgLocs;
2079     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2080                       *DAG.getContext(), Call);
2081     CCInfo.AnalyzeCallOperands(Outs,
2082                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2083     if (CCInfo.getNextStackOffset()) {
2084       MachineFunction &MF = DAG.getMachineFunction();
2085
2086       // Check if the arguments are already laid out in the right way as
2087       // the caller's fixed stack objects.
2088       MachineFrameInfo *MFI = MF.getFrameInfo();
2089       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2090       const TargetInstrInfo *TII =
2091           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2092       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2093            i != e;
2094            ++i, ++realArgIdx) {
2095         CCValAssign &VA = ArgLocs[i];
2096         EVT RegVT = VA.getLocVT();
2097         SDValue Arg = OutVals[realArgIdx];
2098         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2099         if (VA.getLocInfo() == CCValAssign::Indirect)
2100           return false;
2101         if (VA.needsCustom()) {
2102           // f64 and vector types are split into multiple registers or
2103           // register/stack-slot combinations.  The types will not match
2104           // the registers; give up on memory f64 refs until we figure
2105           // out what to do about this.
2106           if (!VA.isRegLoc())
2107             return false;
2108           if (!ArgLocs[++i].isRegLoc())
2109             return false;
2110           if (RegVT == MVT::v2f64) {
2111             if (!ArgLocs[++i].isRegLoc())
2112               return false;
2113             if (!ArgLocs[++i].isRegLoc())
2114               return false;
2115           }
2116         } else if (!VA.isRegLoc()) {
2117           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2118                                    MFI, MRI, TII))
2119             return false;
2120         }
2121       }
2122     }
2123   }
2124
2125   return true;
2126 }
2127
2128 bool
2129 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2130                                   MachineFunction &MF, bool isVarArg,
2131                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2132                                   LLVMContext &Context) const {
2133   SmallVector<CCValAssign, 16> RVLocs;
2134   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2135   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2136                                                     isVarArg));
2137 }
2138
2139 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2140                                     SDLoc DL, SelectionDAG &DAG) {
2141   const MachineFunction &MF = DAG.getMachineFunction();
2142   const Function *F = MF.getFunction();
2143
2144   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2145
2146   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2147   // version of the "preferred return address". These offsets affect the return
2148   // instruction if this is a return from PL1 without hypervisor extensions.
2149   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2150   //    SWI:     0      "subs pc, lr, #0"
2151   //    ABORT:   +4     "subs pc, lr, #4"
2152   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2153   // UNDEF varies depending on where the exception came from ARM or Thumb
2154   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2155
2156   int64_t LROffset;
2157   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2158       IntKind == "ABORT")
2159     LROffset = 4;
2160   else if (IntKind == "SWI" || IntKind == "UNDEF")
2161     LROffset = 0;
2162   else
2163     report_fatal_error("Unsupported interrupt attribute. If present, value "
2164                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2165
2166   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2167
2168   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2169 }
2170
2171 SDValue
2172 ARMTargetLowering::LowerReturn(SDValue Chain,
2173                                CallingConv::ID CallConv, bool isVarArg,
2174                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2175                                const SmallVectorImpl<SDValue> &OutVals,
2176                                SDLoc dl, SelectionDAG &DAG) const {
2177
2178   // CCValAssign - represent the assignment of the return value to a location.
2179   SmallVector<CCValAssign, 16> RVLocs;
2180
2181   // CCState - Info about the registers and stack slots.
2182   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2183                     *DAG.getContext(), Call);
2184
2185   // Analyze outgoing return values.
2186   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2187                                                isVarArg));
2188
2189   SDValue Flag;
2190   SmallVector<SDValue, 4> RetOps;
2191   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2192   bool isLittleEndian = Subtarget->isLittle();
2193
2194   MachineFunction &MF = DAG.getMachineFunction();
2195   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2196   AFI->setReturnRegsCount(RVLocs.size());
2197
2198   // Copy the result values into the output registers.
2199   for (unsigned i = 0, realRVLocIdx = 0;
2200        i != RVLocs.size();
2201        ++i, ++realRVLocIdx) {
2202     CCValAssign &VA = RVLocs[i];
2203     assert(VA.isRegLoc() && "Can only return in registers!");
2204
2205     SDValue Arg = OutVals[realRVLocIdx];
2206
2207     switch (VA.getLocInfo()) {
2208     default: llvm_unreachable("Unknown loc info!");
2209     case CCValAssign::Full: break;
2210     case CCValAssign::BCvt:
2211       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2212       break;
2213     }
2214
2215     if (VA.needsCustom()) {
2216       if (VA.getLocVT() == MVT::v2f64) {
2217         // Extract the first half and return it in two registers.
2218         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2219                                    DAG.getConstant(0, MVT::i32));
2220         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2221                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2222
2223         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2224                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2225                                  Flag);
2226         Flag = Chain.getValue(1);
2227         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2228         VA = RVLocs[++i]; // skip ahead to next loc
2229         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2230                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2231                                  Flag);
2232         Flag = Chain.getValue(1);
2233         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2234         VA = RVLocs[++i]; // skip ahead to next loc
2235
2236         // Extract the 2nd half and fall through to handle it as an f64 value.
2237         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2238                           DAG.getConstant(1, MVT::i32));
2239       }
2240       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2241       // available.
2242       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2243                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2244       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2245                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2246                                Flag);
2247       Flag = Chain.getValue(1);
2248       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2249       VA = RVLocs[++i]; // skip ahead to next loc
2250       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2251                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2252                                Flag);
2253     } else
2254       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2255
2256     // Guarantee that all emitted copies are
2257     // stuck together, avoiding something bad.
2258     Flag = Chain.getValue(1);
2259     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2260   }
2261
2262   // Update chain and glue.
2263   RetOps[0] = Chain;
2264   if (Flag.getNode())
2265     RetOps.push_back(Flag);
2266
2267   // CPUs which aren't M-class use a special sequence to return from
2268   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2269   // though we use "subs pc, lr, #N").
2270   //
2271   // M-class CPUs actually use a normal return sequence with a special
2272   // (hardware-provided) value in LR, so the normal code path works.
2273   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2274       !Subtarget->isMClass()) {
2275     if (Subtarget->isThumb1Only())
2276       report_fatal_error("interrupt attribute is not supported in Thumb1");
2277     return LowerInterruptReturn(RetOps, dl, DAG);
2278   }
2279
2280   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2281 }
2282
2283 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2284   if (N->getNumValues() != 1)
2285     return false;
2286   if (!N->hasNUsesOfValue(1, 0))
2287     return false;
2288
2289   SDValue TCChain = Chain;
2290   SDNode *Copy = *N->use_begin();
2291   if (Copy->getOpcode() == ISD::CopyToReg) {
2292     // If the copy has a glue operand, we conservatively assume it isn't safe to
2293     // perform a tail call.
2294     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2295       return false;
2296     TCChain = Copy->getOperand(0);
2297   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2298     SDNode *VMov = Copy;
2299     // f64 returned in a pair of GPRs.
2300     SmallPtrSet<SDNode*, 2> Copies;
2301     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2302          UI != UE; ++UI) {
2303       if (UI->getOpcode() != ISD::CopyToReg)
2304         return false;
2305       Copies.insert(*UI);
2306     }
2307     if (Copies.size() > 2)
2308       return false;
2309
2310     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2311          UI != UE; ++UI) {
2312       SDValue UseChain = UI->getOperand(0);
2313       if (Copies.count(UseChain.getNode()))
2314         // Second CopyToReg
2315         Copy = *UI;
2316       else {
2317         // We are at the top of this chain.
2318         // If the copy has a glue operand, we conservatively assume it
2319         // isn't safe to perform a tail call.
2320         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2321           return false;
2322         // First CopyToReg
2323         TCChain = UseChain;
2324       }
2325     }
2326   } else if (Copy->getOpcode() == ISD::BITCAST) {
2327     // f32 returned in a single GPR.
2328     if (!Copy->hasOneUse())
2329       return false;
2330     Copy = *Copy->use_begin();
2331     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2332       return false;
2333     // If the copy has a glue operand, we conservatively assume it isn't safe to
2334     // perform a tail call.
2335     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2336       return false;
2337     TCChain = Copy->getOperand(0);
2338   } else {
2339     return false;
2340   }
2341
2342   bool HasRet = false;
2343   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2344        UI != UE; ++UI) {
2345     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2346         UI->getOpcode() != ARMISD::INTRET_FLAG)
2347       return false;
2348     HasRet = true;
2349   }
2350
2351   if (!HasRet)
2352     return false;
2353
2354   Chain = TCChain;
2355   return true;
2356 }
2357
2358 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2359   if (!Subtarget->supportsTailCall())
2360     return false;
2361
2362   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2363     return false;
2364
2365   return !Subtarget->isThumb1Only();
2366 }
2367
2368 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2369 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2370 // one of the above mentioned nodes. It has to be wrapped because otherwise
2371 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2372 // be used to form addressing mode. These wrapped nodes will be selected
2373 // into MOVi.
2374 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2375   EVT PtrVT = Op.getValueType();
2376   // FIXME there is no actual debug info here
2377   SDLoc dl(Op);
2378   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2379   SDValue Res;
2380   if (CP->isMachineConstantPoolEntry())
2381     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2382                                     CP->getAlignment());
2383   else
2384     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2385                                     CP->getAlignment());
2386   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2387 }
2388
2389 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2390   return MachineJumpTableInfo::EK_Inline;
2391 }
2392
2393 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2394                                              SelectionDAG &DAG) const {
2395   MachineFunction &MF = DAG.getMachineFunction();
2396   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2397   unsigned ARMPCLabelIndex = 0;
2398   SDLoc DL(Op);
2399   EVT PtrVT = getPointerTy();
2400   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2401   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2402   SDValue CPAddr;
2403   if (RelocM == Reloc::Static) {
2404     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2405   } else {
2406     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2407     ARMPCLabelIndex = AFI->createPICLabelUId();
2408     ARMConstantPoolValue *CPV =
2409       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2410                                       ARMCP::CPBlockAddress, PCAdj);
2411     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2412   }
2413   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2414   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2415                                MachinePointerInfo::getConstantPool(),
2416                                false, false, false, 0);
2417   if (RelocM == Reloc::Static)
2418     return Result;
2419   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2420   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2421 }
2422
2423 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2424 SDValue
2425 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2426                                                  SelectionDAG &DAG) const {
2427   SDLoc dl(GA);
2428   EVT PtrVT = getPointerTy();
2429   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2430   MachineFunction &MF = DAG.getMachineFunction();
2431   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2432   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2433   ARMConstantPoolValue *CPV =
2434     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2435                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2436   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2437   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2438   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2439                          MachinePointerInfo::getConstantPool(),
2440                          false, false, false, 0);
2441   SDValue Chain = Argument.getValue(1);
2442
2443   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2444   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2445
2446   // call __tls_get_addr.
2447   ArgListTy Args;
2448   ArgListEntry Entry;
2449   Entry.Node = Argument;
2450   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2451   Args.push_back(Entry);
2452
2453   // FIXME: is there useful debug info available here?
2454   TargetLowering::CallLoweringInfo CLI(DAG);
2455   CLI.setDebugLoc(dl).setChain(Chain)
2456     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2457                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2458                0);
2459
2460   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2461   return CallResult.first;
2462 }
2463
2464 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2465 // "local exec" model.
2466 SDValue
2467 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2468                                         SelectionDAG &DAG,
2469                                         TLSModel::Model model) const {
2470   const GlobalValue *GV = GA->getGlobal();
2471   SDLoc dl(GA);
2472   SDValue Offset;
2473   SDValue Chain = DAG.getEntryNode();
2474   EVT PtrVT = getPointerTy();
2475   // Get the Thread Pointer
2476   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2477
2478   if (model == TLSModel::InitialExec) {
2479     MachineFunction &MF = DAG.getMachineFunction();
2480     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2481     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2482     // Initial exec model.
2483     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2484     ARMConstantPoolValue *CPV =
2485       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2486                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2487                                       true);
2488     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2489     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2490     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2491                          MachinePointerInfo::getConstantPool(),
2492                          false, false, false, 0);
2493     Chain = Offset.getValue(1);
2494
2495     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2496     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2497
2498     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2499                          MachinePointerInfo::getConstantPool(),
2500                          false, false, false, 0);
2501   } else {
2502     // local exec model
2503     assert(model == TLSModel::LocalExec);
2504     ARMConstantPoolValue *CPV =
2505       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2506     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2507     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2508     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2509                          MachinePointerInfo::getConstantPool(),
2510                          false, false, false, 0);
2511   }
2512
2513   // The address of the thread local variable is the add of the thread
2514   // pointer with the offset of the variable.
2515   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2516 }
2517
2518 SDValue
2519 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2520   // TODO: implement the "local dynamic" model
2521   assert(Subtarget->isTargetELF() &&
2522          "TLS not implemented for non-ELF targets");
2523   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2524
2525   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2526
2527   switch (model) {
2528     case TLSModel::GeneralDynamic:
2529     case TLSModel::LocalDynamic:
2530       return LowerToTLSGeneralDynamicModel(GA, DAG);
2531     case TLSModel::InitialExec:
2532     case TLSModel::LocalExec:
2533       return LowerToTLSExecModels(GA, DAG, model);
2534   }
2535   llvm_unreachable("bogus TLS model");
2536 }
2537
2538 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2539                                                  SelectionDAG &DAG) const {
2540   EVT PtrVT = getPointerTy();
2541   SDLoc dl(Op);
2542   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2543   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2544     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2545     ARMConstantPoolValue *CPV =
2546       ARMConstantPoolConstant::Create(GV,
2547                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2548     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2549     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2550     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2551                                  CPAddr,
2552                                  MachinePointerInfo::getConstantPool(),
2553                                  false, false, false, 0);
2554     SDValue Chain = Result.getValue(1);
2555     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2556     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2557     if (!UseGOTOFF)
2558       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2559                            MachinePointerInfo::getGOT(),
2560                            false, false, false, 0);
2561     return Result;
2562   }
2563
2564   // If we have T2 ops, we can materialize the address directly via movt/movw
2565   // pair. This is always cheaper.
2566   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2567     ++NumMovwMovt;
2568     // FIXME: Once remat is capable of dealing with instructions with register
2569     // operands, expand this into two nodes.
2570     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2571                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2572   } else {
2573     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2574     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2575     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2576                        MachinePointerInfo::getConstantPool(),
2577                        false, false, false, 0);
2578   }
2579 }
2580
2581 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2582                                                     SelectionDAG &DAG) const {
2583   EVT PtrVT = getPointerTy();
2584   SDLoc dl(Op);
2585   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2586   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2587
2588   if (Subtarget->useMovt(DAG.getMachineFunction()))
2589     ++NumMovwMovt;
2590
2591   // FIXME: Once remat is capable of dealing with instructions with register
2592   // operands, expand this into multiple nodes
2593   unsigned Wrapper =
2594       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2595
2596   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2597   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2598
2599   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2600     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2601                          MachinePointerInfo::getGOT(), false, false, false, 0);
2602   return Result;
2603 }
2604
2605 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2606                                                      SelectionDAG &DAG) const {
2607   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2608   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2609          "Windows on ARM expects to use movw/movt");
2610
2611   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2612   const ARMII::TOF TargetFlags =
2613     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2614   EVT PtrVT = getPointerTy();
2615   SDValue Result;
2616   SDLoc DL(Op);
2617
2618   ++NumMovwMovt;
2619
2620   // FIXME: Once remat is capable of dealing with instructions with register
2621   // operands, expand this into two nodes.
2622   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2623                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2624                                                   TargetFlags));
2625   if (GV->hasDLLImportStorageClass())
2626     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2627                          MachinePointerInfo::getGOT(), false, false, false, 0);
2628   return Result;
2629 }
2630
2631 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2632                                                     SelectionDAG &DAG) const {
2633   assert(Subtarget->isTargetELF() &&
2634          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2635   MachineFunction &MF = DAG.getMachineFunction();
2636   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2637   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2638   EVT PtrVT = getPointerTy();
2639   SDLoc dl(Op);
2640   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2641   ARMConstantPoolValue *CPV =
2642     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2643                                   ARMPCLabelIndex, PCAdj);
2644   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2645   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2646   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2647                                MachinePointerInfo::getConstantPool(),
2648                                false, false, false, 0);
2649   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2650   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2651 }
2652
2653 SDValue
2654 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2655   SDLoc dl(Op);
2656   SDValue Val = DAG.getConstant(0, MVT::i32);
2657   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2658                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2659                      Op.getOperand(1), Val);
2660 }
2661
2662 SDValue
2663 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2664   SDLoc dl(Op);
2665   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2666                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2667 }
2668
2669 SDValue
2670 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2671                                           const ARMSubtarget *Subtarget) const {
2672   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2673   SDLoc dl(Op);
2674   switch (IntNo) {
2675   default: return SDValue();    // Don't custom lower most intrinsics.
2676   case Intrinsic::arm_rbit: {
2677     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2678            "RBIT intrinsic must have i32 type!");
2679     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2680   }
2681   case Intrinsic::arm_thread_pointer: {
2682     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2683     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2684   }
2685   case Intrinsic::eh_sjlj_lsda: {
2686     MachineFunction &MF = DAG.getMachineFunction();
2687     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2688     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2689     EVT PtrVT = getPointerTy();
2690     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2691     SDValue CPAddr;
2692     unsigned PCAdj = (RelocM != Reloc::PIC_)
2693       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2694     ARMConstantPoolValue *CPV =
2695       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2696                                       ARMCP::CPLSDA, PCAdj);
2697     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2698     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2699     SDValue Result =
2700       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2701                   MachinePointerInfo::getConstantPool(),
2702                   false, false, false, 0);
2703
2704     if (RelocM == Reloc::PIC_) {
2705       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2706       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2707     }
2708     return Result;
2709   }
2710   case Intrinsic::arm_neon_vmulls:
2711   case Intrinsic::arm_neon_vmullu: {
2712     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2713       ? ARMISD::VMULLs : ARMISD::VMULLu;
2714     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2715                        Op.getOperand(1), Op.getOperand(2));
2716   }
2717   }
2718 }
2719
2720 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2721                                  const ARMSubtarget *Subtarget) {
2722   // FIXME: handle "fence singlethread" more efficiently.
2723   SDLoc dl(Op);
2724   if (!Subtarget->hasDataBarrier()) {
2725     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2726     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2727     // here.
2728     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2729            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2730     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2731                        DAG.getConstant(0, MVT::i32));
2732   }
2733
2734   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2735   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2736   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2737   if (Subtarget->isMClass()) {
2738     // Only a full system barrier exists in the M-class architectures.
2739     Domain = ARM_MB::SY;
2740   } else if (Subtarget->isSwift() && Ord == Release) {
2741     // Swift happens to implement ISHST barriers in a way that's compatible with
2742     // Release semantics but weaker than ISH so we'd be fools not to use
2743     // it. Beware: other processors probably don't!
2744     Domain = ARM_MB::ISHST;
2745   }
2746
2747   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2748                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2749                      DAG.getConstant(Domain, MVT::i32));
2750 }
2751
2752 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2753                              const ARMSubtarget *Subtarget) {
2754   // ARM pre v5TE and Thumb1 does not have preload instructions.
2755   if (!(Subtarget->isThumb2() ||
2756         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2757     // Just preserve the chain.
2758     return Op.getOperand(0);
2759
2760   SDLoc dl(Op);
2761   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2762   if (!isRead &&
2763       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2764     // ARMv7 with MP extension has PLDW.
2765     return Op.getOperand(0);
2766
2767   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2768   if (Subtarget->isThumb()) {
2769     // Invert the bits.
2770     isRead = ~isRead & 1;
2771     isData = ~isData & 1;
2772   }
2773
2774   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2775                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2776                      DAG.getConstant(isData, MVT::i32));
2777 }
2778
2779 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2780   MachineFunction &MF = DAG.getMachineFunction();
2781   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2782
2783   // vastart just stores the address of the VarArgsFrameIndex slot into the
2784   // memory location argument.
2785   SDLoc dl(Op);
2786   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2787   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2788   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2789   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2790                       MachinePointerInfo(SV), false, false, 0);
2791 }
2792
2793 SDValue
2794 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2795                                         SDValue &Root, SelectionDAG &DAG,
2796                                         SDLoc dl) const {
2797   MachineFunction &MF = DAG.getMachineFunction();
2798   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2799
2800   const TargetRegisterClass *RC;
2801   if (AFI->isThumb1OnlyFunction())
2802     RC = &ARM::tGPRRegClass;
2803   else
2804     RC = &ARM::GPRRegClass;
2805
2806   // Transform the arguments stored in physical registers into virtual ones.
2807   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2808   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2809
2810   SDValue ArgValue2;
2811   if (NextVA.isMemLoc()) {
2812     MachineFrameInfo *MFI = MF.getFrameInfo();
2813     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2814
2815     // Create load node to retrieve arguments from the stack.
2816     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2817     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2818                             MachinePointerInfo::getFixedStack(FI),
2819                             false, false, false, 0);
2820   } else {
2821     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2822     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2823   }
2824   if (!Subtarget->isLittle())
2825     std::swap (ArgValue, ArgValue2);
2826   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2827 }
2828
2829 void
2830 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2831                                   unsigned InRegsParamRecordIdx,
2832                                   unsigned ArgSize,
2833                                   unsigned &ArgRegsSize,
2834                                   unsigned &ArgRegsSaveSize)
2835   const {
2836   unsigned NumGPRs;
2837   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2838     unsigned RBegin, REnd;
2839     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2840     NumGPRs = REnd - RBegin;
2841   } else {
2842     unsigned int firstUnalloced;
2843     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2844                                                 sizeof(GPRArgRegs) /
2845                                                 sizeof(GPRArgRegs[0]));
2846     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2847   }
2848
2849   unsigned Align = MF.getTarget()
2850                        .getSubtargetImpl()
2851                        ->getFrameLowering()
2852                        ->getStackAlignment();
2853   ArgRegsSize = NumGPRs * 4;
2854
2855   // If parameter is split between stack and GPRs...
2856   if (NumGPRs && Align > 4 &&
2857       (ArgRegsSize < ArgSize ||
2858         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2859     // Add padding for part of param recovered from GPRs.  For example,
2860     // if Align == 8, its last byte must be at address K*8 - 1.
2861     // We need to do it, since remained (stack) part of parameter has
2862     // stack alignment, and we need to "attach" "GPRs head" without gaps
2863     // to it:
2864     // Stack:
2865     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2866     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2867     //
2868     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2869     unsigned Padding =
2870         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2871     ArgRegsSaveSize = ArgRegsSize + Padding;
2872   } else
2873     // We don't need to extend regs save size for byval parameters if they
2874     // are passed via GPRs only.
2875     ArgRegsSaveSize = ArgRegsSize;
2876 }
2877
2878 // The remaining GPRs hold either the beginning of variable-argument
2879 // data, or the beginning of an aggregate passed by value (usually
2880 // byval).  Either way, we allocate stack slots adjacent to the data
2881 // provided by our caller, and store the unallocated registers there.
2882 // If this is a variadic function, the va_list pointer will begin with
2883 // these values; otherwise, this reassembles a (byval) structure that
2884 // was split between registers and memory.
2885 // Return: The frame index registers were stored into.
2886 int
2887 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2888                                   SDLoc dl, SDValue &Chain,
2889                                   const Value *OrigArg,
2890                                   unsigned InRegsParamRecordIdx,
2891                                   unsigned OffsetFromOrigArg,
2892                                   unsigned ArgOffset,
2893                                   unsigned ArgSize,
2894                                   bool ForceMutable,
2895                                   unsigned ByValStoreOffset,
2896                                   unsigned TotalArgRegsSaveSize) const {
2897
2898   // Currently, two use-cases possible:
2899   // Case #1. Non-var-args function, and we meet first byval parameter.
2900   //          Setup first unallocated register as first byval register;
2901   //          eat all remained registers
2902   //          (these two actions are performed by HandleByVal method).
2903   //          Then, here, we initialize stack frame with
2904   //          "store-reg" instructions.
2905   // Case #2. Var-args function, that doesn't contain byval parameters.
2906   //          The same: eat all remained unallocated registers,
2907   //          initialize stack frame.
2908
2909   MachineFunction &MF = DAG.getMachineFunction();
2910   MachineFrameInfo *MFI = MF.getFrameInfo();
2911   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2912   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2913   unsigned RBegin, REnd;
2914   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2915     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2916     firstRegToSaveIndex = RBegin - ARM::R0;
2917     lastRegToSaveIndex = REnd - ARM::R0;
2918   } else {
2919     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2920       (GPRArgRegs, array_lengthof(GPRArgRegs));
2921     lastRegToSaveIndex = 4;
2922   }
2923
2924   unsigned ArgRegsSize, ArgRegsSaveSize;
2925   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2926                  ArgRegsSize, ArgRegsSaveSize);
2927
2928   // Store any by-val regs to their spots on the stack so that they may be
2929   // loaded by deferencing the result of formal parameter pointer or va_next.
2930   // Note: once stack area for byval/varargs registers
2931   // was initialized, it can't be initialized again.
2932   if (ArgRegsSaveSize) {
2933     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2934
2935     if (Padding) {
2936       assert(AFI->getStoredByValParamsPadding() == 0 &&
2937              "The only parameter may be padded.");
2938       AFI->setStoredByValParamsPadding(Padding);
2939     }
2940
2941     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2942                                             Padding +
2943                                               ByValStoreOffset -
2944                                               (int64_t)TotalArgRegsSaveSize,
2945                                             false);
2946     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2947     if (Padding) {
2948        MFI->CreateFixedObject(Padding,
2949                               ArgOffset + ByValStoreOffset -
2950                                 (int64_t)ArgRegsSaveSize,
2951                               false);
2952     }
2953
2954     SmallVector<SDValue, 4> MemOps;
2955     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2956          ++firstRegToSaveIndex, ++i) {
2957       const TargetRegisterClass *RC;
2958       if (AFI->isThumb1OnlyFunction())
2959         RC = &ARM::tGPRRegClass;
2960       else
2961         RC = &ARM::GPRRegClass;
2962
2963       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2964       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2965       SDValue Store =
2966         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2967                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2968                      false, false, 0);
2969       MemOps.push_back(Store);
2970       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2971                         DAG.getConstant(4, getPointerTy()));
2972     }
2973
2974     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2975
2976     if (!MemOps.empty())
2977       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2978     return FrameIndex;
2979   } else {
2980     if (ArgSize == 0) {
2981       // We cannot allocate a zero-byte object for the first variadic argument,
2982       // so just make up a size.
2983       ArgSize = 4;
2984     }
2985     // This will point to the next argument passed via stack.
2986     return MFI->CreateFixedObject(
2987       ArgSize, ArgOffset, !ForceMutable);
2988   }
2989 }
2990
2991 // Setup stack frame, the va_list pointer will start from.
2992 void
2993 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2994                                         SDLoc dl, SDValue &Chain,
2995                                         unsigned ArgOffset,
2996                                         unsigned TotalArgRegsSaveSize,
2997                                         bool ForceMutable) const {
2998   MachineFunction &MF = DAG.getMachineFunction();
2999   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3000
3001   // Try to store any remaining integer argument regs
3002   // to their spots on the stack so that they may be loaded by deferencing
3003   // the result of va_next.
3004   // If there is no regs to be stored, just point address after last
3005   // argument passed via stack.
3006   int FrameIndex =
3007     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3008                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3009                    0, TotalArgRegsSaveSize);
3010
3011   AFI->setVarArgsFrameIndex(FrameIndex);
3012 }
3013
3014 SDValue
3015 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3016                                         CallingConv::ID CallConv, bool isVarArg,
3017                                         const SmallVectorImpl<ISD::InputArg>
3018                                           &Ins,
3019                                         SDLoc dl, SelectionDAG &DAG,
3020                                         SmallVectorImpl<SDValue> &InVals)
3021                                           const {
3022   MachineFunction &MF = DAG.getMachineFunction();
3023   MachineFrameInfo *MFI = MF.getFrameInfo();
3024
3025   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3026
3027   // Assign locations to all of the incoming arguments.
3028   SmallVector<CCValAssign, 16> ArgLocs;
3029   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3030                     *DAG.getContext(), Prologue);
3031   CCInfo.AnalyzeFormalArguments(Ins,
3032                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3033                                                   isVarArg));
3034
3035   SmallVector<SDValue, 16> ArgValues;
3036   int lastInsIndex = -1;
3037   SDValue ArgValue;
3038   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3039   unsigned CurArgIdx = 0;
3040
3041   // Initially ArgRegsSaveSize is zero.
3042   // Then we increase this value each time we meet byval parameter.
3043   // We also increase this value in case of varargs function.
3044   AFI->setArgRegsSaveSize(0);
3045
3046   unsigned ByValStoreOffset = 0;
3047   unsigned TotalArgRegsSaveSize = 0;
3048   unsigned ArgRegsSaveSizeMaxAlign = 4;
3049
3050   // Calculate the amount of stack space that we need to allocate to store
3051   // byval and variadic arguments that are passed in registers.
3052   // We need to know this before we allocate the first byval or variadic
3053   // argument, as they will be allocated a stack slot below the CFA (Canonical
3054   // Frame Address, the stack pointer at entry to the function).
3055   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3056     CCValAssign &VA = ArgLocs[i];
3057     if (VA.isMemLoc()) {
3058       int index = VA.getValNo();
3059       if (index != lastInsIndex) {
3060         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3061         if (Flags.isByVal()) {
3062           unsigned ExtraArgRegsSize;
3063           unsigned ExtraArgRegsSaveSize;
3064           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3065                          Flags.getByValSize(),
3066                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3067
3068           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3069           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3070               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3071           CCInfo.nextInRegsParam();
3072         }
3073         lastInsIndex = index;
3074       }
3075     }
3076   }
3077   CCInfo.rewindByValRegsInfo();
3078   lastInsIndex = -1;
3079   if (isVarArg && MFI->hasVAStart()) {
3080     unsigned ExtraArgRegsSize;
3081     unsigned ExtraArgRegsSaveSize;
3082     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3083                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3084     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3085   }
3086   // If the arg regs save area contains N-byte aligned values, the
3087   // bottom of it must be at least N-byte aligned.
3088   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3089   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3090
3091   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3092     CCValAssign &VA = ArgLocs[i];
3093     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3094     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3095     // Arguments stored in registers.
3096     if (VA.isRegLoc()) {
3097       EVT RegVT = VA.getLocVT();
3098
3099       if (VA.needsCustom()) {
3100         // f64 and vector types are split up into multiple registers or
3101         // combinations of registers and stack slots.
3102         if (VA.getLocVT() == MVT::v2f64) {
3103           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3104                                                    Chain, DAG, dl);
3105           VA = ArgLocs[++i]; // skip ahead to next loc
3106           SDValue ArgValue2;
3107           if (VA.isMemLoc()) {
3108             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3109             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3110             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3111                                     MachinePointerInfo::getFixedStack(FI),
3112                                     false, false, false, 0);
3113           } else {
3114             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3115                                              Chain, DAG, dl);
3116           }
3117           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3118           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3119                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3120           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3121                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3122         } else
3123           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3124
3125       } else {
3126         const TargetRegisterClass *RC;
3127
3128         if (RegVT == MVT::f32)
3129           RC = &ARM::SPRRegClass;
3130         else if (RegVT == MVT::f64)
3131           RC = &ARM::DPRRegClass;
3132         else if (RegVT == MVT::v2f64)
3133           RC = &ARM::QPRRegClass;
3134         else if (RegVT == MVT::i32)
3135           RC = AFI->isThumb1OnlyFunction() ?
3136             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3137             (const TargetRegisterClass*)&ARM::GPRRegClass;
3138         else
3139           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3140
3141         // Transform the arguments in physical registers into virtual ones.
3142         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3143         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3144       }
3145
3146       // If this is an 8 or 16-bit value, it is really passed promoted
3147       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3148       // truncate to the right size.
3149       switch (VA.getLocInfo()) {
3150       default: llvm_unreachable("Unknown loc info!");
3151       case CCValAssign::Full: break;
3152       case CCValAssign::BCvt:
3153         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3154         break;
3155       case CCValAssign::SExt:
3156         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3157                                DAG.getValueType(VA.getValVT()));
3158         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3159         break;
3160       case CCValAssign::ZExt:
3161         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3162                                DAG.getValueType(VA.getValVT()));
3163         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3164         break;
3165       }
3166
3167       InVals.push_back(ArgValue);
3168
3169     } else { // VA.isRegLoc()
3170
3171       // sanity check
3172       assert(VA.isMemLoc());
3173       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3174
3175       int index = ArgLocs[i].getValNo();
3176
3177       // Some Ins[] entries become multiple ArgLoc[] entries.
3178       // Process them only once.
3179       if (index != lastInsIndex)
3180         {
3181           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3182           // FIXME: For now, all byval parameter objects are marked mutable.
3183           // This can be changed with more analysis.
3184           // In case of tail call optimization mark all arguments mutable.
3185           // Since they could be overwritten by lowering of arguments in case of
3186           // a tail call.
3187           if (Flags.isByVal()) {
3188             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3189
3190             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3191             int FrameIndex = StoreByValRegs(
3192                 CCInfo, DAG, dl, Chain, CurOrigArg,
3193                 CurByValIndex,
3194                 Ins[VA.getValNo()].PartOffset,
3195                 VA.getLocMemOffset(),
3196                 Flags.getByValSize(),
3197                 true /*force mutable frames*/,
3198                 ByValStoreOffset,
3199                 TotalArgRegsSaveSize);
3200             ByValStoreOffset += Flags.getByValSize();
3201             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3202             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3203             CCInfo.nextInRegsParam();
3204           } else {
3205             unsigned FIOffset = VA.getLocMemOffset();
3206             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3207                                             FIOffset, true);
3208
3209             // Create load nodes to retrieve arguments from the stack.
3210             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3211             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3212                                          MachinePointerInfo::getFixedStack(FI),
3213                                          false, false, false, 0));
3214           }
3215           lastInsIndex = index;
3216         }
3217     }
3218   }
3219
3220   // varargs
3221   if (isVarArg && MFI->hasVAStart())
3222     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3223                          CCInfo.getNextStackOffset(),
3224                          TotalArgRegsSaveSize);
3225
3226   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3227
3228   return Chain;
3229 }
3230
3231 /// isFloatingPointZero - Return true if this is +0.0.
3232 static bool isFloatingPointZero(SDValue Op) {
3233   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3234     return CFP->getValueAPF().isPosZero();
3235   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3236     // Maybe this has already been legalized into the constant pool?
3237     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3238       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3239       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3240         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3241           return CFP->getValueAPF().isPosZero();
3242     }
3243   }
3244   return false;
3245 }
3246
3247 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3248 /// the given operands.
3249 SDValue
3250 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3251                              SDValue &ARMcc, SelectionDAG &DAG,
3252                              SDLoc dl) const {
3253   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3254     unsigned C = RHSC->getZExtValue();
3255     if (!isLegalICmpImmediate(C)) {
3256       // Constant does not fit, try adjusting it by one?
3257       switch (CC) {
3258       default: break;
3259       case ISD::SETLT:
3260       case ISD::SETGE:
3261         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3262           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3263           RHS = DAG.getConstant(C-1, MVT::i32);
3264         }
3265         break;
3266       case ISD::SETULT:
3267       case ISD::SETUGE:
3268         if (C != 0 && isLegalICmpImmediate(C-1)) {
3269           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3270           RHS = DAG.getConstant(C-1, MVT::i32);
3271         }
3272         break;
3273       case ISD::SETLE:
3274       case ISD::SETGT:
3275         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3276           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3277           RHS = DAG.getConstant(C+1, MVT::i32);
3278         }
3279         break;
3280       case ISD::SETULE:
3281       case ISD::SETUGT:
3282         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3283           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3284           RHS = DAG.getConstant(C+1, MVT::i32);
3285         }
3286         break;
3287       }
3288     }
3289   }
3290
3291   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3292   ARMISD::NodeType CompareType;
3293   switch (CondCode) {
3294   default:
3295     CompareType = ARMISD::CMP;
3296     break;
3297   case ARMCC::EQ:
3298   case ARMCC::NE:
3299     // Uses only Z Flag
3300     CompareType = ARMISD::CMPZ;
3301     break;
3302   }
3303   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3304   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3305 }
3306
3307 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3308 SDValue
3309 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3310                              SDLoc dl) const {
3311   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3312   SDValue Cmp;
3313   if (!isFloatingPointZero(RHS))
3314     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3315   else
3316     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3317   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3318 }
3319
3320 /// duplicateCmp - Glue values can have only one use, so this function
3321 /// duplicates a comparison node.
3322 SDValue
3323 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3324   unsigned Opc = Cmp.getOpcode();
3325   SDLoc DL(Cmp);
3326   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3327     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3328
3329   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3330   Cmp = Cmp.getOperand(0);
3331   Opc = Cmp.getOpcode();
3332   if (Opc == ARMISD::CMPFP)
3333     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3334   else {
3335     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3336     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3337   }
3338   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3339 }
3340
3341 std::pair<SDValue, SDValue>
3342 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3343                                  SDValue &ARMcc) const {
3344   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3345
3346   SDValue Value, OverflowCmp;
3347   SDValue LHS = Op.getOperand(0);
3348   SDValue RHS = Op.getOperand(1);
3349
3350
3351   // FIXME: We are currently always generating CMPs because we don't support
3352   // generating CMN through the backend. This is not as good as the natural
3353   // CMP case because it causes a register dependency and cannot be folded
3354   // later.
3355
3356   switch (Op.getOpcode()) {
3357   default:
3358     llvm_unreachable("Unknown overflow instruction!");
3359   case ISD::SADDO:
3360     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3361     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3362     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3363     break;
3364   case ISD::UADDO:
3365     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3366     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3367     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3368     break;
3369   case ISD::SSUBO:
3370     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3371     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3372     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3373     break;
3374   case ISD::USUBO:
3375     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3376     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3377     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3378     break;
3379   } // switch (...)
3380
3381   return std::make_pair(Value, OverflowCmp);
3382 }
3383
3384
3385 SDValue
3386 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3387   // Let legalize expand this if it isn't a legal type yet.
3388   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3389     return SDValue();
3390
3391   SDValue Value, OverflowCmp;
3392   SDValue ARMcc;
3393   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3394   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3395   // We use 0 and 1 as false and true values.
3396   SDValue TVal = DAG.getConstant(1, MVT::i32);
3397   SDValue FVal = DAG.getConstant(0, MVT::i32);
3398   EVT VT = Op.getValueType();
3399
3400   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3401                                  ARMcc, CCR, OverflowCmp);
3402
3403   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3404   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3405 }
3406
3407
3408 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3409   SDValue Cond = Op.getOperand(0);
3410   SDValue SelectTrue = Op.getOperand(1);
3411   SDValue SelectFalse = Op.getOperand(2);
3412   SDLoc dl(Op);
3413   unsigned Opc = Cond.getOpcode();
3414
3415   if (Cond.getResNo() == 1 &&
3416       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3417        Opc == ISD::USUBO)) {
3418     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3419       return SDValue();
3420
3421     SDValue Value, OverflowCmp;
3422     SDValue ARMcc;
3423     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3424     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3425     EVT VT = Op.getValueType();
3426
3427     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3428                    OverflowCmp, DAG);
3429   }
3430
3431   // Convert:
3432   //
3433   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3434   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3435   //
3436   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3437     const ConstantSDNode *CMOVTrue =
3438       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3439     const ConstantSDNode *CMOVFalse =
3440       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3441
3442     if (CMOVTrue && CMOVFalse) {
3443       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3444       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3445
3446       SDValue True;
3447       SDValue False;
3448       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3449         True = SelectTrue;
3450         False = SelectFalse;
3451       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3452         True = SelectFalse;
3453         False = SelectTrue;
3454       }
3455
3456       if (True.getNode() && False.getNode()) {
3457         EVT VT = Op.getValueType();
3458         SDValue ARMcc = Cond.getOperand(2);
3459         SDValue CCR = Cond.getOperand(3);
3460         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3461         assert(True.getValueType() == VT);
3462         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3463       }
3464     }
3465   }
3466
3467   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3468   // undefined bits before doing a full-word comparison with zero.
3469   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3470                      DAG.getConstant(1, Cond.getValueType()));
3471
3472   return DAG.getSelectCC(dl, Cond,
3473                          DAG.getConstant(0, Cond.getValueType()),
3474                          SelectTrue, SelectFalse, ISD::SETNE);
3475 }
3476
3477 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3478   if (CC == ISD::SETNE)
3479     return ISD::SETEQ;
3480   return ISD::getSetCCInverse(CC, true);
3481 }
3482
3483 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3484                                  bool &swpCmpOps, bool &swpVselOps) {
3485   // Start by selecting the GE condition code for opcodes that return true for
3486   // 'equality'
3487   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3488       CC == ISD::SETULE)
3489     CondCode = ARMCC::GE;
3490
3491   // and GT for opcodes that return false for 'equality'.
3492   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3493            CC == ISD::SETULT)
3494     CondCode = ARMCC::GT;
3495
3496   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3497   // to swap the compare operands.
3498   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3499       CC == ISD::SETULT)
3500     swpCmpOps = true;
3501
3502   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3503   // If we have an unordered opcode, we need to swap the operands to the VSEL
3504   // instruction (effectively negating the condition).
3505   //
3506   // This also has the effect of swapping which one of 'less' or 'greater'
3507   // returns true, so we also swap the compare operands. It also switches
3508   // whether we return true for 'equality', so we compensate by picking the
3509   // opposite condition code to our original choice.
3510   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3511       CC == ISD::SETUGT) {
3512     swpCmpOps = !swpCmpOps;
3513     swpVselOps = !swpVselOps;
3514     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3515   }
3516
3517   // 'ordered' is 'anything but unordered', so use the VS condition code and
3518   // swap the VSEL operands.
3519   if (CC == ISD::SETO) {
3520     CondCode = ARMCC::VS;
3521     swpVselOps = true;
3522   }
3523
3524   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3525   // code and swap the VSEL operands.
3526   if (CC == ISD::SETUNE) {
3527     CondCode = ARMCC::EQ;
3528     swpVselOps = true;
3529   }
3530 }
3531
3532 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3533                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3534                                    SDValue Cmp, SelectionDAG &DAG) const {
3535   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3536     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3537                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3538     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3539                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3540
3541     SDValue TrueLow = TrueVal.getValue(0);
3542     SDValue TrueHigh = TrueVal.getValue(1);
3543     SDValue FalseLow = FalseVal.getValue(0);
3544     SDValue FalseHigh = FalseVal.getValue(1);
3545
3546     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3547                               ARMcc, CCR, Cmp);
3548     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3549                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3550
3551     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3552   } else {
3553     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3554                        Cmp);
3555   }
3556 }
3557
3558 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3559   EVT VT = Op.getValueType();
3560   SDValue LHS = Op.getOperand(0);
3561   SDValue RHS = Op.getOperand(1);
3562   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3563   SDValue TrueVal = Op.getOperand(2);
3564   SDValue FalseVal = Op.getOperand(3);
3565   SDLoc dl(Op);
3566
3567   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3568     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3569                                                     dl);
3570
3571     // If softenSetCCOperands only returned one value, we should compare it to
3572     // zero.
3573     if (!RHS.getNode()) {
3574       RHS = DAG.getConstant(0, LHS.getValueType());
3575       CC = ISD::SETNE;
3576     }
3577   }
3578
3579   if (LHS.getValueType() == MVT::i32) {
3580     // Try to generate VSEL on ARMv8.
3581     // The VSEL instruction can't use all the usual ARM condition
3582     // codes: it only has two bits to select the condition code, so it's
3583     // constrained to use only GE, GT, VS and EQ.
3584     //
3585     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3586     // swap the operands of the previous compare instruction (effectively
3587     // inverting the compare condition, swapping 'less' and 'greater') and
3588     // sometimes need to swap the operands to the VSEL (which inverts the
3589     // condition in the sense of firing whenever the previous condition didn't)
3590     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3591                                       TrueVal.getValueType() == MVT::f64)) {
3592       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3593       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3594           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3595         CC = getInverseCCForVSEL(CC);
3596         std::swap(TrueVal, FalseVal);
3597       }
3598     }
3599
3600     SDValue ARMcc;
3601     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3602     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3603     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3604   }
3605
3606   ARMCC::CondCodes CondCode, CondCode2;
3607   FPCCToARMCC(CC, CondCode, CondCode2);
3608
3609   // Try to generate VSEL on ARMv8.
3610   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3611                                     TrueVal.getValueType() == MVT::f64)) {
3612     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3613     // same operands, as follows:
3614     //   c = fcmp [ogt, olt, ugt, ult] a, b
3615     //   select c, a, b
3616     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3617     // handled differently than the original code sequence.
3618     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3619         RHS == FalseVal) {
3620       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3621         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3622       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3623         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3624     }
3625
3626     bool swpCmpOps = false;
3627     bool swpVselOps = false;
3628     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3629
3630     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3631         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3632       if (swpCmpOps)
3633         std::swap(LHS, RHS);
3634       if (swpVselOps)
3635         std::swap(TrueVal, FalseVal);
3636     }
3637   }
3638
3639   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3640   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3641   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3642   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3643   if (CondCode2 != ARMCC::AL) {
3644     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3645     // FIXME: Needs another CMP because flag can have but one use.
3646     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3647     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3648   }
3649   return Result;
3650 }
3651
3652 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3653 /// to morph to an integer compare sequence.
3654 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3655                            const ARMSubtarget *Subtarget) {
3656   SDNode *N = Op.getNode();
3657   if (!N->hasOneUse())
3658     // Otherwise it requires moving the value from fp to integer registers.
3659     return false;
3660   if (!N->getNumValues())
3661     return false;
3662   EVT VT = Op.getValueType();
3663   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3664     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3665     // vmrs are very slow, e.g. cortex-a8.
3666     return false;
3667
3668   if (isFloatingPointZero(Op)) {
3669     SeenZero = true;
3670     return true;
3671   }
3672   return ISD::isNormalLoad(N);
3673 }
3674
3675 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3676   if (isFloatingPointZero(Op))
3677     return DAG.getConstant(0, MVT::i32);
3678
3679   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3680     return DAG.getLoad(MVT::i32, SDLoc(Op),
3681                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3682                        Ld->isVolatile(), Ld->isNonTemporal(),
3683                        Ld->isInvariant(), Ld->getAlignment());
3684
3685   llvm_unreachable("Unknown VFP cmp argument!");
3686 }
3687
3688 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3689                            SDValue &RetVal1, SDValue &RetVal2) {
3690   if (isFloatingPointZero(Op)) {
3691     RetVal1 = DAG.getConstant(0, MVT::i32);
3692     RetVal2 = DAG.getConstant(0, MVT::i32);
3693     return;
3694   }
3695
3696   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3697     SDValue Ptr = Ld->getBasePtr();
3698     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3699                           Ld->getChain(), Ptr,
3700                           Ld->getPointerInfo(),
3701                           Ld->isVolatile(), Ld->isNonTemporal(),
3702                           Ld->isInvariant(), Ld->getAlignment());
3703
3704     EVT PtrType = Ptr.getValueType();
3705     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3706     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3707                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3708     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3709                           Ld->getChain(), NewPtr,
3710                           Ld->getPointerInfo().getWithOffset(4),
3711                           Ld->isVolatile(), Ld->isNonTemporal(),
3712                           Ld->isInvariant(), NewAlign);
3713     return;
3714   }
3715
3716   llvm_unreachable("Unknown VFP cmp argument!");
3717 }
3718
3719 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3720 /// f32 and even f64 comparisons to integer ones.
3721 SDValue
3722 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3723   SDValue Chain = Op.getOperand(0);
3724   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3725   SDValue LHS = Op.getOperand(2);
3726   SDValue RHS = Op.getOperand(3);
3727   SDValue Dest = Op.getOperand(4);
3728   SDLoc dl(Op);
3729
3730   bool LHSSeenZero = false;
3731   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3732   bool RHSSeenZero = false;
3733   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3734   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3735     // If unsafe fp math optimization is enabled and there are no other uses of
3736     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3737     // to an integer comparison.
3738     if (CC == ISD::SETOEQ)
3739       CC = ISD::SETEQ;
3740     else if (CC == ISD::SETUNE)
3741       CC = ISD::SETNE;
3742
3743     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3744     SDValue ARMcc;
3745     if (LHS.getValueType() == MVT::f32) {
3746       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3747                         bitcastf32Toi32(LHS, DAG), Mask);
3748       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3749                         bitcastf32Toi32(RHS, DAG), Mask);
3750       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3751       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3752       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3753                          Chain, Dest, ARMcc, CCR, Cmp);
3754     }
3755
3756     SDValue LHS1, LHS2;
3757     SDValue RHS1, RHS2;
3758     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3759     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3760     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3761     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3762     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3763     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3764     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3765     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3766     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3767   }
3768
3769   return SDValue();
3770 }
3771
3772 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3773   SDValue Chain = Op.getOperand(0);
3774   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3775   SDValue LHS = Op.getOperand(2);
3776   SDValue RHS = Op.getOperand(3);
3777   SDValue Dest = Op.getOperand(4);
3778   SDLoc dl(Op);
3779
3780   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3781     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3782                                                     dl);
3783
3784     // If softenSetCCOperands only returned one value, we should compare it to
3785     // zero.
3786     if (!RHS.getNode()) {
3787       RHS = DAG.getConstant(0, LHS.getValueType());
3788       CC = ISD::SETNE;
3789     }
3790   }
3791
3792   if (LHS.getValueType() == MVT::i32) {
3793     SDValue ARMcc;
3794     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3795     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3796     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3797                        Chain, Dest, ARMcc, CCR, Cmp);
3798   }
3799
3800   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3801
3802   if (getTargetMachine().Options.UnsafeFPMath &&
3803       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3804        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3805     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3806     if (Result.getNode())
3807       return Result;
3808   }
3809
3810   ARMCC::CondCodes CondCode, CondCode2;
3811   FPCCToARMCC(CC, CondCode, CondCode2);
3812
3813   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3814   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3815   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3816   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3817   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3818   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3819   if (CondCode2 != ARMCC::AL) {
3820     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3821     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3822     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3823   }
3824   return Res;
3825 }
3826
3827 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3828   SDValue Chain = Op.getOperand(0);
3829   SDValue Table = Op.getOperand(1);
3830   SDValue Index = Op.getOperand(2);
3831   SDLoc dl(Op);
3832
3833   EVT PTy = getPointerTy();
3834   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3835   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3836   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3837   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3838   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3839   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3840   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3841   if (Subtarget->isThumb2()) {
3842     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3843     // which does another jump to the destination. This also makes it easier
3844     // to translate it to TBB / TBH later.
3845     // FIXME: This might not work if the function is extremely large.
3846     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3847                        Addr, Op.getOperand(2), JTI, UId);
3848   }
3849   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3850     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3851                        MachinePointerInfo::getJumpTable(),
3852                        false, false, false, 0);
3853     Chain = Addr.getValue(1);
3854     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3855     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3856   } else {
3857     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3858                        MachinePointerInfo::getJumpTable(),
3859                        false, false, false, 0);
3860     Chain = Addr.getValue(1);
3861     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3862   }
3863 }
3864
3865 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3866   EVT VT = Op.getValueType();
3867   SDLoc dl(Op);
3868
3869   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3870     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3871       return Op;
3872     return DAG.UnrollVectorOp(Op.getNode());
3873   }
3874
3875   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3876          "Invalid type for custom lowering!");
3877   if (VT != MVT::v4i16)
3878     return DAG.UnrollVectorOp(Op.getNode());
3879
3880   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3881   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3882 }
3883
3884 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3885   EVT VT = Op.getValueType();
3886   if (VT.isVector())
3887     return LowerVectorFP_TO_INT(Op, DAG);
3888
3889   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3890     RTLIB::Libcall LC;
3891     if (Op.getOpcode() == ISD::FP_TO_SINT)
3892       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3893                               Op.getValueType());
3894     else
3895       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3896                               Op.getValueType());
3897     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3898                        /*isSigned*/ false, SDLoc(Op)).first;
3899   }
3900
3901   SDLoc dl(Op);
3902   unsigned Opc;
3903
3904   switch (Op.getOpcode()) {
3905   default: llvm_unreachable("Invalid opcode!");
3906   case ISD::FP_TO_SINT:
3907     Opc = ARMISD::FTOSI;
3908     break;
3909   case ISD::FP_TO_UINT:
3910     Opc = ARMISD::FTOUI;
3911     break;
3912   }
3913   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3914   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3915 }
3916
3917 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3918   EVT VT = Op.getValueType();
3919   SDLoc dl(Op);
3920
3921   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3922     if (VT.getVectorElementType() == MVT::f32)
3923       return Op;
3924     return DAG.UnrollVectorOp(Op.getNode());
3925   }
3926
3927   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3928          "Invalid type for custom lowering!");
3929   if (VT != MVT::v4f32)
3930     return DAG.UnrollVectorOp(Op.getNode());
3931
3932   unsigned CastOpc;
3933   unsigned Opc;
3934   switch (Op.getOpcode()) {
3935   default: llvm_unreachable("Invalid opcode!");
3936   case ISD::SINT_TO_FP:
3937     CastOpc = ISD::SIGN_EXTEND;
3938     Opc = ISD::SINT_TO_FP;
3939     break;
3940   case ISD::UINT_TO_FP:
3941     CastOpc = ISD::ZERO_EXTEND;
3942     Opc = ISD::UINT_TO_FP;
3943     break;
3944   }
3945
3946   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3947   return DAG.getNode(Opc, dl, VT, Op);
3948 }
3949
3950 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3951   EVT VT = Op.getValueType();
3952   if (VT.isVector())
3953     return LowerVectorINT_TO_FP(Op, DAG);
3954
3955   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3956     RTLIB::Libcall LC;
3957     if (Op.getOpcode() == ISD::SINT_TO_FP)
3958       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3959                               Op.getValueType());
3960     else
3961       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3962                               Op.getValueType());
3963     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3964                        /*isSigned*/ false, SDLoc(Op)).first;
3965   }
3966
3967   SDLoc dl(Op);
3968   unsigned Opc;
3969
3970   switch (Op.getOpcode()) {
3971   default: llvm_unreachable("Invalid opcode!");
3972   case ISD::SINT_TO_FP:
3973     Opc = ARMISD::SITOF;
3974     break;
3975   case ISD::UINT_TO_FP:
3976     Opc = ARMISD::UITOF;
3977     break;
3978   }
3979
3980   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3981   return DAG.getNode(Opc, dl, VT, Op);
3982 }
3983
3984 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3985   // Implement fcopysign with a fabs and a conditional fneg.
3986   SDValue Tmp0 = Op.getOperand(0);
3987   SDValue Tmp1 = Op.getOperand(1);
3988   SDLoc dl(Op);
3989   EVT VT = Op.getValueType();
3990   EVT SrcVT = Tmp1.getValueType();
3991   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3992     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3993   bool UseNEON = !InGPR && Subtarget->hasNEON();
3994
3995   if (UseNEON) {
3996     // Use VBSL to copy the sign bit.
3997     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3998     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3999                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4000     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4001     if (VT == MVT::f64)
4002       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4003                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4004                          DAG.getConstant(32, MVT::i32));
4005     else /*if (VT == MVT::f32)*/
4006       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4007     if (SrcVT == MVT::f32) {
4008       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4009       if (VT == MVT::f64)
4010         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4011                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4012                            DAG.getConstant(32, MVT::i32));
4013     } else if (VT == MVT::f32)
4014       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4015                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4016                          DAG.getConstant(32, MVT::i32));
4017     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4018     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4019
4020     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4021                                             MVT::i32);
4022     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4023     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4024                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4025
4026     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4027                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4028                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4029     if (VT == MVT::f32) {
4030       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4031       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4032                         DAG.getConstant(0, MVT::i32));
4033     } else {
4034       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4035     }
4036
4037     return Res;
4038   }
4039
4040   // Bitcast operand 1 to i32.
4041   if (SrcVT == MVT::f64)
4042     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4043                        Tmp1).getValue(1);
4044   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4045
4046   // Or in the signbit with integer operations.
4047   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4048   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4049   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4050   if (VT == MVT::f32) {
4051     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4052                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4053     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4054                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4055   }
4056
4057   // f64: Or the high part with signbit and then combine two parts.
4058   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4059                      Tmp0);
4060   SDValue Lo = Tmp0.getValue(0);
4061   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4062   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4063   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4064 }
4065
4066 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4067   MachineFunction &MF = DAG.getMachineFunction();
4068   MachineFrameInfo *MFI = MF.getFrameInfo();
4069   MFI->setReturnAddressIsTaken(true);
4070
4071   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4072     return SDValue();
4073
4074   EVT VT = Op.getValueType();
4075   SDLoc dl(Op);
4076   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4077   if (Depth) {
4078     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4079     SDValue Offset = DAG.getConstant(4, MVT::i32);
4080     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4081                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4082                        MachinePointerInfo(), false, false, false, 0);
4083   }
4084
4085   // Return LR, which contains the return address. Mark it an implicit live-in.
4086   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4087   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4088 }
4089
4090 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4091   const ARMBaseRegisterInfo &ARI =
4092     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4093   MachineFunction &MF = DAG.getMachineFunction();
4094   MachineFrameInfo *MFI = MF.getFrameInfo();
4095   MFI->setFrameAddressIsTaken(true);
4096
4097   EVT VT = Op.getValueType();
4098   SDLoc dl(Op);  // FIXME probably not meaningful
4099   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4100   unsigned FrameReg = ARI.getFrameRegister(MF);
4101   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4102   while (Depth--)
4103     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4104                             MachinePointerInfo(),
4105                             false, false, false, 0);
4106   return FrameAddr;
4107 }
4108
4109 // FIXME? Maybe this could be a TableGen attribute on some registers and
4110 // this table could be generated automatically from RegInfo.
4111 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4112                                               EVT VT) const {
4113   unsigned Reg = StringSwitch<unsigned>(RegName)
4114                        .Case("sp", ARM::SP)
4115                        .Default(0);
4116   if (Reg)
4117     return Reg;
4118   report_fatal_error("Invalid register name global variable");
4119 }
4120
4121 /// ExpandBITCAST - If the target supports VFP, this function is called to
4122 /// expand a bit convert where either the source or destination type is i64 to
4123 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4124 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4125 /// vectors), since the legalizer won't know what to do with that.
4126 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4128   SDLoc dl(N);
4129   SDValue Op = N->getOperand(0);
4130
4131   // This function is only supposed to be called for i64 types, either as the
4132   // source or destination of the bit convert.
4133   EVT SrcVT = Op.getValueType();
4134   EVT DstVT = N->getValueType(0);
4135   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4136          "ExpandBITCAST called for non-i64 type");
4137
4138   // Turn i64->f64 into VMOVDRR.
4139   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4140     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4141                              DAG.getConstant(0, MVT::i32));
4142     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4143                              DAG.getConstant(1, MVT::i32));
4144     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4145                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4146   }
4147
4148   // Turn f64->i64 into VMOVRRD.
4149   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4150     SDValue Cvt;
4151     if (TLI.isBigEndian() && SrcVT.isVector() &&
4152         SrcVT.getVectorNumElements() > 1)
4153       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4154                         DAG.getVTList(MVT::i32, MVT::i32),
4155                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4156     else
4157       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4158                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4159     // Merge the pieces into a single i64 value.
4160     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4161   }
4162
4163   return SDValue();
4164 }
4165
4166 /// getZeroVector - Returns a vector of specified type with all zero elements.
4167 /// Zero vectors are used to represent vector negation and in those cases
4168 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4169 /// not support i64 elements, so sometimes the zero vectors will need to be
4170 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4171 /// zero vector.
4172 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4173   assert(VT.isVector() && "Expected a vector type");
4174   // The canonical modified immediate encoding of a zero vector is....0!
4175   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4176   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4177   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4178   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4179 }
4180
4181 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4182 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4183 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4184                                                 SelectionDAG &DAG) const {
4185   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4186   EVT VT = Op.getValueType();
4187   unsigned VTBits = VT.getSizeInBits();
4188   SDLoc dl(Op);
4189   SDValue ShOpLo = Op.getOperand(0);
4190   SDValue ShOpHi = Op.getOperand(1);
4191   SDValue ShAmt  = Op.getOperand(2);
4192   SDValue ARMcc;
4193   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4194
4195   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4196
4197   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4198                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4199   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4200   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4201                                    DAG.getConstant(VTBits, MVT::i32));
4202   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4203   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4204   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4205
4206   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4207   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4208                           ARMcc, DAG, dl);
4209   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4210   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4211                            CCR, Cmp);
4212
4213   SDValue Ops[2] = { Lo, Hi };
4214   return DAG.getMergeValues(Ops, dl);
4215 }
4216
4217 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4218 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4219 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4220                                                SelectionDAG &DAG) const {
4221   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4222   EVT VT = Op.getValueType();
4223   unsigned VTBits = VT.getSizeInBits();
4224   SDLoc dl(Op);
4225   SDValue ShOpLo = Op.getOperand(0);
4226   SDValue ShOpHi = Op.getOperand(1);
4227   SDValue ShAmt  = Op.getOperand(2);
4228   SDValue ARMcc;
4229
4230   assert(Op.getOpcode() == ISD::SHL_PARTS);
4231   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4232                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4233   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4234   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4235                                    DAG.getConstant(VTBits, MVT::i32));
4236   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4237   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4238
4239   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4240   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4241   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4242                           ARMcc, DAG, dl);
4243   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4244   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4245                            CCR, Cmp);
4246
4247   SDValue Ops[2] = { Lo, Hi };
4248   return DAG.getMergeValues(Ops, dl);
4249 }
4250
4251 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4252                                             SelectionDAG &DAG) const {
4253   // The rounding mode is in bits 23:22 of the FPSCR.
4254   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4255   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4256   // so that the shift + and get folded into a bitfield extract.
4257   SDLoc dl(Op);
4258   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4259                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4260                                               MVT::i32));
4261   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4262                                   DAG.getConstant(1U << 22, MVT::i32));
4263   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4264                               DAG.getConstant(22, MVT::i32));
4265   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4266                      DAG.getConstant(3, MVT::i32));
4267 }
4268
4269 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4270                          const ARMSubtarget *ST) {
4271   EVT VT = N->getValueType(0);
4272   SDLoc dl(N);
4273
4274   if (!ST->hasV6T2Ops())
4275     return SDValue();
4276
4277   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4278   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4279 }
4280
4281 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4282 /// for each 16-bit element from operand, repeated.  The basic idea is to
4283 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4284 ///
4285 /// Trace for v4i16:
4286 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4287 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4288 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4289 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4290 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4291 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4292 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4293 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4294 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4295   EVT VT = N->getValueType(0);
4296   SDLoc DL(N);
4297
4298   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4299   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4300   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4301   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4302   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4303   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4304 }
4305
4306 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4307 /// bit-count for each 16-bit element from the operand.  We need slightly
4308 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4309 /// 64/128-bit registers.
4310 ///
4311 /// Trace for v4i16:
4312 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4313 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4314 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4315 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4316 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4317   EVT VT = N->getValueType(0);
4318   SDLoc DL(N);
4319
4320   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4321   if (VT.is64BitVector()) {
4322     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4323     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4324                        DAG.getIntPtrConstant(0));
4325   } else {
4326     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4327                                     BitCounts, DAG.getIntPtrConstant(0));
4328     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4329   }
4330 }
4331
4332 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4333 /// bit-count for each 32-bit element from the operand.  The idea here is
4334 /// to split the vector into 16-bit elements, leverage the 16-bit count
4335 /// routine, and then combine the results.
4336 ///
4337 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4338 /// input    = [v0    v1    ] (vi: 32-bit elements)
4339 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4340 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4341 /// vrev: N0 = [k1 k0 k3 k2 ]
4342 ///            [k0 k1 k2 k3 ]
4343 ///       N1 =+[k1 k0 k3 k2 ]
4344 ///            [k0 k2 k1 k3 ]
4345 ///       N2 =+[k1 k3 k0 k2 ]
4346 ///            [k0    k2    k1    k3    ]
4347 /// Extended =+[k1    k3    k0    k2    ]
4348 ///            [k0    k2    ]
4349 /// Extracted=+[k1    k3    ]
4350 ///
4351 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4352   EVT VT = N->getValueType(0);
4353   SDLoc DL(N);
4354
4355   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4356
4357   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4358   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4359   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4360   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4361   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4362
4363   if (VT.is64BitVector()) {
4364     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4365     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4366                        DAG.getIntPtrConstant(0));
4367   } else {
4368     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4369                                     DAG.getIntPtrConstant(0));
4370     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4371   }
4372 }
4373
4374 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4375                           const ARMSubtarget *ST) {
4376   EVT VT = N->getValueType(0);
4377
4378   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4379   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4380           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4381          "Unexpected type for custom ctpop lowering");
4382
4383   if (VT.getVectorElementType() == MVT::i32)
4384     return lowerCTPOP32BitElements(N, DAG);
4385   else
4386     return lowerCTPOP16BitElements(N, DAG);
4387 }
4388
4389 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4390                           const ARMSubtarget *ST) {
4391   EVT VT = N->getValueType(0);
4392   SDLoc dl(N);
4393
4394   if (!VT.isVector())
4395     return SDValue();
4396
4397   // Lower vector shifts on NEON to use VSHL.
4398   assert(ST->hasNEON() && "unexpected vector shift");
4399
4400   // Left shifts translate directly to the vshiftu intrinsic.
4401   if (N->getOpcode() == ISD::SHL)
4402     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4403                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4404                        N->getOperand(0), N->getOperand(1));
4405
4406   assert((N->getOpcode() == ISD::SRA ||
4407           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4408
4409   // NEON uses the same intrinsics for both left and right shifts.  For
4410   // right shifts, the shift amounts are negative, so negate the vector of
4411   // shift amounts.
4412   EVT ShiftVT = N->getOperand(1).getValueType();
4413   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4414                                      getZeroVector(ShiftVT, DAG, dl),
4415                                      N->getOperand(1));
4416   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4417                              Intrinsic::arm_neon_vshifts :
4418                              Intrinsic::arm_neon_vshiftu);
4419   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4420                      DAG.getConstant(vshiftInt, MVT::i32),
4421                      N->getOperand(0), NegatedCount);
4422 }
4423
4424 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4425                                 const ARMSubtarget *ST) {
4426   EVT VT = N->getValueType(0);
4427   SDLoc dl(N);
4428
4429   // We can get here for a node like i32 = ISD::SHL i32, i64
4430   if (VT != MVT::i64)
4431     return SDValue();
4432
4433   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4434          "Unknown shift to lower!");
4435
4436   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4437   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4438       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4439     return SDValue();
4440
4441   // If we are in thumb mode, we don't have RRX.
4442   if (ST->isThumb1Only()) return SDValue();
4443
4444   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4445   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4446                            DAG.getConstant(0, MVT::i32));
4447   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4448                            DAG.getConstant(1, MVT::i32));
4449
4450   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4451   // captures the result into a carry flag.
4452   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4453   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4454
4455   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4456   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4457
4458   // Merge the pieces into a single i64 value.
4459  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4460 }
4461
4462 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4463   SDValue TmpOp0, TmpOp1;
4464   bool Invert = false;
4465   bool Swap = false;
4466   unsigned Opc = 0;
4467
4468   SDValue Op0 = Op.getOperand(0);
4469   SDValue Op1 = Op.getOperand(1);
4470   SDValue CC = Op.getOperand(2);
4471   EVT VT = Op.getValueType();
4472   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4473   SDLoc dl(Op);
4474
4475   if (Op1.getValueType().isFloatingPoint()) {
4476     switch (SetCCOpcode) {
4477     default: llvm_unreachable("Illegal FP comparison");
4478     case ISD::SETUNE:
4479     case ISD::SETNE:  Invert = true; // Fallthrough
4480     case ISD::SETOEQ:
4481     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4482     case ISD::SETOLT:
4483     case ISD::SETLT: Swap = true; // Fallthrough
4484     case ISD::SETOGT:
4485     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4486     case ISD::SETOLE:
4487     case ISD::SETLE:  Swap = true; // Fallthrough
4488     case ISD::SETOGE:
4489     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4490     case ISD::SETUGE: Swap = true; // Fallthrough
4491     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4492     case ISD::SETUGT: Swap = true; // Fallthrough
4493     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4494     case ISD::SETUEQ: Invert = true; // Fallthrough
4495     case ISD::SETONE:
4496       // Expand this to (OLT | OGT).
4497       TmpOp0 = Op0;
4498       TmpOp1 = Op1;
4499       Opc = ISD::OR;
4500       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4501       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4502       break;
4503     case ISD::SETUO: Invert = true; // Fallthrough
4504     case ISD::SETO:
4505       // Expand this to (OLT | OGE).
4506       TmpOp0 = Op0;
4507       TmpOp1 = Op1;
4508       Opc = ISD::OR;
4509       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4510       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4511       break;
4512     }
4513   } else {
4514     // Integer comparisons.
4515     switch (SetCCOpcode) {
4516     default: llvm_unreachable("Illegal integer comparison");
4517     case ISD::SETNE:  Invert = true;
4518     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4519     case ISD::SETLT:  Swap = true;
4520     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4521     case ISD::SETLE:  Swap = true;
4522     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4523     case ISD::SETULT: Swap = true;
4524     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4525     case ISD::SETULE: Swap = true;
4526     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4527     }
4528
4529     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4530     if (Opc == ARMISD::VCEQ) {
4531
4532       SDValue AndOp;
4533       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4534         AndOp = Op0;
4535       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4536         AndOp = Op1;
4537
4538       // Ignore bitconvert.
4539       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4540         AndOp = AndOp.getOperand(0);
4541
4542       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4543         Opc = ARMISD::VTST;
4544         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4545         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4546         Invert = !Invert;
4547       }
4548     }
4549   }
4550
4551   if (Swap)
4552     std::swap(Op0, Op1);
4553
4554   // If one of the operands is a constant vector zero, attempt to fold the
4555   // comparison to a specialized compare-against-zero form.
4556   SDValue SingleOp;
4557   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4558     SingleOp = Op0;
4559   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4560     if (Opc == ARMISD::VCGE)
4561       Opc = ARMISD::VCLEZ;
4562     else if (Opc == ARMISD::VCGT)
4563       Opc = ARMISD::VCLTZ;
4564     SingleOp = Op1;
4565   }
4566
4567   SDValue Result;
4568   if (SingleOp.getNode()) {
4569     switch (Opc) {
4570     case ARMISD::VCEQ:
4571       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4572     case ARMISD::VCGE:
4573       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4574     case ARMISD::VCLEZ:
4575       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4576     case ARMISD::VCGT:
4577       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4578     case ARMISD::VCLTZ:
4579       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4580     default:
4581       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4582     }
4583   } else {
4584      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4585   }
4586
4587   if (Invert)
4588     Result = DAG.getNOT(dl, Result, VT);
4589
4590   return Result;
4591 }
4592
4593 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4594 /// valid vector constant for a NEON instruction with a "modified immediate"
4595 /// operand (e.g., VMOV).  If so, return the encoded value.
4596 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4597                                  unsigned SplatBitSize, SelectionDAG &DAG,
4598                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4599   unsigned OpCmode, Imm;
4600
4601   // SplatBitSize is set to the smallest size that splats the vector, so a
4602   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4603   // immediate instructions others than VMOV do not support the 8-bit encoding
4604   // of a zero vector, and the default encoding of zero is supposed to be the
4605   // 32-bit version.
4606   if (SplatBits == 0)
4607     SplatBitSize = 32;
4608
4609   switch (SplatBitSize) {
4610   case 8:
4611     if (type != VMOVModImm)
4612       return SDValue();
4613     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4614     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4615     OpCmode = 0xe;
4616     Imm = SplatBits;
4617     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4618     break;
4619
4620   case 16:
4621     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4622     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4623     if ((SplatBits & ~0xff) == 0) {
4624       // Value = 0x00nn: Op=x, Cmode=100x.
4625       OpCmode = 0x8;
4626       Imm = SplatBits;
4627       break;
4628     }
4629     if ((SplatBits & ~0xff00) == 0) {
4630       // Value = 0xnn00: Op=x, Cmode=101x.
4631       OpCmode = 0xa;
4632       Imm = SplatBits >> 8;
4633       break;
4634     }
4635     return SDValue();
4636
4637   case 32:
4638     // NEON's 32-bit VMOV supports splat values where:
4639     // * only one byte is nonzero, or
4640     // * the least significant byte is 0xff and the second byte is nonzero, or
4641     // * the least significant 2 bytes are 0xff and the third is nonzero.
4642     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4643     if ((SplatBits & ~0xff) == 0) {
4644       // Value = 0x000000nn: Op=x, Cmode=000x.
4645       OpCmode = 0;
4646       Imm = SplatBits;
4647       break;
4648     }
4649     if ((SplatBits & ~0xff00) == 0) {
4650       // Value = 0x0000nn00: Op=x, Cmode=001x.
4651       OpCmode = 0x2;
4652       Imm = SplatBits >> 8;
4653       break;
4654     }
4655     if ((SplatBits & ~0xff0000) == 0) {
4656       // Value = 0x00nn0000: Op=x, Cmode=010x.
4657       OpCmode = 0x4;
4658       Imm = SplatBits >> 16;
4659       break;
4660     }
4661     if ((SplatBits & ~0xff000000) == 0) {
4662       // Value = 0xnn000000: Op=x, Cmode=011x.
4663       OpCmode = 0x6;
4664       Imm = SplatBits >> 24;
4665       break;
4666     }
4667
4668     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4669     if (type == OtherModImm) return SDValue();
4670
4671     if ((SplatBits & ~0xffff) == 0 &&
4672         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4673       // Value = 0x0000nnff: Op=x, Cmode=1100.
4674       OpCmode = 0xc;
4675       Imm = SplatBits >> 8;
4676       break;
4677     }
4678
4679     if ((SplatBits & ~0xffffff) == 0 &&
4680         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4681       // Value = 0x00nnffff: Op=x, Cmode=1101.
4682       OpCmode = 0xd;
4683       Imm = SplatBits >> 16;
4684       break;
4685     }
4686
4687     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4688     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4689     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4690     // and fall through here to test for a valid 64-bit splat.  But, then the
4691     // caller would also need to check and handle the change in size.
4692     return SDValue();
4693
4694   case 64: {
4695     if (type != VMOVModImm)
4696       return SDValue();
4697     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4698     uint64_t BitMask = 0xff;
4699     uint64_t Val = 0;
4700     unsigned ImmMask = 1;
4701     Imm = 0;
4702     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4703       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4704         Val |= BitMask;
4705         Imm |= ImmMask;
4706       } else if ((SplatBits & BitMask) != 0) {
4707         return SDValue();
4708       }
4709       BitMask <<= 8;
4710       ImmMask <<= 1;
4711     }
4712
4713     if (DAG.getTargetLoweringInfo().isBigEndian())
4714       // swap higher and lower 32 bit word
4715       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4716
4717     // Op=1, Cmode=1110.
4718     OpCmode = 0x1e;
4719     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4720     break;
4721   }
4722
4723   default:
4724     llvm_unreachable("unexpected size for isNEONModifiedImm");
4725   }
4726
4727   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4728   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4729 }
4730
4731 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4732                                            const ARMSubtarget *ST) const {
4733   if (!ST->hasVFP3())
4734     return SDValue();
4735
4736   bool IsDouble = Op.getValueType() == MVT::f64;
4737   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4738
4739   // Use the default (constant pool) lowering for double constants when we have
4740   // an SP-only FPU
4741   if (IsDouble && Subtarget->isFPOnlySP())
4742     return SDValue();
4743
4744   // Try splatting with a VMOV.f32...
4745   APFloat FPVal = CFP->getValueAPF();
4746   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4747
4748   if (ImmVal != -1) {
4749     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4750       // We have code in place to select a valid ConstantFP already, no need to
4751       // do any mangling.
4752       return Op;
4753     }
4754
4755     // It's a float and we are trying to use NEON operations where
4756     // possible. Lower it to a splat followed by an extract.
4757     SDLoc DL(Op);
4758     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4759     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4760                                       NewVal);
4761     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4762                        DAG.getConstant(0, MVT::i32));
4763   }
4764
4765   // The rest of our options are NEON only, make sure that's allowed before
4766   // proceeding..
4767   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4768     return SDValue();
4769
4770   EVT VMovVT;
4771   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4772
4773   // It wouldn't really be worth bothering for doubles except for one very
4774   // important value, which does happen to match: 0.0. So make sure we don't do
4775   // anything stupid.
4776   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4777     return SDValue();
4778
4779   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4780   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4781                                      false, VMOVModImm);
4782   if (NewVal != SDValue()) {
4783     SDLoc DL(Op);
4784     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4785                                       NewVal);
4786     if (IsDouble)
4787       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4788
4789     // It's a float: cast and extract a vector element.
4790     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4791                                        VecConstant);
4792     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4793                        DAG.getConstant(0, MVT::i32));
4794   }
4795
4796   // Finally, try a VMVN.i32
4797   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4798                              false, VMVNModImm);
4799   if (NewVal != SDValue()) {
4800     SDLoc DL(Op);
4801     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4802
4803     if (IsDouble)
4804       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4805
4806     // It's a float: cast and extract a vector element.
4807     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4808                                        VecConstant);
4809     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4810                        DAG.getConstant(0, MVT::i32));
4811   }
4812
4813   return SDValue();
4814 }
4815
4816 // check if an VEXT instruction can handle the shuffle mask when the
4817 // vector sources of the shuffle are the same.
4818 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4819   unsigned NumElts = VT.getVectorNumElements();
4820
4821   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4822   if (M[0] < 0)
4823     return false;
4824
4825   Imm = M[0];
4826
4827   // If this is a VEXT shuffle, the immediate value is the index of the first
4828   // element.  The other shuffle indices must be the successive elements after
4829   // the first one.
4830   unsigned ExpectedElt = Imm;
4831   for (unsigned i = 1; i < NumElts; ++i) {
4832     // Increment the expected index.  If it wraps around, just follow it
4833     // back to index zero and keep going.
4834     ++ExpectedElt;
4835     if (ExpectedElt == NumElts)
4836       ExpectedElt = 0;
4837
4838     if (M[i] < 0) continue; // ignore UNDEF indices
4839     if (ExpectedElt != static_cast<unsigned>(M[i]))
4840       return false;
4841   }
4842
4843   return true;
4844 }
4845
4846
4847 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4848                        bool &ReverseVEXT, unsigned &Imm) {
4849   unsigned NumElts = VT.getVectorNumElements();
4850   ReverseVEXT = false;
4851
4852   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4853   if (M[0] < 0)
4854     return false;
4855
4856   Imm = M[0];
4857
4858   // If this is a VEXT shuffle, the immediate value is the index of the first
4859   // element.  The other shuffle indices must be the successive elements after
4860   // the first one.
4861   unsigned ExpectedElt = Imm;
4862   for (unsigned i = 1; i < NumElts; ++i) {
4863     // Increment the expected index.  If it wraps around, it may still be
4864     // a VEXT but the source vectors must be swapped.
4865     ExpectedElt += 1;
4866     if (ExpectedElt == NumElts * 2) {
4867       ExpectedElt = 0;
4868       ReverseVEXT = true;
4869     }
4870
4871     if (M[i] < 0) continue; // ignore UNDEF indices
4872     if (ExpectedElt != static_cast<unsigned>(M[i]))
4873       return false;
4874   }
4875
4876   // Adjust the index value if the source operands will be swapped.
4877   if (ReverseVEXT)
4878     Imm -= NumElts;
4879
4880   return true;
4881 }
4882
4883 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4884 /// instruction with the specified blocksize.  (The order of the elements
4885 /// within each block of the vector is reversed.)
4886 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4887   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4888          "Only possible block sizes for VREV are: 16, 32, 64");
4889
4890   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4891   if (EltSz == 64)
4892     return false;
4893
4894   unsigned NumElts = VT.getVectorNumElements();
4895   unsigned BlockElts = M[0] + 1;
4896   // If the first shuffle index is UNDEF, be optimistic.
4897   if (M[0] < 0)
4898     BlockElts = BlockSize / EltSz;
4899
4900   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4901     return false;
4902
4903   for (unsigned i = 0; i < NumElts; ++i) {
4904     if (M[i] < 0) continue; // ignore UNDEF indices
4905     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4906       return false;
4907   }
4908
4909   return true;
4910 }
4911
4912 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4913   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4914   // range, then 0 is placed into the resulting vector. So pretty much any mask
4915   // of 8 elements can work here.
4916   return VT == MVT::v8i8 && M.size() == 8;
4917 }
4918
4919 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4920   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4921   if (EltSz == 64)
4922     return false;
4923
4924   unsigned NumElts = VT.getVectorNumElements();
4925   WhichResult = (M[0] == 0 ? 0 : 1);
4926   for (unsigned i = 0; i < NumElts; i += 2) {
4927     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4928         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4929       return false;
4930   }
4931   return true;
4932 }
4933
4934 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4935 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4936 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4937 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4938   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4939   if (EltSz == 64)
4940     return false;
4941
4942   unsigned NumElts = VT.getVectorNumElements();
4943   WhichResult = (M[0] == 0 ? 0 : 1);
4944   for (unsigned i = 0; i < NumElts; i += 2) {
4945     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4946         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4947       return false;
4948   }
4949   return true;
4950 }
4951
4952 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4953   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4954   if (EltSz == 64)
4955     return false;
4956
4957   unsigned NumElts = VT.getVectorNumElements();
4958   WhichResult = (M[0] == 0 ? 0 : 1);
4959   for (unsigned i = 0; i != NumElts; ++i) {
4960     if (M[i] < 0) continue; // ignore UNDEF indices
4961     if ((unsigned) M[i] != 2 * i + WhichResult)
4962       return false;
4963   }
4964
4965   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4966   if (VT.is64BitVector() && EltSz == 32)
4967     return false;
4968
4969   return true;
4970 }
4971
4972 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4973 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4974 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4975 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4976   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4977   if (EltSz == 64)
4978     return false;
4979
4980   unsigned Half = VT.getVectorNumElements() / 2;
4981   WhichResult = (M[0] == 0 ? 0 : 1);
4982   for (unsigned j = 0; j != 2; ++j) {
4983     unsigned Idx = WhichResult;
4984     for (unsigned i = 0; i != Half; ++i) {
4985       int MIdx = M[i + j * Half];
4986       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4987         return false;
4988       Idx += 2;
4989     }
4990   }
4991
4992   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4993   if (VT.is64BitVector() && EltSz == 32)
4994     return false;
4995
4996   return true;
4997 }
4998
4999 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5000   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5001   if (EltSz == 64)
5002     return false;
5003
5004   unsigned NumElts = VT.getVectorNumElements();
5005   WhichResult = (M[0] == 0 ? 0 : 1);
5006   unsigned Idx = WhichResult * NumElts / 2;
5007   for (unsigned i = 0; i != NumElts; i += 2) {
5008     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5009         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5010       return false;
5011     Idx += 1;
5012   }
5013
5014   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5015   if (VT.is64BitVector() && EltSz == 32)
5016     return false;
5017
5018   return true;
5019 }
5020
5021 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5022 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5023 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5024 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5025   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5026   if (EltSz == 64)
5027     return false;
5028
5029   unsigned NumElts = VT.getVectorNumElements();
5030   WhichResult = (M[0] == 0 ? 0 : 1);
5031   unsigned Idx = WhichResult * NumElts / 2;
5032   for (unsigned i = 0; i != NumElts; i += 2) {
5033     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5034         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5035       return false;
5036     Idx += 1;
5037   }
5038
5039   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5040   if (VT.is64BitVector() && EltSz == 32)
5041     return false;
5042
5043   return true;
5044 }
5045
5046 /// \return true if this is a reverse operation on an vector.
5047 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5048   unsigned NumElts = VT.getVectorNumElements();
5049   // Make sure the mask has the right size.
5050   if (NumElts != M.size())
5051       return false;
5052
5053   // Look for <15, ..., 3, -1, 1, 0>.
5054   for (unsigned i = 0; i != NumElts; ++i)
5055     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5056       return false;
5057
5058   return true;
5059 }
5060
5061 // If N is an integer constant that can be moved into a register in one
5062 // instruction, return an SDValue of such a constant (will become a MOV
5063 // instruction).  Otherwise return null.
5064 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5065                                      const ARMSubtarget *ST, SDLoc dl) {
5066   uint64_t Val;
5067   if (!isa<ConstantSDNode>(N))
5068     return SDValue();
5069   Val = cast<ConstantSDNode>(N)->getZExtValue();
5070
5071   if (ST->isThumb1Only()) {
5072     if (Val <= 255 || ~Val <= 255)
5073       return DAG.getConstant(Val, MVT::i32);
5074   } else {
5075     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5076       return DAG.getConstant(Val, MVT::i32);
5077   }
5078   return SDValue();
5079 }
5080
5081 // If this is a case we can't handle, return null and let the default
5082 // expansion code take care of it.
5083 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5084                                              const ARMSubtarget *ST) const {
5085   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5086   SDLoc dl(Op);
5087   EVT VT = Op.getValueType();
5088
5089   APInt SplatBits, SplatUndef;
5090   unsigned SplatBitSize;
5091   bool HasAnyUndefs;
5092   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5093     if (SplatBitSize <= 64) {
5094       // Check if an immediate VMOV works.
5095       EVT VmovVT;
5096       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5097                                       SplatUndef.getZExtValue(), SplatBitSize,
5098                                       DAG, VmovVT, VT.is128BitVector(),
5099                                       VMOVModImm);
5100       if (Val.getNode()) {
5101         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5102         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5103       }
5104
5105       // Try an immediate VMVN.
5106       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5107       Val = isNEONModifiedImm(NegatedImm,
5108                                       SplatUndef.getZExtValue(), SplatBitSize,
5109                                       DAG, VmovVT, VT.is128BitVector(),
5110                                       VMVNModImm);
5111       if (Val.getNode()) {
5112         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5113         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5114       }
5115
5116       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5117       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5118         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5119         if (ImmVal != -1) {
5120           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5121           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5122         }
5123       }
5124     }
5125   }
5126
5127   // Scan through the operands to see if only one value is used.
5128   //
5129   // As an optimisation, even if more than one value is used it may be more
5130   // profitable to splat with one value then change some lanes.
5131   //
5132   // Heuristically we decide to do this if the vector has a "dominant" value,
5133   // defined as splatted to more than half of the lanes.
5134   unsigned NumElts = VT.getVectorNumElements();
5135   bool isOnlyLowElement = true;
5136   bool usesOnlyOneValue = true;
5137   bool hasDominantValue = false;
5138   bool isConstant = true;
5139
5140   // Map of the number of times a particular SDValue appears in the
5141   // element list.
5142   DenseMap<SDValue, unsigned> ValueCounts;
5143   SDValue Value;
5144   for (unsigned i = 0; i < NumElts; ++i) {
5145     SDValue V = Op.getOperand(i);
5146     if (V.getOpcode() == ISD::UNDEF)
5147       continue;
5148     if (i > 0)
5149       isOnlyLowElement = false;
5150     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5151       isConstant = false;
5152
5153     ValueCounts.insert(std::make_pair(V, 0));
5154     unsigned &Count = ValueCounts[V];
5155
5156     // Is this value dominant? (takes up more than half of the lanes)
5157     if (++Count > (NumElts / 2)) {
5158       hasDominantValue = true;
5159       Value = V;
5160     }
5161   }
5162   if (ValueCounts.size() != 1)
5163     usesOnlyOneValue = false;
5164   if (!Value.getNode() && ValueCounts.size() > 0)
5165     Value = ValueCounts.begin()->first;
5166
5167   if (ValueCounts.size() == 0)
5168     return DAG.getUNDEF(VT);
5169
5170   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5171   // Keep going if we are hitting this case.
5172   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5173     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5174
5175   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5176
5177   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5178   // i32 and try again.
5179   if (hasDominantValue && EltSize <= 32) {
5180     if (!isConstant) {
5181       SDValue N;
5182
5183       // If we are VDUPing a value that comes directly from a vector, that will
5184       // cause an unnecessary move to and from a GPR, where instead we could
5185       // just use VDUPLANE. We can only do this if the lane being extracted
5186       // is at a constant index, as the VDUP from lane instructions only have
5187       // constant-index forms.
5188       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5189           isa<ConstantSDNode>(Value->getOperand(1))) {
5190         // We need to create a new undef vector to use for the VDUPLANE if the
5191         // size of the vector from which we get the value is different than the
5192         // size of the vector that we need to create. We will insert the element
5193         // such that the register coalescer will remove unnecessary copies.
5194         if (VT != Value->getOperand(0).getValueType()) {
5195           ConstantSDNode *constIndex;
5196           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5197           assert(constIndex && "The index is not a constant!");
5198           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5199                              VT.getVectorNumElements();
5200           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5201                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5202                         Value, DAG.getConstant(index, MVT::i32)),
5203                            DAG.getConstant(index, MVT::i32));
5204         } else
5205           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5206                         Value->getOperand(0), Value->getOperand(1));
5207       } else
5208         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5209
5210       if (!usesOnlyOneValue) {
5211         // The dominant value was splatted as 'N', but we now have to insert
5212         // all differing elements.
5213         for (unsigned I = 0; I < NumElts; ++I) {
5214           if (Op.getOperand(I) == Value)
5215             continue;
5216           SmallVector<SDValue, 3> Ops;
5217           Ops.push_back(N);
5218           Ops.push_back(Op.getOperand(I));
5219           Ops.push_back(DAG.getConstant(I, MVT::i32));
5220           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5221         }
5222       }
5223       return N;
5224     }
5225     if (VT.getVectorElementType().isFloatingPoint()) {
5226       SmallVector<SDValue, 8> Ops;
5227       for (unsigned i = 0; i < NumElts; ++i)
5228         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5229                                   Op.getOperand(i)));
5230       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5231       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5232       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5233       if (Val.getNode())
5234         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5235     }
5236     if (usesOnlyOneValue) {
5237       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5238       if (isConstant && Val.getNode())
5239         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5240     }
5241   }
5242
5243   // If all elements are constants and the case above didn't get hit, fall back
5244   // to the default expansion, which will generate a load from the constant
5245   // pool.
5246   if (isConstant)
5247     return SDValue();
5248
5249   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5250   if (NumElts >= 4) {
5251     SDValue shuffle = ReconstructShuffle(Op, DAG);
5252     if (shuffle != SDValue())
5253       return shuffle;
5254   }
5255
5256   // Vectors with 32- or 64-bit elements can be built by directly assigning
5257   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5258   // will be legalized.
5259   if (EltSize >= 32) {
5260     // Do the expansion with floating-point types, since that is what the VFP
5261     // registers are defined to use, and since i64 is not legal.
5262     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5263     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5264     SmallVector<SDValue, 8> Ops;
5265     for (unsigned i = 0; i < NumElts; ++i)
5266       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5267     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5268     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5269   }
5270
5271   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5272   // know the default expansion would otherwise fall back on something even
5273   // worse. For a vector with one or two non-undef values, that's
5274   // scalar_to_vector for the elements followed by a shuffle (provided the
5275   // shuffle is valid for the target) and materialization element by element
5276   // on the stack followed by a load for everything else.
5277   if (!isConstant && !usesOnlyOneValue) {
5278     SDValue Vec = DAG.getUNDEF(VT);
5279     for (unsigned i = 0 ; i < NumElts; ++i) {
5280       SDValue V = Op.getOperand(i);
5281       if (V.getOpcode() == ISD::UNDEF)
5282         continue;
5283       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5284       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5285     }
5286     return Vec;
5287   }
5288
5289   return SDValue();
5290 }
5291
5292 // Gather data to see if the operation can be modelled as a
5293 // shuffle in combination with VEXTs.
5294 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5295                                               SelectionDAG &DAG) const {
5296   SDLoc dl(Op);
5297   EVT VT = Op.getValueType();
5298   unsigned NumElts = VT.getVectorNumElements();
5299
5300   SmallVector<SDValue, 2> SourceVecs;
5301   SmallVector<unsigned, 2> MinElts;
5302   SmallVector<unsigned, 2> MaxElts;
5303
5304   for (unsigned i = 0; i < NumElts; ++i) {
5305     SDValue V = Op.getOperand(i);
5306     if (V.getOpcode() == ISD::UNDEF)
5307       continue;
5308     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5309       // A shuffle can only come from building a vector from various
5310       // elements of other vectors.
5311       return SDValue();
5312     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5313                VT.getVectorElementType()) {
5314       // This code doesn't know how to handle shuffles where the vector
5315       // element types do not match (this happens because type legalization
5316       // promotes the return type of EXTRACT_VECTOR_ELT).
5317       // FIXME: It might be appropriate to extend this code to handle
5318       // mismatched types.
5319       return SDValue();
5320     }
5321
5322     // Record this extraction against the appropriate vector if possible...
5323     SDValue SourceVec = V.getOperand(0);
5324     // If the element number isn't a constant, we can't effectively
5325     // analyze what's going on.
5326     if (!isa<ConstantSDNode>(V.getOperand(1)))
5327       return SDValue();
5328     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5329     bool FoundSource = false;
5330     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5331       if (SourceVecs[j] == SourceVec) {
5332         if (MinElts[j] > EltNo)
5333           MinElts[j] = EltNo;
5334         if (MaxElts[j] < EltNo)
5335           MaxElts[j] = EltNo;
5336         FoundSource = true;
5337         break;
5338       }
5339     }
5340
5341     // Or record a new source if not...
5342     if (!FoundSource) {
5343       SourceVecs.push_back(SourceVec);
5344       MinElts.push_back(EltNo);
5345       MaxElts.push_back(EltNo);
5346     }
5347   }
5348
5349   // Currently only do something sane when at most two source vectors
5350   // involved.
5351   if (SourceVecs.size() > 2)
5352     return SDValue();
5353
5354   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5355   int VEXTOffsets[2] = {0, 0};
5356
5357   // This loop extracts the usage patterns of the source vectors
5358   // and prepares appropriate SDValues for a shuffle if possible.
5359   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5360     if (SourceVecs[i].getValueType() == VT) {
5361       // No VEXT necessary
5362       ShuffleSrcs[i] = SourceVecs[i];
5363       VEXTOffsets[i] = 0;
5364       continue;
5365     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5366       // It probably isn't worth padding out a smaller vector just to
5367       // break it down again in a shuffle.
5368       return SDValue();
5369     }
5370
5371     // Since only 64-bit and 128-bit vectors are legal on ARM and
5372     // we've eliminated the other cases...
5373     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5374            "unexpected vector sizes in ReconstructShuffle");
5375
5376     if (MaxElts[i] - MinElts[i] >= NumElts) {
5377       // Span too large for a VEXT to cope
5378       return SDValue();
5379     }
5380
5381     if (MinElts[i] >= NumElts) {
5382       // The extraction can just take the second half
5383       VEXTOffsets[i] = NumElts;
5384       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5385                                    SourceVecs[i],
5386                                    DAG.getIntPtrConstant(NumElts));
5387     } else if (MaxElts[i] < NumElts) {
5388       // The extraction can just take the first half
5389       VEXTOffsets[i] = 0;
5390       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5391                                    SourceVecs[i],
5392                                    DAG.getIntPtrConstant(0));
5393     } else {
5394       // An actual VEXT is needed
5395       VEXTOffsets[i] = MinElts[i];
5396       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5397                                      SourceVecs[i],
5398                                      DAG.getIntPtrConstant(0));
5399       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5400                                      SourceVecs[i],
5401                                      DAG.getIntPtrConstant(NumElts));
5402       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5403                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5404     }
5405   }
5406
5407   SmallVector<int, 8> Mask;
5408
5409   for (unsigned i = 0; i < NumElts; ++i) {
5410     SDValue Entry = Op.getOperand(i);
5411     if (Entry.getOpcode() == ISD::UNDEF) {
5412       Mask.push_back(-1);
5413       continue;
5414     }
5415
5416     SDValue ExtractVec = Entry.getOperand(0);
5417     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5418                                           .getOperand(1))->getSExtValue();
5419     if (ExtractVec == SourceVecs[0]) {
5420       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5421     } else {
5422       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5423     }
5424   }
5425
5426   // Final check before we try to produce nonsense...
5427   if (isShuffleMaskLegal(Mask, VT))
5428     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5429                                 &Mask[0]);
5430
5431   return SDValue();
5432 }
5433
5434 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5435 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5436 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5437 /// are assumed to be legal.
5438 bool
5439 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5440                                       EVT VT) const {
5441   if (VT.getVectorNumElements() == 4 &&
5442       (VT.is128BitVector() || VT.is64BitVector())) {
5443     unsigned PFIndexes[4];
5444     for (unsigned i = 0; i != 4; ++i) {
5445       if (M[i] < 0)
5446         PFIndexes[i] = 8;
5447       else
5448         PFIndexes[i] = M[i];
5449     }
5450
5451     // Compute the index in the perfect shuffle table.
5452     unsigned PFTableIndex =
5453       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5454     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5455     unsigned Cost = (PFEntry >> 30);
5456
5457     if (Cost <= 4)
5458       return true;
5459   }
5460
5461   bool ReverseVEXT;
5462   unsigned Imm, WhichResult;
5463
5464   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5465   return (EltSize >= 32 ||
5466           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5467           isVREVMask(M, VT, 64) ||
5468           isVREVMask(M, VT, 32) ||
5469           isVREVMask(M, VT, 16) ||
5470           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5471           isVTBLMask(M, VT) ||
5472           isVTRNMask(M, VT, WhichResult) ||
5473           isVUZPMask(M, VT, WhichResult) ||
5474           isVZIPMask(M, VT, WhichResult) ||
5475           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5476           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5477           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5478           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5479 }
5480
5481 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5482 /// the specified operations to build the shuffle.
5483 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5484                                       SDValue RHS, SelectionDAG &DAG,
5485                                       SDLoc dl) {
5486   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5487   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5488   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5489
5490   enum {
5491     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5492     OP_VREV,
5493     OP_VDUP0,
5494     OP_VDUP1,
5495     OP_VDUP2,
5496     OP_VDUP3,
5497     OP_VEXT1,
5498     OP_VEXT2,
5499     OP_VEXT3,
5500     OP_VUZPL, // VUZP, left result
5501     OP_VUZPR, // VUZP, right result
5502     OP_VZIPL, // VZIP, left result
5503     OP_VZIPR, // VZIP, right result
5504     OP_VTRNL, // VTRN, left result
5505     OP_VTRNR  // VTRN, right result
5506   };
5507
5508   if (OpNum == OP_COPY) {
5509     if (LHSID == (1*9+2)*9+3) return LHS;
5510     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5511     return RHS;
5512   }
5513
5514   SDValue OpLHS, OpRHS;
5515   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5516   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5517   EVT VT = OpLHS.getValueType();
5518
5519   switch (OpNum) {
5520   default: llvm_unreachable("Unknown shuffle opcode!");
5521   case OP_VREV:
5522     // VREV divides the vector in half and swaps within the half.
5523     if (VT.getVectorElementType() == MVT::i32 ||
5524         VT.getVectorElementType() == MVT::f32)
5525       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5526     // vrev <4 x i16> -> VREV32
5527     if (VT.getVectorElementType() == MVT::i16)
5528       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5529     // vrev <4 x i8> -> VREV16
5530     assert(VT.getVectorElementType() == MVT::i8);
5531     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5532   case OP_VDUP0:
5533   case OP_VDUP1:
5534   case OP_VDUP2:
5535   case OP_VDUP3:
5536     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5537                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5538   case OP_VEXT1:
5539   case OP_VEXT2:
5540   case OP_VEXT3:
5541     return DAG.getNode(ARMISD::VEXT, dl, VT,
5542                        OpLHS, OpRHS,
5543                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5544   case OP_VUZPL:
5545   case OP_VUZPR:
5546     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5547                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5548   case OP_VZIPL:
5549   case OP_VZIPR:
5550     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5551                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5552   case OP_VTRNL:
5553   case OP_VTRNR:
5554     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5555                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5556   }
5557 }
5558
5559 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5560                                        ArrayRef<int> ShuffleMask,
5561                                        SelectionDAG &DAG) {
5562   // Check to see if we can use the VTBL instruction.
5563   SDValue V1 = Op.getOperand(0);
5564   SDValue V2 = Op.getOperand(1);
5565   SDLoc DL(Op);
5566
5567   SmallVector<SDValue, 8> VTBLMask;
5568   for (ArrayRef<int>::iterator
5569          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5570     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5571
5572   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5573     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5574                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5575
5576   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5577                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5578 }
5579
5580 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5581                                                       SelectionDAG &DAG) {
5582   SDLoc DL(Op);
5583   SDValue OpLHS = Op.getOperand(0);
5584   EVT VT = OpLHS.getValueType();
5585
5586   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5587          "Expect an v8i16/v16i8 type");
5588   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5589   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5590   // extract the first 8 bytes into the top double word and the last 8 bytes
5591   // into the bottom double word. The v8i16 case is similar.
5592   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5593   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5594                      DAG.getConstant(ExtractNum, MVT::i32));
5595 }
5596
5597 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5598   SDValue V1 = Op.getOperand(0);
5599   SDValue V2 = Op.getOperand(1);
5600   SDLoc dl(Op);
5601   EVT VT = Op.getValueType();
5602   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5603
5604   // Convert shuffles that are directly supported on NEON to target-specific
5605   // DAG nodes, instead of keeping them as shuffles and matching them again
5606   // during code selection.  This is more efficient and avoids the possibility
5607   // of inconsistencies between legalization and selection.
5608   // FIXME: floating-point vectors should be canonicalized to integer vectors
5609   // of the same time so that they get CSEd properly.
5610   ArrayRef<int> ShuffleMask = SVN->getMask();
5611
5612   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5613   if (EltSize <= 32) {
5614     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5615       int Lane = SVN->getSplatIndex();
5616       // If this is undef splat, generate it via "just" vdup, if possible.
5617       if (Lane == -1) Lane = 0;
5618
5619       // Test if V1 is a SCALAR_TO_VECTOR.
5620       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5621         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5622       }
5623       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5624       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5625       // reaches it).
5626       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5627           !isa<ConstantSDNode>(V1.getOperand(0))) {
5628         bool IsScalarToVector = true;
5629         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5630           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5631             IsScalarToVector = false;
5632             break;
5633           }
5634         if (IsScalarToVector)
5635           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5636       }
5637       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5638                          DAG.getConstant(Lane, MVT::i32));
5639     }
5640
5641     bool ReverseVEXT;
5642     unsigned Imm;
5643     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5644       if (ReverseVEXT)
5645         std::swap(V1, V2);
5646       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5647                          DAG.getConstant(Imm, MVT::i32));
5648     }
5649
5650     if (isVREVMask(ShuffleMask, VT, 64))
5651       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5652     if (isVREVMask(ShuffleMask, VT, 32))
5653       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5654     if (isVREVMask(ShuffleMask, VT, 16))
5655       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5656
5657     if (V2->getOpcode() == ISD::UNDEF &&
5658         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5659       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5660                          DAG.getConstant(Imm, MVT::i32));
5661     }
5662
5663     // Check for Neon shuffles that modify both input vectors in place.
5664     // If both results are used, i.e., if there are two shuffles with the same
5665     // source operands and with masks corresponding to both results of one of
5666     // these operations, DAG memoization will ensure that a single node is
5667     // used for both shuffles.
5668     unsigned WhichResult;
5669     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5670       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5671                          V1, V2).getValue(WhichResult);
5672     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5673       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5674                          V1, V2).getValue(WhichResult);
5675     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5676       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5677                          V1, V2).getValue(WhichResult);
5678
5679     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5680       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5681                          V1, V1).getValue(WhichResult);
5682     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5683       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5684                          V1, V1).getValue(WhichResult);
5685     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5686       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5687                          V1, V1).getValue(WhichResult);
5688   }
5689
5690   // If the shuffle is not directly supported and it has 4 elements, use
5691   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5692   unsigned NumElts = VT.getVectorNumElements();
5693   if (NumElts == 4) {
5694     unsigned PFIndexes[4];
5695     for (unsigned i = 0; i != 4; ++i) {
5696       if (ShuffleMask[i] < 0)
5697         PFIndexes[i] = 8;
5698       else
5699         PFIndexes[i] = ShuffleMask[i];
5700     }
5701
5702     // Compute the index in the perfect shuffle table.
5703     unsigned PFTableIndex =
5704       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5705     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5706     unsigned Cost = (PFEntry >> 30);
5707
5708     if (Cost <= 4)
5709       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5710   }
5711
5712   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5713   if (EltSize >= 32) {
5714     // Do the expansion with floating-point types, since that is what the VFP
5715     // registers are defined to use, and since i64 is not legal.
5716     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5717     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5718     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5719     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5720     SmallVector<SDValue, 8> Ops;
5721     for (unsigned i = 0; i < NumElts; ++i) {
5722       if (ShuffleMask[i] < 0)
5723         Ops.push_back(DAG.getUNDEF(EltVT));
5724       else
5725         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5726                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5727                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5728                                                   MVT::i32)));
5729     }
5730     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5731     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5732   }
5733
5734   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5735     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5736
5737   if (VT == MVT::v8i8) {
5738     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5739     if (NewOp.getNode())
5740       return NewOp;
5741   }
5742
5743   return SDValue();
5744 }
5745
5746 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5747   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5748   SDValue Lane = Op.getOperand(2);
5749   if (!isa<ConstantSDNode>(Lane))
5750     return SDValue();
5751
5752   return Op;
5753 }
5754
5755 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5756   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5757   SDValue Lane = Op.getOperand(1);
5758   if (!isa<ConstantSDNode>(Lane))
5759     return SDValue();
5760
5761   SDValue Vec = Op.getOperand(0);
5762   if (Op.getValueType() == MVT::i32 &&
5763       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5764     SDLoc dl(Op);
5765     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5766   }
5767
5768   return Op;
5769 }
5770
5771 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5772   // The only time a CONCAT_VECTORS operation can have legal types is when
5773   // two 64-bit vectors are concatenated to a 128-bit vector.
5774   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5775          "unexpected CONCAT_VECTORS");
5776   SDLoc dl(Op);
5777   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5778   SDValue Op0 = Op.getOperand(0);
5779   SDValue Op1 = Op.getOperand(1);
5780   if (Op0.getOpcode() != ISD::UNDEF)
5781     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5782                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5783                       DAG.getIntPtrConstant(0));
5784   if (Op1.getOpcode() != ISD::UNDEF)
5785     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5786                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5787                       DAG.getIntPtrConstant(1));
5788   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5789 }
5790
5791 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5792 /// element has been zero/sign-extended, depending on the isSigned parameter,
5793 /// from an integer type half its size.
5794 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5795                                    bool isSigned) {
5796   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5797   EVT VT = N->getValueType(0);
5798   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5799     SDNode *BVN = N->getOperand(0).getNode();
5800     if (BVN->getValueType(0) != MVT::v4i32 ||
5801         BVN->getOpcode() != ISD::BUILD_VECTOR)
5802       return false;
5803     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5804     unsigned HiElt = 1 - LoElt;
5805     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5806     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5807     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5808     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5809     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5810       return false;
5811     if (isSigned) {
5812       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5813           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5814         return true;
5815     } else {
5816       if (Hi0->isNullValue() && Hi1->isNullValue())
5817         return true;
5818     }
5819     return false;
5820   }
5821
5822   if (N->getOpcode() != ISD::BUILD_VECTOR)
5823     return false;
5824
5825   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5826     SDNode *Elt = N->getOperand(i).getNode();
5827     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5828       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5829       unsigned HalfSize = EltSize / 2;
5830       if (isSigned) {
5831         if (!isIntN(HalfSize, C->getSExtValue()))
5832           return false;
5833       } else {
5834         if (!isUIntN(HalfSize, C->getZExtValue()))
5835           return false;
5836       }
5837       continue;
5838     }
5839     return false;
5840   }
5841
5842   return true;
5843 }
5844
5845 /// isSignExtended - Check if a node is a vector value that is sign-extended
5846 /// or a constant BUILD_VECTOR with sign-extended elements.
5847 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5848   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5849     return true;
5850   if (isExtendedBUILD_VECTOR(N, DAG, true))
5851     return true;
5852   return false;
5853 }
5854
5855 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5856 /// or a constant BUILD_VECTOR with zero-extended elements.
5857 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5858   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5859     return true;
5860   if (isExtendedBUILD_VECTOR(N, DAG, false))
5861     return true;
5862   return false;
5863 }
5864
5865 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5866   if (OrigVT.getSizeInBits() >= 64)
5867     return OrigVT;
5868
5869   assert(OrigVT.isSimple() && "Expecting a simple value type");
5870
5871   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5872   switch (OrigSimpleTy) {
5873   default: llvm_unreachable("Unexpected Vector Type");
5874   case MVT::v2i8:
5875   case MVT::v2i16:
5876      return MVT::v2i32;
5877   case MVT::v4i8:
5878     return  MVT::v4i16;
5879   }
5880 }
5881
5882 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5883 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5884 /// We insert the required extension here to get the vector to fill a D register.
5885 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5886                                             const EVT &OrigTy,
5887                                             const EVT &ExtTy,
5888                                             unsigned ExtOpcode) {
5889   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5890   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5891   // 64-bits we need to insert a new extension so that it will be 64-bits.
5892   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5893   if (OrigTy.getSizeInBits() >= 64)
5894     return N;
5895
5896   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5897   EVT NewVT = getExtensionTo64Bits(OrigTy);
5898
5899   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5900 }
5901
5902 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5903 /// does not do any sign/zero extension. If the original vector is less
5904 /// than 64 bits, an appropriate extension will be added after the load to
5905 /// reach a total size of 64 bits. We have to add the extension separately
5906 /// because ARM does not have a sign/zero extending load for vectors.
5907 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5908   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5909
5910   // The load already has the right type.
5911   if (ExtendedTy == LD->getMemoryVT())
5912     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5913                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5914                 LD->isNonTemporal(), LD->isInvariant(),
5915                 LD->getAlignment());
5916
5917   // We need to create a zextload/sextload. We cannot just create a load
5918   // followed by a zext/zext node because LowerMUL is also run during normal
5919   // operation legalization where we can't create illegal types.
5920   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5921                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5922                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5923                         LD->isNonTemporal(), LD->getAlignment());
5924 }
5925
5926 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5927 /// extending load, or BUILD_VECTOR with extended elements, return the
5928 /// unextended value. The unextended vector should be 64 bits so that it can
5929 /// be used as an operand to a VMULL instruction. If the original vector size
5930 /// before extension is less than 64 bits we add a an extension to resize
5931 /// the vector to 64 bits.
5932 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5933   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5934     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5935                                         N->getOperand(0)->getValueType(0),
5936                                         N->getValueType(0),
5937                                         N->getOpcode());
5938
5939   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5940     return SkipLoadExtensionForVMULL(LD, DAG);
5941
5942   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5943   // have been legalized as a BITCAST from v4i32.
5944   if (N->getOpcode() == ISD::BITCAST) {
5945     SDNode *BVN = N->getOperand(0).getNode();
5946     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5947            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5948     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5949     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5950                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5951   }
5952   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5953   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5954   EVT VT = N->getValueType(0);
5955   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5956   unsigned NumElts = VT.getVectorNumElements();
5957   MVT TruncVT = MVT::getIntegerVT(EltSize);
5958   SmallVector<SDValue, 8> Ops;
5959   for (unsigned i = 0; i != NumElts; ++i) {
5960     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5961     const APInt &CInt = C->getAPIntValue();
5962     // Element types smaller than 32 bits are not legal, so use i32 elements.
5963     // The values are implicitly truncated so sext vs. zext doesn't matter.
5964     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5965   }
5966   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5967                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5968 }
5969
5970 static bool isAddSubSExt(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       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5977   }
5978   return false;
5979 }
5980
5981 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5982   unsigned Opcode = N->getOpcode();
5983   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5984     SDNode *N0 = N->getOperand(0).getNode();
5985     SDNode *N1 = N->getOperand(1).getNode();
5986     return N0->hasOneUse() && N1->hasOneUse() &&
5987       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5988   }
5989   return false;
5990 }
5991
5992 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5993   // Multiplications are only custom-lowered for 128-bit vectors so that
5994   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5995   EVT VT = Op.getValueType();
5996   assert(VT.is128BitVector() && VT.isInteger() &&
5997          "unexpected type for custom-lowering ISD::MUL");
5998   SDNode *N0 = Op.getOperand(0).getNode();
5999   SDNode *N1 = Op.getOperand(1).getNode();
6000   unsigned NewOpc = 0;
6001   bool isMLA = false;
6002   bool isN0SExt = isSignExtended(N0, DAG);
6003   bool isN1SExt = isSignExtended(N1, DAG);
6004   if (isN0SExt && isN1SExt)
6005     NewOpc = ARMISD::VMULLs;
6006   else {
6007     bool isN0ZExt = isZeroExtended(N0, DAG);
6008     bool isN1ZExt = isZeroExtended(N1, DAG);
6009     if (isN0ZExt && isN1ZExt)
6010       NewOpc = ARMISD::VMULLu;
6011     else if (isN1SExt || isN1ZExt) {
6012       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6013       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6014       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6015         NewOpc = ARMISD::VMULLs;
6016         isMLA = true;
6017       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6018         NewOpc = ARMISD::VMULLu;
6019         isMLA = true;
6020       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6021         std::swap(N0, N1);
6022         NewOpc = ARMISD::VMULLu;
6023         isMLA = true;
6024       }
6025     }
6026
6027     if (!NewOpc) {
6028       if (VT == MVT::v2i64)
6029         // Fall through to expand this.  It is not legal.
6030         return SDValue();
6031       else
6032         // Other vector multiplications are legal.
6033         return Op;
6034     }
6035   }
6036
6037   // Legalize to a VMULL instruction.
6038   SDLoc DL(Op);
6039   SDValue Op0;
6040   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6041   if (!isMLA) {
6042     Op0 = SkipExtensionForVMULL(N0, DAG);
6043     assert(Op0.getValueType().is64BitVector() &&
6044            Op1.getValueType().is64BitVector() &&
6045            "unexpected types for extended operands to VMULL");
6046     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6047   }
6048
6049   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6050   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6051   //   vmull q0, d4, d6
6052   //   vmlal q0, d5, d6
6053   // is faster than
6054   //   vaddl q0, d4, d5
6055   //   vmovl q1, d6
6056   //   vmul  q0, q0, q1
6057   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6058   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6059   EVT Op1VT = Op1.getValueType();
6060   return DAG.getNode(N0->getOpcode(), DL, VT,
6061                      DAG.getNode(NewOpc, DL, VT,
6062                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6063                      DAG.getNode(NewOpc, DL, VT,
6064                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6065 }
6066
6067 static SDValue
6068 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6069   // Convert to float
6070   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6071   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6072   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6073   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6074   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6075   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6076   // Get reciprocal estimate.
6077   // float4 recip = vrecpeq_f32(yf);
6078   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6079                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6080   // Because char has a smaller range than uchar, we can actually get away
6081   // without any newton steps.  This requires that we use a weird bias
6082   // of 0xb000, however (again, this has been exhaustively tested).
6083   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6084   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6085   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6086   Y = DAG.getConstant(0xb000, MVT::i32);
6087   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6088   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6089   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6090   // Convert back to short.
6091   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6092   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6093   return X;
6094 }
6095
6096 static SDValue
6097 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6098   SDValue N2;
6099   // Convert to float.
6100   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6101   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6102   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6103   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6104   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6105   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6106
6107   // Use reciprocal estimate and one refinement step.
6108   // float4 recip = vrecpeq_f32(yf);
6109   // recip *= vrecpsq_f32(yf, recip);
6110   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6111                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6112   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6113                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6114                    N1, N2);
6115   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6116   // Because short has a smaller range than ushort, we can actually get away
6117   // with only a single newton step.  This requires that we use a weird bias
6118   // of 89, however (again, this has been exhaustively tested).
6119   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6120   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6121   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6122   N1 = DAG.getConstant(0x89, MVT::i32);
6123   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6124   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6125   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6126   // Convert back to integer and return.
6127   // return vmovn_s32(vcvt_s32_f32(result));
6128   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6129   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6130   return N0;
6131 }
6132
6133 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6134   EVT VT = Op.getValueType();
6135   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6136          "unexpected type for custom-lowering ISD::SDIV");
6137
6138   SDLoc dl(Op);
6139   SDValue N0 = Op.getOperand(0);
6140   SDValue N1 = Op.getOperand(1);
6141   SDValue N2, N3;
6142
6143   if (VT == MVT::v8i8) {
6144     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6145     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6146
6147     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6148                      DAG.getIntPtrConstant(4));
6149     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6150                      DAG.getIntPtrConstant(4));
6151     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6152                      DAG.getIntPtrConstant(0));
6153     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6154                      DAG.getIntPtrConstant(0));
6155
6156     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6157     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6158
6159     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6160     N0 = LowerCONCAT_VECTORS(N0, DAG);
6161
6162     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6163     return N0;
6164   }
6165   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6166 }
6167
6168 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6169   EVT VT = Op.getValueType();
6170   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6171          "unexpected type for custom-lowering ISD::UDIV");
6172
6173   SDLoc dl(Op);
6174   SDValue N0 = Op.getOperand(0);
6175   SDValue N1 = Op.getOperand(1);
6176   SDValue N2, N3;
6177
6178   if (VT == MVT::v8i8) {
6179     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6180     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6181
6182     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6183                      DAG.getIntPtrConstant(4));
6184     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6185                      DAG.getIntPtrConstant(4));
6186     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6187                      DAG.getIntPtrConstant(0));
6188     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6189                      DAG.getIntPtrConstant(0));
6190
6191     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6192     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6193
6194     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6195     N0 = LowerCONCAT_VECTORS(N0, DAG);
6196
6197     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6198                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6199                      N0);
6200     return N0;
6201   }
6202
6203   // v4i16 sdiv ... Convert to float.
6204   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6205   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6206   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6207   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6208   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6209   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6210
6211   // Use reciprocal estimate and two refinement steps.
6212   // float4 recip = vrecpeq_f32(yf);
6213   // recip *= vrecpsq_f32(yf, recip);
6214   // recip *= vrecpsq_f32(yf, recip);
6215   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6216                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6217   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6218                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6219                    BN1, N2);
6220   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6221   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6222                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6223                    BN1, N2);
6224   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6225   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6226   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6227   // and that it will never cause us to return an answer too large).
6228   // float4 result = as_float4(as_int4(xf*recip) + 2);
6229   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6230   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6231   N1 = DAG.getConstant(2, MVT::i32);
6232   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6233   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6234   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6235   // Convert back to integer and return.
6236   // return vmovn_u32(vcvt_s32_f32(result));
6237   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6238   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6239   return N0;
6240 }
6241
6242 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6243   EVT VT = Op.getNode()->getValueType(0);
6244   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6245
6246   unsigned Opc;
6247   bool ExtraOp = false;
6248   switch (Op.getOpcode()) {
6249   default: llvm_unreachable("Invalid code");
6250   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6251   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6252   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6253   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6254   }
6255
6256   if (!ExtraOp)
6257     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6258                        Op.getOperand(1));
6259   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6260                      Op.getOperand(1), Op.getOperand(2));
6261 }
6262
6263 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6264   assert(Subtarget->isTargetDarwin());
6265
6266   // For iOS, we want to call an alternative entry point: __sincos_stret,
6267   // return values are passed via sret.
6268   SDLoc dl(Op);
6269   SDValue Arg = Op.getOperand(0);
6270   EVT ArgVT = Arg.getValueType();
6271   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6272
6273   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6275
6276   // Pair of floats / doubles used to pass the result.
6277   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6278
6279   // Create stack object for sret.
6280   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6281   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6282   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6283   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6284
6285   ArgListTy Args;
6286   ArgListEntry Entry;
6287
6288   Entry.Node = SRet;
6289   Entry.Ty = RetTy->getPointerTo();
6290   Entry.isSExt = false;
6291   Entry.isZExt = false;
6292   Entry.isSRet = true;
6293   Args.push_back(Entry);
6294
6295   Entry.Node = Arg;
6296   Entry.Ty = ArgTy;
6297   Entry.isSExt = false;
6298   Entry.isZExt = false;
6299   Args.push_back(Entry);
6300
6301   const char *LibcallName  = (ArgVT == MVT::f64)
6302   ? "__sincos_stret" : "__sincosf_stret";
6303   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6304
6305   TargetLowering::CallLoweringInfo CLI(DAG);
6306   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6307     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6308                std::move(Args), 0)
6309     .setDiscardResult();
6310
6311   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6312
6313   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6314                                 MachinePointerInfo(), false, false, false, 0);
6315
6316   // Address of cos field.
6317   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6318                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6319   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6320                                 MachinePointerInfo(), false, false, false, 0);
6321
6322   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6323   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6324                      LoadSin.getValue(0), LoadCos.getValue(0));
6325 }
6326
6327 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6328   // Monotonic load/store is legal for all targets
6329   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6330     return Op;
6331
6332   // Acquire/Release load/store is not legal for targets without a
6333   // dmb or equivalent available.
6334   return SDValue();
6335 }
6336
6337 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6338                                     SmallVectorImpl<SDValue> &Results,
6339                                     SelectionDAG &DAG,
6340                                     const ARMSubtarget *Subtarget) {
6341   SDLoc DL(N);
6342   SDValue Cycles32, OutChain;
6343
6344   if (Subtarget->hasPerfMon()) {
6345     // Under Power Management extensions, the cycle-count is:
6346     //    mrc p15, #0, <Rt>, c9, c13, #0
6347     SDValue Ops[] = { N->getOperand(0), // Chain
6348                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6349                       DAG.getConstant(15, MVT::i32),
6350                       DAG.getConstant(0, MVT::i32),
6351                       DAG.getConstant(9, MVT::i32),
6352                       DAG.getConstant(13, MVT::i32),
6353                       DAG.getConstant(0, MVT::i32)
6354     };
6355
6356     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6357                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6358     OutChain = Cycles32.getValue(1);
6359   } else {
6360     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6361     // there are older ARM CPUs that have implementation-specific ways of
6362     // obtaining this information (FIXME!).
6363     Cycles32 = DAG.getConstant(0, MVT::i32);
6364     OutChain = DAG.getEntryNode();
6365   }
6366
6367
6368   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6369                                  Cycles32, DAG.getConstant(0, MVT::i32));
6370   Results.push_back(Cycles64);
6371   Results.push_back(OutChain);
6372 }
6373
6374 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6375   switch (Op.getOpcode()) {
6376   default: llvm_unreachable("Don't know how to custom lower this!");
6377   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6378   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6379   case ISD::GlobalAddress:
6380     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6381     default: llvm_unreachable("unknown object format");
6382     case Triple::COFF:
6383       return LowerGlobalAddressWindows(Op, DAG);
6384     case Triple::ELF:
6385       return LowerGlobalAddressELF(Op, DAG);
6386     case Triple::MachO:
6387       return LowerGlobalAddressDarwin(Op, DAG);
6388     }
6389   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6390   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6391   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6392   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6393   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6394   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6395   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6396   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6397   case ISD::SINT_TO_FP:
6398   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6399   case ISD::FP_TO_SINT:
6400   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6401   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6402   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6403   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6404   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6405   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6406   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6407   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6408                                                                Subtarget);
6409   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6410   case ISD::SHL:
6411   case ISD::SRL:
6412   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6413   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6414   case ISD::SRL_PARTS:
6415   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6416   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6417   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6418   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6419   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6420   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6421   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6422   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6423   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6424   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6425   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6426   case ISD::MUL:           return LowerMUL(Op, DAG);
6427   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6428   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6429   case ISD::ADDC:
6430   case ISD::ADDE:
6431   case ISD::SUBC:
6432   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6433   case ISD::SADDO:
6434   case ISD::UADDO:
6435   case ISD::SSUBO:
6436   case ISD::USUBO:
6437     return LowerXALUO(Op, DAG);
6438   case ISD::ATOMIC_LOAD:
6439   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6440   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6441   case ISD::SDIVREM:
6442   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6443   case ISD::DYNAMIC_STACKALLOC:
6444     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6445       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6446     llvm_unreachable("Don't know how to custom lower this!");
6447   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6448   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6449   }
6450 }
6451
6452 /// ReplaceNodeResults - Replace the results of node with an illegal result
6453 /// type with new values built out of custom code.
6454 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6455                                            SmallVectorImpl<SDValue>&Results,
6456                                            SelectionDAG &DAG) const {
6457   SDValue Res;
6458   switch (N->getOpcode()) {
6459   default:
6460     llvm_unreachable("Don't know how to custom expand this!");
6461   case ISD::BITCAST:
6462     Res = ExpandBITCAST(N, DAG);
6463     break;
6464   case ISD::SRL:
6465   case ISD::SRA:
6466     Res = Expand64BitShift(N, DAG, Subtarget);
6467     break;
6468   case ISD::READCYCLECOUNTER:
6469     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6470     return;
6471   }
6472   if (Res.getNode())
6473     Results.push_back(Res);
6474 }
6475
6476 //===----------------------------------------------------------------------===//
6477 //                           ARM Scheduler Hooks
6478 //===----------------------------------------------------------------------===//
6479
6480 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6481 /// registers the function context.
6482 void ARMTargetLowering::
6483 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6484                        MachineBasicBlock *DispatchBB, int FI) const {
6485   const TargetInstrInfo *TII =
6486       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6487   DebugLoc dl = MI->getDebugLoc();
6488   MachineFunction *MF = MBB->getParent();
6489   MachineRegisterInfo *MRI = &MF->getRegInfo();
6490   MachineConstantPool *MCP = MF->getConstantPool();
6491   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6492   const Function *F = MF->getFunction();
6493
6494   bool isThumb = Subtarget->isThumb();
6495   bool isThumb2 = Subtarget->isThumb2();
6496
6497   unsigned PCLabelId = AFI->createPICLabelUId();
6498   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6499   ARMConstantPoolValue *CPV =
6500     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6501   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6502
6503   const TargetRegisterClass *TRC = isThumb ?
6504     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6505     (const TargetRegisterClass*)&ARM::GPRRegClass;
6506
6507   // Grab constant pool and fixed stack memory operands.
6508   MachineMemOperand *CPMMO =
6509     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6510                              MachineMemOperand::MOLoad, 4, 4);
6511
6512   MachineMemOperand *FIMMOSt =
6513     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6514                              MachineMemOperand::MOStore, 4, 4);
6515
6516   // Load the address of the dispatch MBB into the jump buffer.
6517   if (isThumb2) {
6518     // Incoming value: jbuf
6519     //   ldr.n  r5, LCPI1_1
6520     //   orr    r5, r5, #1
6521     //   add    r5, pc
6522     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6523     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6524     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6525                    .addConstantPoolIndex(CPI)
6526                    .addMemOperand(CPMMO));
6527     // Set the low bit because of thumb mode.
6528     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6529     AddDefaultCC(
6530       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6531                      .addReg(NewVReg1, RegState::Kill)
6532                      .addImm(0x01)));
6533     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6534     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6535       .addReg(NewVReg2, RegState::Kill)
6536       .addImm(PCLabelId);
6537     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6538                    .addReg(NewVReg3, RegState::Kill)
6539                    .addFrameIndex(FI)
6540                    .addImm(36)  // &jbuf[1] :: pc
6541                    .addMemOperand(FIMMOSt));
6542   } else if (isThumb) {
6543     // Incoming value: jbuf
6544     //   ldr.n  r1, LCPI1_4
6545     //   add    r1, pc
6546     //   mov    r2, #1
6547     //   orrs   r1, r2
6548     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6549     //   str    r1, [r2]
6550     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6551     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6552                    .addConstantPoolIndex(CPI)
6553                    .addMemOperand(CPMMO));
6554     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6555     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6556       .addReg(NewVReg1, RegState::Kill)
6557       .addImm(PCLabelId);
6558     // Set the low bit because of thumb mode.
6559     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6560     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6561                    .addReg(ARM::CPSR, RegState::Define)
6562                    .addImm(1));
6563     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6564     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6565                    .addReg(ARM::CPSR, RegState::Define)
6566                    .addReg(NewVReg2, RegState::Kill)
6567                    .addReg(NewVReg3, RegState::Kill));
6568     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6569     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6570                    .addFrameIndex(FI)
6571                    .addImm(36)); // &jbuf[1] :: pc
6572     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6573                    .addReg(NewVReg4, RegState::Kill)
6574                    .addReg(NewVReg5, RegState::Kill)
6575                    .addImm(0)
6576                    .addMemOperand(FIMMOSt));
6577   } else {
6578     // Incoming value: jbuf
6579     //   ldr  r1, LCPI1_1
6580     //   add  r1, pc, r1
6581     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6582     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6583     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6584                    .addConstantPoolIndex(CPI)
6585                    .addImm(0)
6586                    .addMemOperand(CPMMO));
6587     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6588     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6589                    .addReg(NewVReg1, RegState::Kill)
6590                    .addImm(PCLabelId));
6591     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6592                    .addReg(NewVReg2, RegState::Kill)
6593                    .addFrameIndex(FI)
6594                    .addImm(36)  // &jbuf[1] :: pc
6595                    .addMemOperand(FIMMOSt));
6596   }
6597 }
6598
6599 MachineBasicBlock *ARMTargetLowering::
6600 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6601   const TargetInstrInfo *TII =
6602       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6603   DebugLoc dl = MI->getDebugLoc();
6604   MachineFunction *MF = MBB->getParent();
6605   MachineRegisterInfo *MRI = &MF->getRegInfo();
6606   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6607   MachineFrameInfo *MFI = MF->getFrameInfo();
6608   int FI = MFI->getFunctionContextIndex();
6609
6610   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6611     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6612     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6613
6614   // Get a mapping of the call site numbers to all of the landing pads they're
6615   // associated with.
6616   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6617   unsigned MaxCSNum = 0;
6618   MachineModuleInfo &MMI = MF->getMMI();
6619   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6620        ++BB) {
6621     if (!BB->isLandingPad()) continue;
6622
6623     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6624     // pad.
6625     for (MachineBasicBlock::iterator
6626            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6627       if (!II->isEHLabel()) continue;
6628
6629       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6630       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6631
6632       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6633       for (SmallVectorImpl<unsigned>::iterator
6634              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6635            CSI != CSE; ++CSI) {
6636         CallSiteNumToLPad[*CSI].push_back(BB);
6637         MaxCSNum = std::max(MaxCSNum, *CSI);
6638       }
6639       break;
6640     }
6641   }
6642
6643   // Get an ordered list of the machine basic blocks for the jump table.
6644   std::vector<MachineBasicBlock*> LPadList;
6645   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6646   LPadList.reserve(CallSiteNumToLPad.size());
6647   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6648     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6649     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6650            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6651       LPadList.push_back(*II);
6652       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6653     }
6654   }
6655
6656   assert(!LPadList.empty() &&
6657          "No landing pad destinations for the dispatch jump table!");
6658
6659   // Create the jump table and associated information.
6660   MachineJumpTableInfo *JTI =
6661     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6662   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6663   unsigned UId = AFI->createJumpTableUId();
6664   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6665
6666   // Create the MBBs for the dispatch code.
6667
6668   // Shove the dispatch's address into the return slot in the function context.
6669   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6670   DispatchBB->setIsLandingPad();
6671
6672   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6673   unsigned trap_opcode;
6674   if (Subtarget->isThumb())
6675     trap_opcode = ARM::tTRAP;
6676   else
6677     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6678
6679   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6680   DispatchBB->addSuccessor(TrapBB);
6681
6682   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6683   DispatchBB->addSuccessor(DispContBB);
6684
6685   // Insert and MBBs.
6686   MF->insert(MF->end(), DispatchBB);
6687   MF->insert(MF->end(), DispContBB);
6688   MF->insert(MF->end(), TrapBB);
6689
6690   // Insert code into the entry block that creates and registers the function
6691   // context.
6692   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6693
6694   MachineMemOperand *FIMMOLd =
6695     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6696                              MachineMemOperand::MOLoad |
6697                              MachineMemOperand::MOVolatile, 4, 4);
6698
6699   MachineInstrBuilder MIB;
6700   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6701
6702   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6703   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6704
6705   // Add a register mask with no preserved registers.  This results in all
6706   // registers being marked as clobbered.
6707   MIB.addRegMask(RI.getNoPreservedMask());
6708
6709   unsigned NumLPads = LPadList.size();
6710   if (Subtarget->isThumb2()) {
6711     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6712     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6713                    .addFrameIndex(FI)
6714                    .addImm(4)
6715                    .addMemOperand(FIMMOLd));
6716
6717     if (NumLPads < 256) {
6718       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6719                      .addReg(NewVReg1)
6720                      .addImm(LPadList.size()));
6721     } else {
6722       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6723       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6724                      .addImm(NumLPads & 0xFFFF));
6725
6726       unsigned VReg2 = VReg1;
6727       if ((NumLPads & 0xFFFF0000) != 0) {
6728         VReg2 = MRI->createVirtualRegister(TRC);
6729         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6730                        .addReg(VReg1)
6731                        .addImm(NumLPads >> 16));
6732       }
6733
6734       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6735                      .addReg(NewVReg1)
6736                      .addReg(VReg2));
6737     }
6738
6739     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6740       .addMBB(TrapBB)
6741       .addImm(ARMCC::HI)
6742       .addReg(ARM::CPSR);
6743
6744     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6745     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6746                    .addJumpTableIndex(MJTI)
6747                    .addImm(UId));
6748
6749     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6750     AddDefaultCC(
6751       AddDefaultPred(
6752         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6753         .addReg(NewVReg3, RegState::Kill)
6754         .addReg(NewVReg1)
6755         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6756
6757     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6758       .addReg(NewVReg4, RegState::Kill)
6759       .addReg(NewVReg1)
6760       .addJumpTableIndex(MJTI)
6761       .addImm(UId);
6762   } else if (Subtarget->isThumb()) {
6763     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6764     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6765                    .addFrameIndex(FI)
6766                    .addImm(1)
6767                    .addMemOperand(FIMMOLd));
6768
6769     if (NumLPads < 256) {
6770       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6771                      .addReg(NewVReg1)
6772                      .addImm(NumLPads));
6773     } else {
6774       MachineConstantPool *ConstantPool = MF->getConstantPool();
6775       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6776       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6777
6778       // MachineConstantPool wants an explicit alignment.
6779       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6780       if (Align == 0)
6781         Align = getDataLayout()->getTypeAllocSize(C->getType());
6782       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6783
6784       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6785       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6786                      .addReg(VReg1, RegState::Define)
6787                      .addConstantPoolIndex(Idx));
6788       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6789                      .addReg(NewVReg1)
6790                      .addReg(VReg1));
6791     }
6792
6793     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6794       .addMBB(TrapBB)
6795       .addImm(ARMCC::HI)
6796       .addReg(ARM::CPSR);
6797
6798     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6799     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6800                    .addReg(ARM::CPSR, RegState::Define)
6801                    .addReg(NewVReg1)
6802                    .addImm(2));
6803
6804     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6805     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6806                    .addJumpTableIndex(MJTI)
6807                    .addImm(UId));
6808
6809     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6810     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6811                    .addReg(ARM::CPSR, RegState::Define)
6812                    .addReg(NewVReg2, RegState::Kill)
6813                    .addReg(NewVReg3));
6814
6815     MachineMemOperand *JTMMOLd =
6816       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6817                                MachineMemOperand::MOLoad, 4, 4);
6818
6819     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6820     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6821                    .addReg(NewVReg4, RegState::Kill)
6822                    .addImm(0)
6823                    .addMemOperand(JTMMOLd));
6824
6825     unsigned NewVReg6 = NewVReg5;
6826     if (RelocM == Reloc::PIC_) {
6827       NewVReg6 = MRI->createVirtualRegister(TRC);
6828       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6829                      .addReg(ARM::CPSR, RegState::Define)
6830                      .addReg(NewVReg5, RegState::Kill)
6831                      .addReg(NewVReg3));
6832     }
6833
6834     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6835       .addReg(NewVReg6, RegState::Kill)
6836       .addJumpTableIndex(MJTI)
6837       .addImm(UId);
6838   } else {
6839     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6840     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6841                    .addFrameIndex(FI)
6842                    .addImm(4)
6843                    .addMemOperand(FIMMOLd));
6844
6845     if (NumLPads < 256) {
6846       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6847                      .addReg(NewVReg1)
6848                      .addImm(NumLPads));
6849     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6850       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6851       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6852                      .addImm(NumLPads & 0xFFFF));
6853
6854       unsigned VReg2 = VReg1;
6855       if ((NumLPads & 0xFFFF0000) != 0) {
6856         VReg2 = MRI->createVirtualRegister(TRC);
6857         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6858                        .addReg(VReg1)
6859                        .addImm(NumLPads >> 16));
6860       }
6861
6862       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6863                      .addReg(NewVReg1)
6864                      .addReg(VReg2));
6865     } else {
6866       MachineConstantPool *ConstantPool = MF->getConstantPool();
6867       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6868       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6869
6870       // MachineConstantPool wants an explicit alignment.
6871       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6872       if (Align == 0)
6873         Align = getDataLayout()->getTypeAllocSize(C->getType());
6874       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6875
6876       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6877       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6878                      .addReg(VReg1, RegState::Define)
6879                      .addConstantPoolIndex(Idx)
6880                      .addImm(0));
6881       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6882                      .addReg(NewVReg1)
6883                      .addReg(VReg1, RegState::Kill));
6884     }
6885
6886     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6887       .addMBB(TrapBB)
6888       .addImm(ARMCC::HI)
6889       .addReg(ARM::CPSR);
6890
6891     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6892     AddDefaultCC(
6893       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6894                      .addReg(NewVReg1)
6895                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6896     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6897     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6898                    .addJumpTableIndex(MJTI)
6899                    .addImm(UId));
6900
6901     MachineMemOperand *JTMMOLd =
6902       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6903                                MachineMemOperand::MOLoad, 4, 4);
6904     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6905     AddDefaultPred(
6906       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6907       .addReg(NewVReg3, RegState::Kill)
6908       .addReg(NewVReg4)
6909       .addImm(0)
6910       .addMemOperand(JTMMOLd));
6911
6912     if (RelocM == Reloc::PIC_) {
6913       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6914         .addReg(NewVReg5, RegState::Kill)
6915         .addReg(NewVReg4)
6916         .addJumpTableIndex(MJTI)
6917         .addImm(UId);
6918     } else {
6919       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6920         .addReg(NewVReg5, RegState::Kill)
6921         .addJumpTableIndex(MJTI)
6922         .addImm(UId);
6923     }
6924   }
6925
6926   // Add the jump table entries as successors to the MBB.
6927   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6928   for (std::vector<MachineBasicBlock*>::iterator
6929          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6930     MachineBasicBlock *CurMBB = *I;
6931     if (SeenMBBs.insert(CurMBB))
6932       DispContBB->addSuccessor(CurMBB);
6933   }
6934
6935   // N.B. the order the invoke BBs are processed in doesn't matter here.
6936   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6937   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6938   for (MachineBasicBlock *BB : InvokeBBs) {
6939
6940     // Remove the landing pad successor from the invoke block and replace it
6941     // with the new dispatch block.
6942     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6943                                                   BB->succ_end());
6944     while (!Successors.empty()) {
6945       MachineBasicBlock *SMBB = Successors.pop_back_val();
6946       if (SMBB->isLandingPad()) {
6947         BB->removeSuccessor(SMBB);
6948         MBBLPads.push_back(SMBB);
6949       }
6950     }
6951
6952     BB->addSuccessor(DispatchBB);
6953
6954     // Find the invoke call and mark all of the callee-saved registers as
6955     // 'implicit defined' so that they're spilled. This prevents code from
6956     // moving instructions to before the EH block, where they will never be
6957     // executed.
6958     for (MachineBasicBlock::reverse_iterator
6959            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6960       if (!II->isCall()) continue;
6961
6962       DenseMap<unsigned, bool> DefRegs;
6963       for (MachineInstr::mop_iterator
6964              OI = II->operands_begin(), OE = II->operands_end();
6965            OI != OE; ++OI) {
6966         if (!OI->isReg()) continue;
6967         DefRegs[OI->getReg()] = true;
6968       }
6969
6970       MachineInstrBuilder MIB(*MF, &*II);
6971
6972       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6973         unsigned Reg = SavedRegs[i];
6974         if (Subtarget->isThumb2() &&
6975             !ARM::tGPRRegClass.contains(Reg) &&
6976             !ARM::hGPRRegClass.contains(Reg))
6977           continue;
6978         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6979           continue;
6980         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6981           continue;
6982         if (!DefRegs[Reg])
6983           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6984       }
6985
6986       break;
6987     }
6988   }
6989
6990   // Mark all former landing pads as non-landing pads. The dispatch is the only
6991   // landing pad now.
6992   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6993          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6994     (*I)->setIsLandingPad(false);
6995
6996   // The instruction is gone now.
6997   MI->eraseFromParent();
6998
6999   return MBB;
7000 }
7001
7002 static
7003 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7004   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7005        E = MBB->succ_end(); I != E; ++I)
7006     if (*I != Succ)
7007       return *I;
7008   llvm_unreachable("Expecting a BB with two successors!");
7009 }
7010
7011 /// Return the load opcode for a given load size. If load size >= 8,
7012 /// neon opcode will be returned.
7013 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7014   if (LdSize >= 8)
7015     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7016                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7017   if (IsThumb1)
7018     return LdSize == 4 ? ARM::tLDRi
7019                        : LdSize == 2 ? ARM::tLDRHi
7020                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7021   if (IsThumb2)
7022     return LdSize == 4 ? ARM::t2LDR_POST
7023                        : LdSize == 2 ? ARM::t2LDRH_POST
7024                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7025   return LdSize == 4 ? ARM::LDR_POST_IMM
7026                      : LdSize == 2 ? ARM::LDRH_POST
7027                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7028 }
7029
7030 /// Return the store opcode for a given store size. If store size >= 8,
7031 /// neon opcode will be returned.
7032 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7033   if (StSize >= 8)
7034     return StSize == 16 ? ARM::VST1q32wb_fixed
7035                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7036   if (IsThumb1)
7037     return StSize == 4 ? ARM::tSTRi
7038                        : StSize == 2 ? ARM::tSTRHi
7039                                      : StSize == 1 ? ARM::tSTRBi : 0;
7040   if (IsThumb2)
7041     return StSize == 4 ? ARM::t2STR_POST
7042                        : StSize == 2 ? ARM::t2STRH_POST
7043                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7044   return StSize == 4 ? ARM::STR_POST_IMM
7045                      : StSize == 2 ? ARM::STRH_POST
7046                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7047 }
7048
7049 /// Emit a post-increment load operation with given size. The instructions
7050 /// will be added to BB at Pos.
7051 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7052                        const TargetInstrInfo *TII, DebugLoc dl,
7053                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7054                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7055   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7056   assert(LdOpc != 0 && "Should have a load opcode");
7057   if (LdSize >= 8) {
7058     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7059                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7060                        .addImm(0));
7061   } else if (IsThumb1) {
7062     // load + update AddrIn
7063     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7064                        .addReg(AddrIn).addImm(0));
7065     MachineInstrBuilder MIB =
7066         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7067     MIB = AddDefaultT1CC(MIB);
7068     MIB.addReg(AddrIn).addImm(LdSize);
7069     AddDefaultPred(MIB);
7070   } else if (IsThumb2) {
7071     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7072                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7073                        .addImm(LdSize));
7074   } else { // arm
7075     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7076                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7077                        .addReg(0).addImm(LdSize));
7078   }
7079 }
7080
7081 /// Emit a post-increment store operation with given size. The instructions
7082 /// will be added to BB at Pos.
7083 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7084                        const TargetInstrInfo *TII, DebugLoc dl,
7085                        unsigned StSize, unsigned Data, unsigned AddrIn,
7086                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7087   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7088   assert(StOpc != 0 && "Should have a store opcode");
7089   if (StSize >= 8) {
7090     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7091                        .addReg(AddrIn).addImm(0).addReg(Data));
7092   } else if (IsThumb1) {
7093     // store + update AddrIn
7094     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7095                        .addReg(AddrIn).addImm(0));
7096     MachineInstrBuilder MIB =
7097         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7098     MIB = AddDefaultT1CC(MIB);
7099     MIB.addReg(AddrIn).addImm(StSize);
7100     AddDefaultPred(MIB);
7101   } else if (IsThumb2) {
7102     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7103                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7104   } else { // arm
7105     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7106                        .addReg(Data).addReg(AddrIn).addReg(0)
7107                        .addImm(StSize));
7108   }
7109 }
7110
7111 MachineBasicBlock *
7112 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7113                                    MachineBasicBlock *BB) const {
7114   // This pseudo instruction has 3 operands: dst, src, size
7115   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7116   // Otherwise, we will generate unrolled scalar copies.
7117   const TargetInstrInfo *TII =
7118       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7119   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7120   MachineFunction::iterator It = BB;
7121   ++It;
7122
7123   unsigned dest = MI->getOperand(0).getReg();
7124   unsigned src = MI->getOperand(1).getReg();
7125   unsigned SizeVal = MI->getOperand(2).getImm();
7126   unsigned Align = MI->getOperand(3).getImm();
7127   DebugLoc dl = MI->getDebugLoc();
7128
7129   MachineFunction *MF = BB->getParent();
7130   MachineRegisterInfo &MRI = MF->getRegInfo();
7131   unsigned UnitSize = 0;
7132   const TargetRegisterClass *TRC = nullptr;
7133   const TargetRegisterClass *VecTRC = nullptr;
7134
7135   bool IsThumb1 = Subtarget->isThumb1Only();
7136   bool IsThumb2 = Subtarget->isThumb2();
7137
7138   if (Align & 1) {
7139     UnitSize = 1;
7140   } else if (Align & 2) {
7141     UnitSize = 2;
7142   } else {
7143     // Check whether we can use NEON instructions.
7144     if (!MF->getFunction()->getAttributes().
7145           hasAttribute(AttributeSet::FunctionIndex,
7146                        Attribute::NoImplicitFloat) &&
7147         Subtarget->hasNEON()) {
7148       if ((Align % 16 == 0) && SizeVal >= 16)
7149         UnitSize = 16;
7150       else if ((Align % 8 == 0) && SizeVal >= 8)
7151         UnitSize = 8;
7152     }
7153     // Can't use NEON instructions.
7154     if (UnitSize == 0)
7155       UnitSize = 4;
7156   }
7157
7158   // Select the correct opcode and register class for unit size load/store
7159   bool IsNeon = UnitSize >= 8;
7160   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7161                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7162   if (IsNeon)
7163     VecTRC = UnitSize == 16
7164                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7165                  : UnitSize == 8
7166                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7167                        : nullptr;
7168
7169   unsigned BytesLeft = SizeVal % UnitSize;
7170   unsigned LoopSize = SizeVal - BytesLeft;
7171
7172   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7173     // Use LDR and STR to copy.
7174     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7175     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7176     unsigned srcIn = src;
7177     unsigned destIn = dest;
7178     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7179       unsigned srcOut = MRI.createVirtualRegister(TRC);
7180       unsigned destOut = MRI.createVirtualRegister(TRC);
7181       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7182       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7183                  IsThumb1, IsThumb2);
7184       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7185                  IsThumb1, IsThumb2);
7186       srcIn = srcOut;
7187       destIn = destOut;
7188     }
7189
7190     // Handle the leftover bytes with LDRB and STRB.
7191     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7192     // [destOut] = STRB_POST(scratch, destIn, 1)
7193     for (unsigned i = 0; i < BytesLeft; i++) {
7194       unsigned srcOut = MRI.createVirtualRegister(TRC);
7195       unsigned destOut = MRI.createVirtualRegister(TRC);
7196       unsigned scratch = MRI.createVirtualRegister(TRC);
7197       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7198                  IsThumb1, IsThumb2);
7199       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7200                  IsThumb1, IsThumb2);
7201       srcIn = srcOut;
7202       destIn = destOut;
7203     }
7204     MI->eraseFromParent();   // The instruction is gone now.
7205     return BB;
7206   }
7207
7208   // Expand the pseudo op to a loop.
7209   // thisMBB:
7210   //   ...
7211   //   movw varEnd, # --> with thumb2
7212   //   movt varEnd, #
7213   //   ldrcp varEnd, idx --> without thumb2
7214   //   fallthrough --> loopMBB
7215   // loopMBB:
7216   //   PHI varPhi, varEnd, varLoop
7217   //   PHI srcPhi, src, srcLoop
7218   //   PHI destPhi, dst, destLoop
7219   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7220   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7221   //   subs varLoop, varPhi, #UnitSize
7222   //   bne loopMBB
7223   //   fallthrough --> exitMBB
7224   // exitMBB:
7225   //   epilogue to handle left-over bytes
7226   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7227   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7228   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7229   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7230   MF->insert(It, loopMBB);
7231   MF->insert(It, exitMBB);
7232
7233   // Transfer the remainder of BB and its successor edges to exitMBB.
7234   exitMBB->splice(exitMBB->begin(), BB,
7235                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7236   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7237
7238   // Load an immediate to varEnd.
7239   unsigned varEnd = MRI.createVirtualRegister(TRC);
7240   if (IsThumb2) {
7241     unsigned Vtmp = varEnd;
7242     if ((LoopSize & 0xFFFF0000) != 0)
7243       Vtmp = MRI.createVirtualRegister(TRC);
7244     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7245                        .addImm(LoopSize & 0xFFFF));
7246
7247     if ((LoopSize & 0xFFFF0000) != 0)
7248       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7249                          .addReg(Vtmp).addImm(LoopSize >> 16));
7250   } else {
7251     MachineConstantPool *ConstantPool = MF->getConstantPool();
7252     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7253     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7254
7255     // MachineConstantPool wants an explicit alignment.
7256     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7257     if (Align == 0)
7258       Align = getDataLayout()->getTypeAllocSize(C->getType());
7259     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7260
7261     if (IsThumb1)
7262       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7263           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7264     else
7265       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7266           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7267   }
7268   BB->addSuccessor(loopMBB);
7269
7270   // Generate the loop body:
7271   //   varPhi = PHI(varLoop, varEnd)
7272   //   srcPhi = PHI(srcLoop, src)
7273   //   destPhi = PHI(destLoop, dst)
7274   MachineBasicBlock *entryBB = BB;
7275   BB = loopMBB;
7276   unsigned varLoop = MRI.createVirtualRegister(TRC);
7277   unsigned varPhi = MRI.createVirtualRegister(TRC);
7278   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7279   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7280   unsigned destLoop = MRI.createVirtualRegister(TRC);
7281   unsigned destPhi = MRI.createVirtualRegister(TRC);
7282
7283   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7284     .addReg(varLoop).addMBB(loopMBB)
7285     .addReg(varEnd).addMBB(entryBB);
7286   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7287     .addReg(srcLoop).addMBB(loopMBB)
7288     .addReg(src).addMBB(entryBB);
7289   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7290     .addReg(destLoop).addMBB(loopMBB)
7291     .addReg(dest).addMBB(entryBB);
7292
7293   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7294   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7295   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7296   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7297              IsThumb1, IsThumb2);
7298   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7299              IsThumb1, IsThumb2);
7300
7301   // Decrement loop variable by UnitSize.
7302   if (IsThumb1) {
7303     MachineInstrBuilder MIB =
7304         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7305     MIB = AddDefaultT1CC(MIB);
7306     MIB.addReg(varPhi).addImm(UnitSize);
7307     AddDefaultPred(MIB);
7308   } else {
7309     MachineInstrBuilder MIB =
7310         BuildMI(*BB, BB->end(), dl,
7311                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7312     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7313     MIB->getOperand(5).setReg(ARM::CPSR);
7314     MIB->getOperand(5).setIsDef(true);
7315   }
7316   BuildMI(*BB, BB->end(), dl,
7317           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7318       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7319
7320   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7321   BB->addSuccessor(loopMBB);
7322   BB->addSuccessor(exitMBB);
7323
7324   // Add epilogue to handle BytesLeft.
7325   BB = exitMBB;
7326   MachineInstr *StartOfExit = exitMBB->begin();
7327
7328   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7329   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7330   unsigned srcIn = srcLoop;
7331   unsigned destIn = destLoop;
7332   for (unsigned i = 0; i < BytesLeft; i++) {
7333     unsigned srcOut = MRI.createVirtualRegister(TRC);
7334     unsigned destOut = MRI.createVirtualRegister(TRC);
7335     unsigned scratch = MRI.createVirtualRegister(TRC);
7336     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7337                IsThumb1, IsThumb2);
7338     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7339                IsThumb1, IsThumb2);
7340     srcIn = srcOut;
7341     destIn = destOut;
7342   }
7343
7344   MI->eraseFromParent();   // The instruction is gone now.
7345   return BB;
7346 }
7347
7348 MachineBasicBlock *
7349 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7350                                        MachineBasicBlock *MBB) const {
7351   const TargetMachine &TM = getTargetMachine();
7352   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7353   DebugLoc DL = MI->getDebugLoc();
7354
7355   assert(Subtarget->isTargetWindows() &&
7356          "__chkstk is only supported on Windows");
7357   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7358
7359   // __chkstk takes the number of words to allocate on the stack in R4, and
7360   // returns the stack adjustment in number of bytes in R4.  This will not
7361   // clober any other registers (other than the obvious lr).
7362   //
7363   // Although, technically, IP should be considered a register which may be
7364   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7365   // thumb-2 environment, so there is no interworking required.  As a result, we
7366   // do not expect a veneer to be emitted by the linker, clobbering IP.
7367   //
7368   // Each module receives its own copy of __chkstk, so no import thunk is
7369   // required, again, ensuring that IP is not clobbered.
7370   //
7371   // Finally, although some linkers may theoretically provide a trampoline for
7372   // out of range calls (which is quite common due to a 32M range limitation of
7373   // branches for Thumb), we can generate the long-call version via
7374   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7375   // IP.
7376
7377   switch (TM.getCodeModel()) {
7378   case CodeModel::Small:
7379   case CodeModel::Medium:
7380   case CodeModel::Default:
7381   case CodeModel::Kernel:
7382     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7383       .addImm((unsigned)ARMCC::AL).addReg(0)
7384       .addExternalSymbol("__chkstk")
7385       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7386       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7387       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7388     break;
7389   case CodeModel::Large:
7390   case CodeModel::JITDefault: {
7391     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7392     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7393
7394     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7395       .addExternalSymbol("__chkstk");
7396     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7397       .addImm((unsigned)ARMCC::AL).addReg(0)
7398       .addReg(Reg, RegState::Kill)
7399       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7400       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7401       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7402     break;
7403   }
7404   }
7405
7406   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7407                                       ARM::SP)
7408                               .addReg(ARM::SP).addReg(ARM::R4)));
7409
7410   MI->eraseFromParent();
7411   return MBB;
7412 }
7413
7414 MachineBasicBlock *
7415 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7416                                                MachineBasicBlock *BB) const {
7417   const TargetInstrInfo *TII =
7418       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7419   DebugLoc dl = MI->getDebugLoc();
7420   bool isThumb2 = Subtarget->isThumb2();
7421   switch (MI->getOpcode()) {
7422   default: {
7423     MI->dump();
7424     llvm_unreachable("Unexpected instr type to insert");
7425   }
7426   // The Thumb2 pre-indexed stores have the same MI operands, they just
7427   // define them differently in the .td files from the isel patterns, so
7428   // they need pseudos.
7429   case ARM::t2STR_preidx:
7430     MI->setDesc(TII->get(ARM::t2STR_PRE));
7431     return BB;
7432   case ARM::t2STRB_preidx:
7433     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7434     return BB;
7435   case ARM::t2STRH_preidx:
7436     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7437     return BB;
7438
7439   case ARM::STRi_preidx:
7440   case ARM::STRBi_preidx: {
7441     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7442       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7443     // Decode the offset.
7444     unsigned Offset = MI->getOperand(4).getImm();
7445     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7446     Offset = ARM_AM::getAM2Offset(Offset);
7447     if (isSub)
7448       Offset = -Offset;
7449
7450     MachineMemOperand *MMO = *MI->memoperands_begin();
7451     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7452       .addOperand(MI->getOperand(0))  // Rn_wb
7453       .addOperand(MI->getOperand(1))  // Rt
7454       .addOperand(MI->getOperand(2))  // Rn
7455       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7456       .addOperand(MI->getOperand(5))  // pred
7457       .addOperand(MI->getOperand(6))
7458       .addMemOperand(MMO);
7459     MI->eraseFromParent();
7460     return BB;
7461   }
7462   case ARM::STRr_preidx:
7463   case ARM::STRBr_preidx:
7464   case ARM::STRH_preidx: {
7465     unsigned NewOpc;
7466     switch (MI->getOpcode()) {
7467     default: llvm_unreachable("unexpected opcode!");
7468     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7469     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7470     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7471     }
7472     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7473     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7474       MIB.addOperand(MI->getOperand(i));
7475     MI->eraseFromParent();
7476     return BB;
7477   }
7478
7479   case ARM::tMOVCCr_pseudo: {
7480     // To "insert" a SELECT_CC instruction, we actually have to insert the
7481     // diamond control-flow pattern.  The incoming instruction knows the
7482     // destination vreg to set, the condition code register to branch on, the
7483     // true/false values to select between, and a branch opcode to use.
7484     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7485     MachineFunction::iterator It = BB;
7486     ++It;
7487
7488     //  thisMBB:
7489     //  ...
7490     //   TrueVal = ...
7491     //   cmpTY ccX, r1, r2
7492     //   bCC copy1MBB
7493     //   fallthrough --> copy0MBB
7494     MachineBasicBlock *thisMBB  = BB;
7495     MachineFunction *F = BB->getParent();
7496     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7497     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7498     F->insert(It, copy0MBB);
7499     F->insert(It, sinkMBB);
7500
7501     // Transfer the remainder of BB and its successor edges to sinkMBB.
7502     sinkMBB->splice(sinkMBB->begin(), BB,
7503                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7504     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7505
7506     BB->addSuccessor(copy0MBB);
7507     BB->addSuccessor(sinkMBB);
7508
7509     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7510       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7511
7512     //  copy0MBB:
7513     //   %FalseValue = ...
7514     //   # fallthrough to sinkMBB
7515     BB = copy0MBB;
7516
7517     // Update machine-CFG edges
7518     BB->addSuccessor(sinkMBB);
7519
7520     //  sinkMBB:
7521     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7522     //  ...
7523     BB = sinkMBB;
7524     BuildMI(*BB, BB->begin(), dl,
7525             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7526       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7527       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7528
7529     MI->eraseFromParent();   // The pseudo instruction is gone now.
7530     return BB;
7531   }
7532
7533   case ARM::BCCi64:
7534   case ARM::BCCZi64: {
7535     // If there is an unconditional branch to the other successor, remove it.
7536     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7537
7538     // Compare both parts that make up the double comparison separately for
7539     // equality.
7540     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7541
7542     unsigned LHS1 = MI->getOperand(1).getReg();
7543     unsigned LHS2 = MI->getOperand(2).getReg();
7544     if (RHSisZero) {
7545       AddDefaultPred(BuildMI(BB, dl,
7546                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7547                      .addReg(LHS1).addImm(0));
7548       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7549         .addReg(LHS2).addImm(0)
7550         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7551     } else {
7552       unsigned RHS1 = MI->getOperand(3).getReg();
7553       unsigned RHS2 = MI->getOperand(4).getReg();
7554       AddDefaultPred(BuildMI(BB, dl,
7555                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7556                      .addReg(LHS1).addReg(RHS1));
7557       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7558         .addReg(LHS2).addReg(RHS2)
7559         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7560     }
7561
7562     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7563     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7564     if (MI->getOperand(0).getImm() == ARMCC::NE)
7565       std::swap(destMBB, exitMBB);
7566
7567     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7568       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7569     if (isThumb2)
7570       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7571     else
7572       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7573
7574     MI->eraseFromParent();   // The pseudo instruction is gone now.
7575     return BB;
7576   }
7577
7578   case ARM::Int_eh_sjlj_setjmp:
7579   case ARM::Int_eh_sjlj_setjmp_nofp:
7580   case ARM::tInt_eh_sjlj_setjmp:
7581   case ARM::t2Int_eh_sjlj_setjmp:
7582   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7583     EmitSjLjDispatchBlock(MI, BB);
7584     return BB;
7585
7586   case ARM::ABS:
7587   case ARM::t2ABS: {
7588     // To insert an ABS instruction, we have to insert the
7589     // diamond control-flow pattern.  The incoming instruction knows the
7590     // source vreg to test against 0, the destination vreg to set,
7591     // the condition code register to branch on, the
7592     // true/false values to select between, and a branch opcode to use.
7593     // It transforms
7594     //     V1 = ABS V0
7595     // into
7596     //     V2 = MOVS V0
7597     //     BCC                      (branch to SinkBB if V0 >= 0)
7598     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7599     //     SinkBB: V1 = PHI(V2, V3)
7600     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7601     MachineFunction::iterator BBI = BB;
7602     ++BBI;
7603     MachineFunction *Fn = BB->getParent();
7604     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7605     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7606     Fn->insert(BBI, RSBBB);
7607     Fn->insert(BBI, SinkBB);
7608
7609     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7610     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7611     bool isThumb2 = Subtarget->isThumb2();
7612     MachineRegisterInfo &MRI = Fn->getRegInfo();
7613     // In Thumb mode S must not be specified if source register is the SP or
7614     // PC and if destination register is the SP, so restrict register class
7615     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7616       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7617       (const TargetRegisterClass*)&ARM::GPRRegClass);
7618
7619     // Transfer the remainder of BB and its successor edges to sinkMBB.
7620     SinkBB->splice(SinkBB->begin(), BB,
7621                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7622     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7623
7624     BB->addSuccessor(RSBBB);
7625     BB->addSuccessor(SinkBB);
7626
7627     // fall through to SinkMBB
7628     RSBBB->addSuccessor(SinkBB);
7629
7630     // insert a cmp at the end of BB
7631     AddDefaultPred(BuildMI(BB, dl,
7632                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7633                    .addReg(ABSSrcReg).addImm(0));
7634
7635     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7636     BuildMI(BB, dl,
7637       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7638       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7639
7640     // insert rsbri in RSBBB
7641     // Note: BCC and rsbri will be converted into predicated rsbmi
7642     // by if-conversion pass
7643     BuildMI(*RSBBB, RSBBB->begin(), dl,
7644       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7645       .addReg(ABSSrcReg, RegState::Kill)
7646       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7647
7648     // insert PHI in SinkBB,
7649     // reuse ABSDstReg to not change uses of ABS instruction
7650     BuildMI(*SinkBB, SinkBB->begin(), dl,
7651       TII->get(ARM::PHI), ABSDstReg)
7652       .addReg(NewRsbDstReg).addMBB(RSBBB)
7653       .addReg(ABSSrcReg).addMBB(BB);
7654
7655     // remove ABS instruction
7656     MI->eraseFromParent();
7657
7658     // return last added BB
7659     return SinkBB;
7660   }
7661   case ARM::COPY_STRUCT_BYVAL_I32:
7662     ++NumLoopByVals;
7663     return EmitStructByval(MI, BB);
7664   case ARM::WIN__CHKSTK:
7665     return EmitLowered__chkstk(MI, BB);
7666   }
7667 }
7668
7669 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7670                                                       SDNode *Node) const {
7671   if (!MI->hasPostISelHook()) {
7672     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7673            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7674     return;
7675   }
7676
7677   const MCInstrDesc *MCID = &MI->getDesc();
7678   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7679   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7680   // operand is still set to noreg. If needed, set the optional operand's
7681   // register to CPSR, and remove the redundant implicit def.
7682   //
7683   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7684
7685   // Rename pseudo opcodes.
7686   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7687   if (NewOpc) {
7688     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7689         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7690     MCID = &TII->get(NewOpc);
7691
7692     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7693            "converted opcode should be the same except for cc_out");
7694
7695     MI->setDesc(*MCID);
7696
7697     // Add the optional cc_out operand
7698     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7699   }
7700   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7701
7702   // Any ARM instruction that sets the 's' bit should specify an optional
7703   // "cc_out" operand in the last operand position.
7704   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7705     assert(!NewOpc && "Optional cc_out operand required");
7706     return;
7707   }
7708   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7709   // since we already have an optional CPSR def.
7710   bool definesCPSR = false;
7711   bool deadCPSR = false;
7712   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7713        i != e; ++i) {
7714     const MachineOperand &MO = MI->getOperand(i);
7715     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7716       definesCPSR = true;
7717       if (MO.isDead())
7718         deadCPSR = true;
7719       MI->RemoveOperand(i);
7720       break;
7721     }
7722   }
7723   if (!definesCPSR) {
7724     assert(!NewOpc && "Optional cc_out operand required");
7725     return;
7726   }
7727   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7728   if (deadCPSR) {
7729     assert(!MI->getOperand(ccOutIdx).getReg() &&
7730            "expect uninitialized optional cc_out operand");
7731     return;
7732   }
7733
7734   // If this instruction was defined with an optional CPSR def and its dag node
7735   // had a live implicit CPSR def, then activate the optional CPSR def.
7736   MachineOperand &MO = MI->getOperand(ccOutIdx);
7737   MO.setReg(ARM::CPSR);
7738   MO.setIsDef(true);
7739 }
7740
7741 //===----------------------------------------------------------------------===//
7742 //                           ARM Optimization Hooks
7743 //===----------------------------------------------------------------------===//
7744
7745 // Helper function that checks if N is a null or all ones constant.
7746 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7747   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7748   if (!C)
7749     return false;
7750   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7751 }
7752
7753 // Return true if N is conditionally 0 or all ones.
7754 // Detects these expressions where cc is an i1 value:
7755 //
7756 //   (select cc 0, y)   [AllOnes=0]
7757 //   (select cc y, 0)   [AllOnes=0]
7758 //   (zext cc)          [AllOnes=0]
7759 //   (sext cc)          [AllOnes=0/1]
7760 //   (select cc -1, y)  [AllOnes=1]
7761 //   (select cc y, -1)  [AllOnes=1]
7762 //
7763 // Invert is set when N is the null/all ones constant when CC is false.
7764 // OtherOp is set to the alternative value of N.
7765 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7766                                        SDValue &CC, bool &Invert,
7767                                        SDValue &OtherOp,
7768                                        SelectionDAG &DAG) {
7769   switch (N->getOpcode()) {
7770   default: return false;
7771   case ISD::SELECT: {
7772     CC = N->getOperand(0);
7773     SDValue N1 = N->getOperand(1);
7774     SDValue N2 = N->getOperand(2);
7775     if (isZeroOrAllOnes(N1, AllOnes)) {
7776       Invert = false;
7777       OtherOp = N2;
7778       return true;
7779     }
7780     if (isZeroOrAllOnes(N2, AllOnes)) {
7781       Invert = true;
7782       OtherOp = N1;
7783       return true;
7784     }
7785     return false;
7786   }
7787   case ISD::ZERO_EXTEND:
7788     // (zext cc) can never be the all ones value.
7789     if (AllOnes)
7790       return false;
7791     // Fall through.
7792   case ISD::SIGN_EXTEND: {
7793     EVT VT = N->getValueType(0);
7794     CC = N->getOperand(0);
7795     if (CC.getValueType() != MVT::i1)
7796       return false;
7797     Invert = !AllOnes;
7798     if (AllOnes)
7799       // When looking for an AllOnes constant, N is an sext, and the 'other'
7800       // value is 0.
7801       OtherOp = DAG.getConstant(0, VT);
7802     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7803       // When looking for a 0 constant, N can be zext or sext.
7804       OtherOp = DAG.getConstant(1, VT);
7805     else
7806       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7807     return true;
7808   }
7809   }
7810 }
7811
7812 // Combine a constant select operand into its use:
7813 //
7814 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7815 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7816 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7817 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7818 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7819 //
7820 // The transform is rejected if the select doesn't have a constant operand that
7821 // is null, or all ones when AllOnes is set.
7822 //
7823 // Also recognize sext/zext from i1:
7824 //
7825 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7826 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7827 //
7828 // These transformations eventually create predicated instructions.
7829 //
7830 // @param N       The node to transform.
7831 // @param Slct    The N operand that is a select.
7832 // @param OtherOp The other N operand (x above).
7833 // @param DCI     Context.
7834 // @param AllOnes Require the select constant to be all ones instead of null.
7835 // @returns The new node, or SDValue() on failure.
7836 static
7837 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7838                             TargetLowering::DAGCombinerInfo &DCI,
7839                             bool AllOnes = false) {
7840   SelectionDAG &DAG = DCI.DAG;
7841   EVT VT = N->getValueType(0);
7842   SDValue NonConstantVal;
7843   SDValue CCOp;
7844   bool SwapSelectOps;
7845   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7846                                   NonConstantVal, DAG))
7847     return SDValue();
7848
7849   // Slct is now know to be the desired identity constant when CC is true.
7850   SDValue TrueVal = OtherOp;
7851   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7852                                  OtherOp, NonConstantVal);
7853   // Unless SwapSelectOps says CC should be false.
7854   if (SwapSelectOps)
7855     std::swap(TrueVal, FalseVal);
7856
7857   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7858                      CCOp, TrueVal, FalseVal);
7859 }
7860
7861 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7862 static
7863 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7864                                        TargetLowering::DAGCombinerInfo &DCI) {
7865   SDValue N0 = N->getOperand(0);
7866   SDValue N1 = N->getOperand(1);
7867   if (N0.getNode()->hasOneUse()) {
7868     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7869     if (Result.getNode())
7870       return Result;
7871   }
7872   if (N1.getNode()->hasOneUse()) {
7873     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7874     if (Result.getNode())
7875       return Result;
7876   }
7877   return SDValue();
7878 }
7879
7880 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7881 // (only after legalization).
7882 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7883                                  TargetLowering::DAGCombinerInfo &DCI,
7884                                  const ARMSubtarget *Subtarget) {
7885
7886   // Only perform optimization if after legalize, and if NEON is available. We
7887   // also expected both operands to be BUILD_VECTORs.
7888   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7889       || N0.getOpcode() != ISD::BUILD_VECTOR
7890       || N1.getOpcode() != ISD::BUILD_VECTOR)
7891     return SDValue();
7892
7893   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7894   EVT VT = N->getValueType(0);
7895   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7896     return SDValue();
7897
7898   // Check that the vector operands are of the right form.
7899   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7900   // operands, where N is the size of the formed vector.
7901   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7902   // index such that we have a pair wise add pattern.
7903
7904   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7905   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7906     return SDValue();
7907   SDValue Vec = N0->getOperand(0)->getOperand(0);
7908   SDNode *V = Vec.getNode();
7909   unsigned nextIndex = 0;
7910
7911   // For each operands to the ADD which are BUILD_VECTORs,
7912   // check to see if each of their operands are an EXTRACT_VECTOR with
7913   // the same vector and appropriate index.
7914   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7915     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7916         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7917
7918       SDValue ExtVec0 = N0->getOperand(i);
7919       SDValue ExtVec1 = N1->getOperand(i);
7920
7921       // First operand is the vector, verify its the same.
7922       if (V != ExtVec0->getOperand(0).getNode() ||
7923           V != ExtVec1->getOperand(0).getNode())
7924         return SDValue();
7925
7926       // Second is the constant, verify its correct.
7927       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7928       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7929
7930       // For the constant, we want to see all the even or all the odd.
7931       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7932           || C1->getZExtValue() != nextIndex+1)
7933         return SDValue();
7934
7935       // Increment index.
7936       nextIndex+=2;
7937     } else
7938       return SDValue();
7939   }
7940
7941   // Create VPADDL node.
7942   SelectionDAG &DAG = DCI.DAG;
7943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7944
7945   // Build operand list.
7946   SmallVector<SDValue, 8> Ops;
7947   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7948                                 TLI.getPointerTy()));
7949
7950   // Input is the vector.
7951   Ops.push_back(Vec);
7952
7953   // Get widened type and narrowed type.
7954   MVT widenType;
7955   unsigned numElem = VT.getVectorNumElements();
7956   
7957   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7958   switch (inputLaneType.getSimpleVT().SimpleTy) {
7959     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7960     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7961     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7962     default:
7963       llvm_unreachable("Invalid vector element type for padd optimization.");
7964   }
7965
7966   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7967   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7968   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7969 }
7970
7971 static SDValue findMUL_LOHI(SDValue V) {
7972   if (V->getOpcode() == ISD::UMUL_LOHI ||
7973       V->getOpcode() == ISD::SMUL_LOHI)
7974     return V;
7975   return SDValue();
7976 }
7977
7978 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7979                                      TargetLowering::DAGCombinerInfo &DCI,
7980                                      const ARMSubtarget *Subtarget) {
7981
7982   if (Subtarget->isThumb1Only()) return SDValue();
7983
7984   // Only perform the checks after legalize when the pattern is available.
7985   if (DCI.isBeforeLegalize()) return SDValue();
7986
7987   // Look for multiply add opportunities.
7988   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7989   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7990   // a glue link from the first add to the second add.
7991   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7992   // a S/UMLAL instruction.
7993   //          loAdd   UMUL_LOHI
7994   //            \    / :lo    \ :hi
7995   //             \  /          \          [no multiline comment]
7996   //              ADDC         |  hiAdd
7997   //                 \ :glue  /  /
7998   //                  \      /  /
7999   //                    ADDE
8000   //
8001   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8002   SDValue AddcOp0 = AddcNode->getOperand(0);
8003   SDValue AddcOp1 = AddcNode->getOperand(1);
8004
8005   // Check if the two operands are from the same mul_lohi node.
8006   if (AddcOp0.getNode() == AddcOp1.getNode())
8007     return SDValue();
8008
8009   assert(AddcNode->getNumValues() == 2 &&
8010          AddcNode->getValueType(0) == MVT::i32 &&
8011          "Expect ADDC with two result values. First: i32");
8012
8013   // Check that we have a glued ADDC node.
8014   if (AddcNode->getValueType(1) != MVT::Glue)
8015     return SDValue();
8016
8017   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8018   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8019       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8020       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8021       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8022     return SDValue();
8023
8024   // Look for the glued ADDE.
8025   SDNode* AddeNode = AddcNode->getGluedUser();
8026   if (!AddeNode)
8027     return SDValue();
8028
8029   // Make sure it is really an ADDE.
8030   if (AddeNode->getOpcode() != ISD::ADDE)
8031     return SDValue();
8032
8033   assert(AddeNode->getNumOperands() == 3 &&
8034          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8035          "ADDE node has the wrong inputs");
8036
8037   // Check for the triangle shape.
8038   SDValue AddeOp0 = AddeNode->getOperand(0);
8039   SDValue AddeOp1 = AddeNode->getOperand(1);
8040
8041   // Make sure that the ADDE operands are not coming from the same node.
8042   if (AddeOp0.getNode() == AddeOp1.getNode())
8043     return SDValue();
8044
8045   // Find the MUL_LOHI node walking up ADDE's operands.
8046   bool IsLeftOperandMUL = false;
8047   SDValue MULOp = findMUL_LOHI(AddeOp0);
8048   if (MULOp == SDValue())
8049    MULOp = findMUL_LOHI(AddeOp1);
8050   else
8051     IsLeftOperandMUL = true;
8052   if (MULOp == SDValue())
8053      return SDValue();
8054
8055   // Figure out the right opcode.
8056   unsigned Opc = MULOp->getOpcode();
8057   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8058
8059   // Figure out the high and low input values to the MLAL node.
8060   SDValue* HiMul = &MULOp;
8061   SDValue* HiAdd = nullptr;
8062   SDValue* LoMul = nullptr;
8063   SDValue* LowAdd = nullptr;
8064
8065   if (IsLeftOperandMUL)
8066     HiAdd = &AddeOp1;
8067   else
8068     HiAdd = &AddeOp0;
8069
8070
8071   if (AddcOp0->getOpcode() == Opc) {
8072     LoMul = &AddcOp0;
8073     LowAdd = &AddcOp1;
8074   }
8075   if (AddcOp1->getOpcode() == Opc) {
8076     LoMul = &AddcOp1;
8077     LowAdd = &AddcOp0;
8078   }
8079
8080   if (!LoMul)
8081     return SDValue();
8082
8083   if (LoMul->getNode() != HiMul->getNode())
8084     return SDValue();
8085
8086   // Create the merged node.
8087   SelectionDAG &DAG = DCI.DAG;
8088
8089   // Build operand list.
8090   SmallVector<SDValue, 8> Ops;
8091   Ops.push_back(LoMul->getOperand(0));
8092   Ops.push_back(LoMul->getOperand(1));
8093   Ops.push_back(*LowAdd);
8094   Ops.push_back(*HiAdd);
8095
8096   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8097                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8098
8099   // Replace the ADDs' nodes uses by the MLA node's values.
8100   SDValue HiMLALResult(MLALNode.getNode(), 1);
8101   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8102
8103   SDValue LoMLALResult(MLALNode.getNode(), 0);
8104   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8105
8106   // Return original node to notify the driver to stop replacing.
8107   SDValue resNode(AddcNode, 0);
8108   return resNode;
8109 }
8110
8111 /// PerformADDCCombine - Target-specific dag combine transform from
8112 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8113 static SDValue PerformADDCCombine(SDNode *N,
8114                                  TargetLowering::DAGCombinerInfo &DCI,
8115                                  const ARMSubtarget *Subtarget) {
8116
8117   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8118
8119 }
8120
8121 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8122 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8123 /// called with the default operands, and if that fails, with commuted
8124 /// operands.
8125 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8126                                           TargetLowering::DAGCombinerInfo &DCI,
8127                                           const ARMSubtarget *Subtarget){
8128
8129   // Attempt to create vpaddl for this add.
8130   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8131   if (Result.getNode())
8132     return Result;
8133
8134   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8135   if (N0.getNode()->hasOneUse()) {
8136     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8137     if (Result.getNode()) return Result;
8138   }
8139   return SDValue();
8140 }
8141
8142 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8143 ///
8144 static SDValue PerformADDCombine(SDNode *N,
8145                                  TargetLowering::DAGCombinerInfo &DCI,
8146                                  const ARMSubtarget *Subtarget) {
8147   SDValue N0 = N->getOperand(0);
8148   SDValue N1 = N->getOperand(1);
8149
8150   // First try with the default operand order.
8151   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8152   if (Result.getNode())
8153     return Result;
8154
8155   // If that didn't work, try again with the operands commuted.
8156   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8157 }
8158
8159 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8160 ///
8161 static SDValue PerformSUBCombine(SDNode *N,
8162                                  TargetLowering::DAGCombinerInfo &DCI) {
8163   SDValue N0 = N->getOperand(0);
8164   SDValue N1 = N->getOperand(1);
8165
8166   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8167   if (N1.getNode()->hasOneUse()) {
8168     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8169     if (Result.getNode()) return Result;
8170   }
8171
8172   return SDValue();
8173 }
8174
8175 /// PerformVMULCombine
8176 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8177 /// special multiplier accumulator forwarding.
8178 ///   vmul d3, d0, d2
8179 ///   vmla d3, d1, d2
8180 /// is faster than
8181 ///   vadd d3, d0, d1
8182 ///   vmul d3, d3, d2
8183 //  However, for (A + B) * (A + B),
8184 //    vadd d2, d0, d1
8185 //    vmul d3, d0, d2
8186 //    vmla d3, d1, d2
8187 //  is slower than
8188 //    vadd d2, d0, d1
8189 //    vmul d3, d2, d2
8190 static SDValue PerformVMULCombine(SDNode *N,
8191                                   TargetLowering::DAGCombinerInfo &DCI,
8192                                   const ARMSubtarget *Subtarget) {
8193   if (!Subtarget->hasVMLxForwarding())
8194     return SDValue();
8195
8196   SelectionDAG &DAG = DCI.DAG;
8197   SDValue N0 = N->getOperand(0);
8198   SDValue N1 = N->getOperand(1);
8199   unsigned Opcode = N0.getOpcode();
8200   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8201       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8202     Opcode = N1.getOpcode();
8203     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8204         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8205       return SDValue();
8206     std::swap(N0, N1);
8207   }
8208
8209   if (N0 == N1)
8210     return SDValue();
8211
8212   EVT VT = N->getValueType(0);
8213   SDLoc DL(N);
8214   SDValue N00 = N0->getOperand(0);
8215   SDValue N01 = N0->getOperand(1);
8216   return DAG.getNode(Opcode, DL, VT,
8217                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8218                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8219 }
8220
8221 static SDValue PerformMULCombine(SDNode *N,
8222                                  TargetLowering::DAGCombinerInfo &DCI,
8223                                  const ARMSubtarget *Subtarget) {
8224   SelectionDAG &DAG = DCI.DAG;
8225
8226   if (Subtarget->isThumb1Only())
8227     return SDValue();
8228
8229   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8230     return SDValue();
8231
8232   EVT VT = N->getValueType(0);
8233   if (VT.is64BitVector() || VT.is128BitVector())
8234     return PerformVMULCombine(N, DCI, Subtarget);
8235   if (VT != MVT::i32)
8236     return SDValue();
8237
8238   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8239   if (!C)
8240     return SDValue();
8241
8242   int64_t MulAmt = C->getSExtValue();
8243   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8244
8245   ShiftAmt = ShiftAmt & (32 - 1);
8246   SDValue V = N->getOperand(0);
8247   SDLoc DL(N);
8248
8249   SDValue Res;
8250   MulAmt >>= ShiftAmt;
8251
8252   if (MulAmt >= 0) {
8253     if (isPowerOf2_32(MulAmt - 1)) {
8254       // (mul x, 2^N + 1) => (add (shl x, N), x)
8255       Res = DAG.getNode(ISD::ADD, DL, VT,
8256                         V,
8257                         DAG.getNode(ISD::SHL, DL, VT,
8258                                     V,
8259                                     DAG.getConstant(Log2_32(MulAmt - 1),
8260                                                     MVT::i32)));
8261     } else if (isPowerOf2_32(MulAmt + 1)) {
8262       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8263       Res = DAG.getNode(ISD::SUB, DL, VT,
8264                         DAG.getNode(ISD::SHL, DL, VT,
8265                                     V,
8266                                     DAG.getConstant(Log2_32(MulAmt + 1),
8267                                                     MVT::i32)),
8268                         V);
8269     } else
8270       return SDValue();
8271   } else {
8272     uint64_t MulAmtAbs = -MulAmt;
8273     if (isPowerOf2_32(MulAmtAbs + 1)) {
8274       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8275       Res = DAG.getNode(ISD::SUB, DL, VT,
8276                         V,
8277                         DAG.getNode(ISD::SHL, DL, VT,
8278                                     V,
8279                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8280                                                     MVT::i32)));
8281     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8282       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8283       Res = DAG.getNode(ISD::ADD, DL, VT,
8284                         V,
8285                         DAG.getNode(ISD::SHL, DL, VT,
8286                                     V,
8287                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8288                                                     MVT::i32)));
8289       Res = DAG.getNode(ISD::SUB, DL, VT,
8290                         DAG.getConstant(0, MVT::i32),Res);
8291
8292     } else
8293       return SDValue();
8294   }
8295
8296   if (ShiftAmt != 0)
8297     Res = DAG.getNode(ISD::SHL, DL, VT,
8298                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8299
8300   // Do not add new nodes to DAG combiner worklist.
8301   DCI.CombineTo(N, Res, false);
8302   return SDValue();
8303 }
8304
8305 static SDValue PerformANDCombine(SDNode *N,
8306                                  TargetLowering::DAGCombinerInfo &DCI,
8307                                  const ARMSubtarget *Subtarget) {
8308
8309   // Attempt to use immediate-form VBIC
8310   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8311   SDLoc dl(N);
8312   EVT VT = N->getValueType(0);
8313   SelectionDAG &DAG = DCI.DAG;
8314
8315   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8316     return SDValue();
8317
8318   APInt SplatBits, SplatUndef;
8319   unsigned SplatBitSize;
8320   bool HasAnyUndefs;
8321   if (BVN &&
8322       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8323     if (SplatBitSize <= 64) {
8324       EVT VbicVT;
8325       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8326                                       SplatUndef.getZExtValue(), SplatBitSize,
8327                                       DAG, VbicVT, VT.is128BitVector(),
8328                                       OtherModImm);
8329       if (Val.getNode()) {
8330         SDValue Input =
8331           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8332         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8333         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8334       }
8335     }
8336   }
8337
8338   if (!Subtarget->isThumb1Only()) {
8339     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8340     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8341     if (Result.getNode())
8342       return Result;
8343   }
8344
8345   return SDValue();
8346 }
8347
8348 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8349 static SDValue PerformORCombine(SDNode *N,
8350                                 TargetLowering::DAGCombinerInfo &DCI,
8351                                 const ARMSubtarget *Subtarget) {
8352   // Attempt to use immediate-form VORR
8353   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8354   SDLoc dl(N);
8355   EVT VT = N->getValueType(0);
8356   SelectionDAG &DAG = DCI.DAG;
8357
8358   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8359     return SDValue();
8360
8361   APInt SplatBits, SplatUndef;
8362   unsigned SplatBitSize;
8363   bool HasAnyUndefs;
8364   if (BVN && Subtarget->hasNEON() &&
8365       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8366     if (SplatBitSize <= 64) {
8367       EVT VorrVT;
8368       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8369                                       SplatUndef.getZExtValue(), SplatBitSize,
8370                                       DAG, VorrVT, VT.is128BitVector(),
8371                                       OtherModImm);
8372       if (Val.getNode()) {
8373         SDValue Input =
8374           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8375         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8376         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8377       }
8378     }
8379   }
8380
8381   if (!Subtarget->isThumb1Only()) {
8382     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8383     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8384     if (Result.getNode())
8385       return Result;
8386   }
8387
8388   // The code below optimizes (or (and X, Y), Z).
8389   // The AND operand needs to have a single user to make these optimizations
8390   // profitable.
8391   SDValue N0 = N->getOperand(0);
8392   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8393     return SDValue();
8394   SDValue N1 = N->getOperand(1);
8395
8396   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8397   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8398       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8399     APInt SplatUndef;
8400     unsigned SplatBitSize;
8401     bool HasAnyUndefs;
8402
8403     APInt SplatBits0, SplatBits1;
8404     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8405     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8406     // Ensure that the second operand of both ands are constants
8407     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8408                                       HasAnyUndefs) && !HasAnyUndefs) {
8409         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8410                                           HasAnyUndefs) && !HasAnyUndefs) {
8411             // Ensure that the bit width of the constants are the same and that
8412             // the splat arguments are logical inverses as per the pattern we
8413             // are trying to simplify.
8414             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8415                 SplatBits0 == ~SplatBits1) {
8416                 // Canonicalize the vector type to make instruction selection
8417                 // simpler.
8418                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8419                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8420                                              N0->getOperand(1),
8421                                              N0->getOperand(0),
8422                                              N1->getOperand(0));
8423                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8424             }
8425         }
8426     }
8427   }
8428
8429   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8430   // reasonable.
8431
8432   // BFI is only available on V6T2+
8433   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8434     return SDValue();
8435
8436   SDLoc DL(N);
8437   // 1) or (and A, mask), val => ARMbfi A, val, mask
8438   //      iff (val & mask) == val
8439   //
8440   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8441   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8442   //          && mask == ~mask2
8443   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8444   //          && ~mask == mask2
8445   //  (i.e., copy a bitfield value into another bitfield of the same width)
8446
8447   if (VT != MVT::i32)
8448     return SDValue();
8449
8450   SDValue N00 = N0.getOperand(0);
8451
8452   // The value and the mask need to be constants so we can verify this is
8453   // actually a bitfield set. If the mask is 0xffff, we can do better
8454   // via a movt instruction, so don't use BFI in that case.
8455   SDValue MaskOp = N0.getOperand(1);
8456   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8457   if (!MaskC)
8458     return SDValue();
8459   unsigned Mask = MaskC->getZExtValue();
8460   if (Mask == 0xffff)
8461     return SDValue();
8462   SDValue Res;
8463   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8464   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8465   if (N1C) {
8466     unsigned Val = N1C->getZExtValue();
8467     if ((Val & ~Mask) != Val)
8468       return SDValue();
8469
8470     if (ARM::isBitFieldInvertedMask(Mask)) {
8471       Val >>= countTrailingZeros(~Mask);
8472
8473       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8474                         DAG.getConstant(Val, MVT::i32),
8475                         DAG.getConstant(Mask, MVT::i32));
8476
8477       // Do not add new nodes to DAG combiner worklist.
8478       DCI.CombineTo(N, Res, false);
8479       return SDValue();
8480     }
8481   } else if (N1.getOpcode() == ISD::AND) {
8482     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8483     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8484     if (!N11C)
8485       return SDValue();
8486     unsigned Mask2 = N11C->getZExtValue();
8487
8488     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8489     // as is to match.
8490     if (ARM::isBitFieldInvertedMask(Mask) &&
8491         (Mask == ~Mask2)) {
8492       // The pack halfword instruction works better for masks that fit it,
8493       // so use that when it's available.
8494       if (Subtarget->hasT2ExtractPack() &&
8495           (Mask == 0xffff || Mask == 0xffff0000))
8496         return SDValue();
8497       // 2a
8498       unsigned amt = countTrailingZeros(Mask2);
8499       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8500                         DAG.getConstant(amt, MVT::i32));
8501       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8502                         DAG.getConstant(Mask, MVT::i32));
8503       // Do not add new nodes to DAG combiner worklist.
8504       DCI.CombineTo(N, Res, false);
8505       return SDValue();
8506     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8507                (~Mask == Mask2)) {
8508       // The pack halfword instruction works better for masks that fit it,
8509       // so use that when it's available.
8510       if (Subtarget->hasT2ExtractPack() &&
8511           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8512         return SDValue();
8513       // 2b
8514       unsigned lsb = countTrailingZeros(Mask);
8515       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8516                         DAG.getConstant(lsb, MVT::i32));
8517       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8518                         DAG.getConstant(Mask2, MVT::i32));
8519       // Do not add new nodes to DAG combiner worklist.
8520       DCI.CombineTo(N, Res, false);
8521       return SDValue();
8522     }
8523   }
8524
8525   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8526       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8527       ARM::isBitFieldInvertedMask(~Mask)) {
8528     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8529     // where lsb(mask) == #shamt and masked bits of B are known zero.
8530     SDValue ShAmt = N00.getOperand(1);
8531     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8532     unsigned LSB = countTrailingZeros(Mask);
8533     if (ShAmtC != LSB)
8534       return SDValue();
8535
8536     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8537                       DAG.getConstant(~Mask, MVT::i32));
8538
8539     // Do not add new nodes to DAG combiner worklist.
8540     DCI.CombineTo(N, Res, false);
8541   }
8542
8543   return SDValue();
8544 }
8545
8546 static SDValue PerformXORCombine(SDNode *N,
8547                                  TargetLowering::DAGCombinerInfo &DCI,
8548                                  const ARMSubtarget *Subtarget) {
8549   EVT VT = N->getValueType(0);
8550   SelectionDAG &DAG = DCI.DAG;
8551
8552   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8553     return SDValue();
8554
8555   if (!Subtarget->isThumb1Only()) {
8556     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8557     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8558     if (Result.getNode())
8559       return Result;
8560   }
8561
8562   return SDValue();
8563 }
8564
8565 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8566 /// the bits being cleared by the AND are not demanded by the BFI.
8567 static SDValue PerformBFICombine(SDNode *N,
8568                                  TargetLowering::DAGCombinerInfo &DCI) {
8569   SDValue N1 = N->getOperand(1);
8570   if (N1.getOpcode() == ISD::AND) {
8571     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8572     if (!N11C)
8573       return SDValue();
8574     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8575     unsigned LSB = countTrailingZeros(~InvMask);
8576     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8577     unsigned Mask = (1 << Width)-1;
8578     unsigned Mask2 = N11C->getZExtValue();
8579     if ((Mask & (~Mask2)) == 0)
8580       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8581                              N->getOperand(0), N1.getOperand(0),
8582                              N->getOperand(2));
8583   }
8584   return SDValue();
8585 }
8586
8587 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8588 /// ARMISD::VMOVRRD.
8589 static SDValue PerformVMOVRRDCombine(SDNode *N,
8590                                      TargetLowering::DAGCombinerInfo &DCI,
8591                                      const ARMSubtarget *Subtarget) {
8592   // vmovrrd(vmovdrr x, y) -> x,y
8593   SDValue InDouble = N->getOperand(0);
8594   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8595     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8596
8597   // vmovrrd(load f64) -> (load i32), (load i32)
8598   SDNode *InNode = InDouble.getNode();
8599   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8600       InNode->getValueType(0) == MVT::f64 &&
8601       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8602       !cast<LoadSDNode>(InNode)->isVolatile()) {
8603     // TODO: Should this be done for non-FrameIndex operands?
8604     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8605
8606     SelectionDAG &DAG = DCI.DAG;
8607     SDLoc DL(LD);
8608     SDValue BasePtr = LD->getBasePtr();
8609     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8610                                  LD->getPointerInfo(), LD->isVolatile(),
8611                                  LD->isNonTemporal(), LD->isInvariant(),
8612                                  LD->getAlignment());
8613
8614     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8615                                     DAG.getConstant(4, MVT::i32));
8616     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8617                                  LD->getPointerInfo(), LD->isVolatile(),
8618                                  LD->isNonTemporal(), LD->isInvariant(),
8619                                  std::min(4U, LD->getAlignment() / 2));
8620
8621     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8622     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8623       std::swap (NewLD1, NewLD2);
8624     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8625     return Result;
8626   }
8627
8628   return SDValue();
8629 }
8630
8631 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8632 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8633 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8634   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8635   SDValue Op0 = N->getOperand(0);
8636   SDValue Op1 = N->getOperand(1);
8637   if (Op0.getOpcode() == ISD::BITCAST)
8638     Op0 = Op0.getOperand(0);
8639   if (Op1.getOpcode() == ISD::BITCAST)
8640     Op1 = Op1.getOperand(0);
8641   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8642       Op0.getNode() == Op1.getNode() &&
8643       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8644     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8645                        N->getValueType(0), Op0.getOperand(0));
8646   return SDValue();
8647 }
8648
8649 /// PerformSTORECombine - Target-specific dag combine xforms for
8650 /// ISD::STORE.
8651 static SDValue PerformSTORECombine(SDNode *N,
8652                                    TargetLowering::DAGCombinerInfo &DCI) {
8653   StoreSDNode *St = cast<StoreSDNode>(N);
8654   if (St->isVolatile())
8655     return SDValue();
8656
8657   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8658   // pack all of the elements in one place.  Next, store to memory in fewer
8659   // chunks.
8660   SDValue StVal = St->getValue();
8661   EVT VT = StVal.getValueType();
8662   if (St->isTruncatingStore() && VT.isVector()) {
8663     SelectionDAG &DAG = DCI.DAG;
8664     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8665     EVT StVT = St->getMemoryVT();
8666     unsigned NumElems = VT.getVectorNumElements();
8667     assert(StVT != VT && "Cannot truncate to the same type");
8668     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8669     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8670
8671     // From, To sizes and ElemCount must be pow of two
8672     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8673
8674     // We are going to use the original vector elt for storing.
8675     // Accumulated smaller vector elements must be a multiple of the store size.
8676     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8677
8678     unsigned SizeRatio  = FromEltSz / ToEltSz;
8679     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8680
8681     // Create a type on which we perform the shuffle.
8682     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8683                                      NumElems*SizeRatio);
8684     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8685
8686     SDLoc DL(St);
8687     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8688     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8689     for (unsigned i = 0; i < NumElems; ++i)
8690       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8691
8692     // Can't shuffle using an illegal type.
8693     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8694
8695     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8696                                 DAG.getUNDEF(WideVec.getValueType()),
8697                                 ShuffleVec.data());
8698     // At this point all of the data is stored at the bottom of the
8699     // register. We now need to save it to mem.
8700
8701     // Find the largest store unit
8702     MVT StoreType = MVT::i8;
8703     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8704          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8705       MVT Tp = (MVT::SimpleValueType)tp;
8706       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8707         StoreType = Tp;
8708     }
8709     // Didn't find a legal store type.
8710     if (!TLI.isTypeLegal(StoreType))
8711       return SDValue();
8712
8713     // Bitcast the original vector into a vector of store-size units
8714     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8715             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8716     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8717     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8718     SmallVector<SDValue, 8> Chains;
8719     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8720                                         TLI.getPointerTy());
8721     SDValue BasePtr = St->getBasePtr();
8722
8723     // Perform one or more big stores into memory.
8724     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8725     for (unsigned I = 0; I < E; I++) {
8726       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8727                                    StoreType, ShuffWide,
8728                                    DAG.getIntPtrConstant(I));
8729       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8730                                 St->getPointerInfo(), St->isVolatile(),
8731                                 St->isNonTemporal(), St->getAlignment());
8732       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8733                             Increment);
8734       Chains.push_back(Ch);
8735     }
8736     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8737   }
8738
8739   if (!ISD::isNormalStore(St))
8740     return SDValue();
8741
8742   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8743   // ARM stores of arguments in the same cache line.
8744   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8745       StVal.getNode()->hasOneUse()) {
8746     SelectionDAG  &DAG = DCI.DAG;
8747     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8748     SDLoc DL(St);
8749     SDValue BasePtr = St->getBasePtr();
8750     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8751                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8752                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8753                                   St->isNonTemporal(), St->getAlignment());
8754
8755     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8756                                     DAG.getConstant(4, MVT::i32));
8757     return DAG.getStore(NewST1.getValue(0), DL,
8758                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8759                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8760                         St->isNonTemporal(),
8761                         std::min(4U, St->getAlignment() / 2));
8762   }
8763
8764   if (StVal.getValueType() != MVT::i64 ||
8765       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8766     return SDValue();
8767
8768   // Bitcast an i64 store extracted from a vector to f64.
8769   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8770   SelectionDAG &DAG = DCI.DAG;
8771   SDLoc dl(StVal);
8772   SDValue IntVec = StVal.getOperand(0);
8773   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8774                                  IntVec.getValueType().getVectorNumElements());
8775   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8776   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8777                                Vec, StVal.getOperand(1));
8778   dl = SDLoc(N);
8779   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8780   // Make the DAGCombiner fold the bitcasts.
8781   DCI.AddToWorklist(Vec.getNode());
8782   DCI.AddToWorklist(ExtElt.getNode());
8783   DCI.AddToWorklist(V.getNode());
8784   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8785                       St->getPointerInfo(), St->isVolatile(),
8786                       St->isNonTemporal(), St->getAlignment(),
8787                       St->getAAInfo());
8788 }
8789
8790 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8791 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8792 /// i64 vector to have f64 elements, since the value can then be loaded
8793 /// directly into a VFP register.
8794 static bool hasNormalLoadOperand(SDNode *N) {
8795   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8796   for (unsigned i = 0; i < NumElts; ++i) {
8797     SDNode *Elt = N->getOperand(i).getNode();
8798     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8799       return true;
8800   }
8801   return false;
8802 }
8803
8804 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8805 /// ISD::BUILD_VECTOR.
8806 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8807                                           TargetLowering::DAGCombinerInfo &DCI,
8808                                           const ARMSubtarget *Subtarget) {
8809   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8810   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8811   // into a pair of GPRs, which is fine when the value is used as a scalar,
8812   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8813   SelectionDAG &DAG = DCI.DAG;
8814   if (N->getNumOperands() == 2) {
8815     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8816     if (RV.getNode())
8817       return RV;
8818   }
8819
8820   // Load i64 elements as f64 values so that type legalization does not split
8821   // them up into i32 values.
8822   EVT VT = N->getValueType(0);
8823   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8824     return SDValue();
8825   SDLoc dl(N);
8826   SmallVector<SDValue, 8> Ops;
8827   unsigned NumElts = VT.getVectorNumElements();
8828   for (unsigned i = 0; i < NumElts; ++i) {
8829     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8830     Ops.push_back(V);
8831     // Make the DAGCombiner fold the bitcast.
8832     DCI.AddToWorklist(V.getNode());
8833   }
8834   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8835   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8836   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8837 }
8838
8839 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8840 static SDValue
8841 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8842   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8843   // At that time, we may have inserted bitcasts from integer to float.
8844   // If these bitcasts have survived DAGCombine, change the lowering of this
8845   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8846   // force to use floating point types.
8847
8848   // Make sure we can change the type of the vector.
8849   // This is possible iff:
8850   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8851   //    1.1. Vector is used only once.
8852   //    1.2. Use is a bit convert to an integer type.
8853   // 2. The size of its operands are 32-bits (64-bits are not legal).
8854   EVT VT = N->getValueType(0);
8855   EVT EltVT = VT.getVectorElementType();
8856
8857   // Check 1.1. and 2.
8858   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8859     return SDValue();
8860
8861   // By construction, the input type must be float.
8862   assert(EltVT == MVT::f32 && "Unexpected type!");
8863
8864   // Check 1.2.
8865   SDNode *Use = *N->use_begin();
8866   if (Use->getOpcode() != ISD::BITCAST ||
8867       Use->getValueType(0).isFloatingPoint())
8868     return SDValue();
8869
8870   // Check profitability.
8871   // Model is, if more than half of the relevant operands are bitcast from
8872   // i32, turn the build_vector into a sequence of insert_vector_elt.
8873   // Relevant operands are everything that is not statically
8874   // (i.e., at compile time) bitcasted.
8875   unsigned NumOfBitCastedElts = 0;
8876   unsigned NumElts = VT.getVectorNumElements();
8877   unsigned NumOfRelevantElts = NumElts;
8878   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8879     SDValue Elt = N->getOperand(Idx);
8880     if (Elt->getOpcode() == ISD::BITCAST) {
8881       // Assume only bit cast to i32 will go away.
8882       if (Elt->getOperand(0).getValueType() == MVT::i32)
8883         ++NumOfBitCastedElts;
8884     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8885       // Constants are statically casted, thus do not count them as
8886       // relevant operands.
8887       --NumOfRelevantElts;
8888   }
8889
8890   // Check if more than half of the elements require a non-free bitcast.
8891   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8892     return SDValue();
8893
8894   SelectionDAG &DAG = DCI.DAG;
8895   // Create the new vector type.
8896   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8897   // Check if the type is legal.
8898   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8899   if (!TLI.isTypeLegal(VecVT))
8900     return SDValue();
8901
8902   // Combine:
8903   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8904   // => BITCAST INSERT_VECTOR_ELT
8905   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8906   //                      (BITCAST EN), N.
8907   SDValue Vec = DAG.getUNDEF(VecVT);
8908   SDLoc dl(N);
8909   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8910     SDValue V = N->getOperand(Idx);
8911     if (V.getOpcode() == ISD::UNDEF)
8912       continue;
8913     if (V.getOpcode() == ISD::BITCAST &&
8914         V->getOperand(0).getValueType() == MVT::i32)
8915       // Fold obvious case.
8916       V = V.getOperand(0);
8917     else {
8918       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8919       // Make the DAGCombiner fold the bitcasts.
8920       DCI.AddToWorklist(V.getNode());
8921     }
8922     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8923     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8924   }
8925   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8926   // Make the DAGCombiner fold the bitcasts.
8927   DCI.AddToWorklist(Vec.getNode());
8928   return Vec;
8929 }
8930
8931 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8932 /// ISD::INSERT_VECTOR_ELT.
8933 static SDValue PerformInsertEltCombine(SDNode *N,
8934                                        TargetLowering::DAGCombinerInfo &DCI) {
8935   // Bitcast an i64 load inserted into a vector to f64.
8936   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8937   EVT VT = N->getValueType(0);
8938   SDNode *Elt = N->getOperand(1).getNode();
8939   if (VT.getVectorElementType() != MVT::i64 ||
8940       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8941     return SDValue();
8942
8943   SelectionDAG &DAG = DCI.DAG;
8944   SDLoc dl(N);
8945   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8946                                  VT.getVectorNumElements());
8947   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8948   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8949   // Make the DAGCombiner fold the bitcasts.
8950   DCI.AddToWorklist(Vec.getNode());
8951   DCI.AddToWorklist(V.getNode());
8952   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8953                                Vec, V, N->getOperand(2));
8954   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8955 }
8956
8957 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8958 /// ISD::VECTOR_SHUFFLE.
8959 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8960   // The LLVM shufflevector instruction does not require the shuffle mask
8961   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8962   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8963   // operands do not match the mask length, they are extended by concatenating
8964   // them with undef vectors.  That is probably the right thing for other
8965   // targets, but for NEON it is better to concatenate two double-register
8966   // size vector operands into a single quad-register size vector.  Do that
8967   // transformation here:
8968   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8969   //   shuffle(concat(v1, v2), undef)
8970   SDValue Op0 = N->getOperand(0);
8971   SDValue Op1 = N->getOperand(1);
8972   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8973       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8974       Op0.getNumOperands() != 2 ||
8975       Op1.getNumOperands() != 2)
8976     return SDValue();
8977   SDValue Concat0Op1 = Op0.getOperand(1);
8978   SDValue Concat1Op1 = Op1.getOperand(1);
8979   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8980       Concat1Op1.getOpcode() != ISD::UNDEF)
8981     return SDValue();
8982   // Skip the transformation if any of the types are illegal.
8983   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8984   EVT VT = N->getValueType(0);
8985   if (!TLI.isTypeLegal(VT) ||
8986       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8987       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8988     return SDValue();
8989
8990   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8991                                   Op0.getOperand(0), Op1.getOperand(0));
8992   // Translate the shuffle mask.
8993   SmallVector<int, 16> NewMask;
8994   unsigned NumElts = VT.getVectorNumElements();
8995   unsigned HalfElts = NumElts/2;
8996   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8997   for (unsigned n = 0; n < NumElts; ++n) {
8998     int MaskElt = SVN->getMaskElt(n);
8999     int NewElt = -1;
9000     if (MaskElt < (int)HalfElts)
9001       NewElt = MaskElt;
9002     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9003       NewElt = HalfElts + MaskElt - NumElts;
9004     NewMask.push_back(NewElt);
9005   }
9006   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9007                               DAG.getUNDEF(VT), NewMask.data());
9008 }
9009
9010 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9011 /// NEON load/store intrinsics to merge base address updates.
9012 static SDValue CombineBaseUpdate(SDNode *N,
9013                                  TargetLowering::DAGCombinerInfo &DCI) {
9014   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9015     return SDValue();
9016
9017   SelectionDAG &DAG = DCI.DAG;
9018   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9019                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9020   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9021   SDValue Addr = N->getOperand(AddrOpIdx);
9022
9023   // Search for a use of the address operand that is an increment.
9024   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9025          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9026     SDNode *User = *UI;
9027     if (User->getOpcode() != ISD::ADD ||
9028         UI.getUse().getResNo() != Addr.getResNo())
9029       continue;
9030
9031     // Check that the add is independent of the load/store.  Otherwise, folding
9032     // it would create a cycle.
9033     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9034       continue;
9035
9036     // Find the new opcode for the updating load/store.
9037     bool isLoad = true;
9038     bool isLaneOp = false;
9039     unsigned NewOpc = 0;
9040     unsigned NumVecs = 0;
9041     if (isIntrinsic) {
9042       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9043       switch (IntNo) {
9044       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9045       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9046         NumVecs = 1; break;
9047       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9048         NumVecs = 2; break;
9049       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9050         NumVecs = 3; break;
9051       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9052         NumVecs = 4; break;
9053       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9054         NumVecs = 2; isLaneOp = true; break;
9055       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9056         NumVecs = 3; isLaneOp = true; break;
9057       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9058         NumVecs = 4; isLaneOp = true; break;
9059       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9060         NumVecs = 1; isLoad = false; break;
9061       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9062         NumVecs = 2; isLoad = false; break;
9063       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9064         NumVecs = 3; isLoad = false; break;
9065       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9066         NumVecs = 4; isLoad = false; break;
9067       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9068         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9069       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9070         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9071       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9072         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9073       }
9074     } else {
9075       isLaneOp = true;
9076       switch (N->getOpcode()) {
9077       default: llvm_unreachable("unexpected opcode for Neon base update");
9078       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9079       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9080       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9081       }
9082     }
9083
9084     // Find the size of memory referenced by the load/store.
9085     EVT VecTy;
9086     if (isLoad)
9087       VecTy = N->getValueType(0);
9088     else
9089       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9090     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9091     if (isLaneOp)
9092       NumBytes /= VecTy.getVectorNumElements();
9093
9094     // If the increment is a constant, it must match the memory ref size.
9095     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9096     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9097       uint64_t IncVal = CInc->getZExtValue();
9098       if (IncVal != NumBytes)
9099         continue;
9100     } else if (NumBytes >= 3 * 16) {
9101       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9102       // separate instructions that make it harder to use a non-constant update.
9103       continue;
9104     }
9105
9106     // Create the new updating load/store node.
9107     EVT Tys[6];
9108     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9109     unsigned n;
9110     for (n = 0; n < NumResultVecs; ++n)
9111       Tys[n] = VecTy;
9112     Tys[n++] = MVT::i32;
9113     Tys[n] = MVT::Other;
9114     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9115     SmallVector<SDValue, 8> Ops;
9116     Ops.push_back(N->getOperand(0)); // incoming chain
9117     Ops.push_back(N->getOperand(AddrOpIdx));
9118     Ops.push_back(Inc);
9119     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9120       Ops.push_back(N->getOperand(i));
9121     }
9122     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9123     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9124                                            Ops, MemInt->getMemoryVT(),
9125                                            MemInt->getMemOperand());
9126
9127     // Update the uses.
9128     std::vector<SDValue> NewResults;
9129     for (unsigned i = 0; i < NumResultVecs; ++i) {
9130       NewResults.push_back(SDValue(UpdN.getNode(), i));
9131     }
9132     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9133     DCI.CombineTo(N, NewResults);
9134     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9135
9136     break;
9137   }
9138   return SDValue();
9139 }
9140
9141 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9142 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9143 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9144 /// return true.
9145 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9146   SelectionDAG &DAG = DCI.DAG;
9147   EVT VT = N->getValueType(0);
9148   // vldN-dup instructions only support 64-bit vectors for N > 1.
9149   if (!VT.is64BitVector())
9150     return false;
9151
9152   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9153   SDNode *VLD = N->getOperand(0).getNode();
9154   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9155     return false;
9156   unsigned NumVecs = 0;
9157   unsigned NewOpc = 0;
9158   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9159   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9160     NumVecs = 2;
9161     NewOpc = ARMISD::VLD2DUP;
9162   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9163     NumVecs = 3;
9164     NewOpc = ARMISD::VLD3DUP;
9165   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9166     NumVecs = 4;
9167     NewOpc = ARMISD::VLD4DUP;
9168   } else {
9169     return false;
9170   }
9171
9172   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9173   // numbers match the load.
9174   unsigned VLDLaneNo =
9175     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9176   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9177        UI != UE; ++UI) {
9178     // Ignore uses of the chain result.
9179     if (UI.getUse().getResNo() == NumVecs)
9180       continue;
9181     SDNode *User = *UI;
9182     if (User->getOpcode() != ARMISD::VDUPLANE ||
9183         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9184       return false;
9185   }
9186
9187   // Create the vldN-dup node.
9188   EVT Tys[5];
9189   unsigned n;
9190   for (n = 0; n < NumVecs; ++n)
9191     Tys[n] = VT;
9192   Tys[n] = MVT::Other;
9193   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9194   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9195   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9196   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9197                                            Ops, VLDMemInt->getMemoryVT(),
9198                                            VLDMemInt->getMemOperand());
9199
9200   // Update the uses.
9201   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9202        UI != UE; ++UI) {
9203     unsigned ResNo = UI.getUse().getResNo();
9204     // Ignore uses of the chain result.
9205     if (ResNo == NumVecs)
9206       continue;
9207     SDNode *User = *UI;
9208     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9209   }
9210
9211   // Now the vldN-lane intrinsic is dead except for its chain result.
9212   // Update uses of the chain.
9213   std::vector<SDValue> VLDDupResults;
9214   for (unsigned n = 0; n < NumVecs; ++n)
9215     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9216   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9217   DCI.CombineTo(VLD, VLDDupResults);
9218
9219   return true;
9220 }
9221
9222 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9223 /// ARMISD::VDUPLANE.
9224 static SDValue PerformVDUPLANECombine(SDNode *N,
9225                                       TargetLowering::DAGCombinerInfo &DCI) {
9226   SDValue Op = N->getOperand(0);
9227
9228   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9229   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9230   if (CombineVLDDUP(N, DCI))
9231     return SDValue(N, 0);
9232
9233   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9234   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9235   while (Op.getOpcode() == ISD::BITCAST)
9236     Op = Op.getOperand(0);
9237   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9238     return SDValue();
9239
9240   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9241   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9242   // The canonical VMOV for a zero vector uses a 32-bit element size.
9243   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9244   unsigned EltBits;
9245   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9246     EltSize = 8;
9247   EVT VT = N->getValueType(0);
9248   if (EltSize > VT.getVectorElementType().getSizeInBits())
9249     return SDValue();
9250
9251   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9252 }
9253
9254 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9255 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9256 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9257 {
9258   integerPart cN;
9259   integerPart c0 = 0;
9260   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9261        I != E; I++) {
9262     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9263     if (!C)
9264       return false;
9265
9266     bool isExact;
9267     APFloat APF = C->getValueAPF();
9268     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9269         != APFloat::opOK || !isExact)
9270       return false;
9271
9272     c0 = (I == 0) ? cN : c0;
9273     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9274       return false;
9275   }
9276   C = c0;
9277   return true;
9278 }
9279
9280 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9281 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9282 /// when the VMUL has a constant operand that is a power of 2.
9283 ///
9284 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9285 ///  vmul.f32        d16, d17, d16
9286 ///  vcvt.s32.f32    d16, d16
9287 /// becomes:
9288 ///  vcvt.s32.f32    d16, d16, #3
9289 static SDValue PerformVCVTCombine(SDNode *N,
9290                                   TargetLowering::DAGCombinerInfo &DCI,
9291                                   const ARMSubtarget *Subtarget) {
9292   SelectionDAG &DAG = DCI.DAG;
9293   SDValue Op = N->getOperand(0);
9294
9295   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9296       Op.getOpcode() != ISD::FMUL)
9297     return SDValue();
9298
9299   uint64_t C;
9300   SDValue N0 = Op->getOperand(0);
9301   SDValue ConstVec = Op->getOperand(1);
9302   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9303
9304   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9305       !isConstVecPow2(ConstVec, isSigned, C))
9306     return SDValue();
9307
9308   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9309   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9310   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9311     // These instructions only exist converting from f32 to i32. We can handle
9312     // smaller integers by generating an extra truncate, but larger ones would
9313     // be lossy.
9314     return SDValue();
9315   }
9316
9317   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9318     Intrinsic::arm_neon_vcvtfp2fxu;
9319   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9320   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9321                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9322                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9323                                  DAG.getConstant(Log2_64(C), MVT::i32));
9324
9325   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9326     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9327
9328   return FixConv;
9329 }
9330
9331 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9332 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9333 /// when the VDIV has a constant operand that is a power of 2.
9334 ///
9335 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9336 ///  vcvt.f32.s32    d16, d16
9337 ///  vdiv.f32        d16, d17, d16
9338 /// becomes:
9339 ///  vcvt.f32.s32    d16, d16, #3
9340 static SDValue PerformVDIVCombine(SDNode *N,
9341                                   TargetLowering::DAGCombinerInfo &DCI,
9342                                   const ARMSubtarget *Subtarget) {
9343   SelectionDAG &DAG = DCI.DAG;
9344   SDValue Op = N->getOperand(0);
9345   unsigned OpOpcode = Op.getNode()->getOpcode();
9346
9347   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9348       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9349     return SDValue();
9350
9351   uint64_t C;
9352   SDValue ConstVec = N->getOperand(1);
9353   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9354
9355   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9356       !isConstVecPow2(ConstVec, isSigned, C))
9357     return SDValue();
9358
9359   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9360   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9361   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9362     // These instructions only exist converting from i32 to f32. We can handle
9363     // smaller integers by generating an extra extend, but larger ones would
9364     // be lossy.
9365     return SDValue();
9366   }
9367
9368   SDValue ConvInput = Op.getOperand(0);
9369   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9370   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9371     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9372                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9373                             ConvInput);
9374
9375   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9376     Intrinsic::arm_neon_vcvtfxu2fp;
9377   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9378                      Op.getValueType(),
9379                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9380                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9381 }
9382
9383 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9384 /// operand of a vector shift operation, where all the elements of the
9385 /// build_vector must have the same constant integer value.
9386 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9387   // Ignore bit_converts.
9388   while (Op.getOpcode() == ISD::BITCAST)
9389     Op = Op.getOperand(0);
9390   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9391   APInt SplatBits, SplatUndef;
9392   unsigned SplatBitSize;
9393   bool HasAnyUndefs;
9394   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9395                                       HasAnyUndefs, ElementBits) ||
9396       SplatBitSize > ElementBits)
9397     return false;
9398   Cnt = SplatBits.getSExtValue();
9399   return true;
9400 }
9401
9402 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9403 /// operand of a vector shift left operation.  That value must be in the range:
9404 ///   0 <= Value < ElementBits for a left shift; or
9405 ///   0 <= Value <= ElementBits for a long left shift.
9406 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9407   assert(VT.isVector() && "vector shift count is not a vector type");
9408   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9409   if (! getVShiftImm(Op, ElementBits, Cnt))
9410     return false;
9411   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9412 }
9413
9414 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9415 /// operand of a vector shift right operation.  For a shift opcode, the value
9416 /// is positive, but for an intrinsic the value count must be negative. The
9417 /// absolute value must be in the range:
9418 ///   1 <= |Value| <= ElementBits for a right shift; or
9419 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9420 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9421                          int64_t &Cnt) {
9422   assert(VT.isVector() && "vector shift count is not a vector type");
9423   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9424   if (! getVShiftImm(Op, ElementBits, Cnt))
9425     return false;
9426   if (isIntrinsic)
9427     Cnt = -Cnt;
9428   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9429 }
9430
9431 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9432 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9433   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9434   switch (IntNo) {
9435   default:
9436     // Don't do anything for most intrinsics.
9437     break;
9438
9439   // Vector shifts: check for immediate versions and lower them.
9440   // Note: This is done during DAG combining instead of DAG legalizing because
9441   // the build_vectors for 64-bit vector element shift counts are generally
9442   // not legal, and it is hard to see their values after they get legalized to
9443   // loads from a constant pool.
9444   case Intrinsic::arm_neon_vshifts:
9445   case Intrinsic::arm_neon_vshiftu:
9446   case Intrinsic::arm_neon_vrshifts:
9447   case Intrinsic::arm_neon_vrshiftu:
9448   case Intrinsic::arm_neon_vrshiftn:
9449   case Intrinsic::arm_neon_vqshifts:
9450   case Intrinsic::arm_neon_vqshiftu:
9451   case Intrinsic::arm_neon_vqshiftsu:
9452   case Intrinsic::arm_neon_vqshiftns:
9453   case Intrinsic::arm_neon_vqshiftnu:
9454   case Intrinsic::arm_neon_vqshiftnsu:
9455   case Intrinsic::arm_neon_vqrshiftns:
9456   case Intrinsic::arm_neon_vqrshiftnu:
9457   case Intrinsic::arm_neon_vqrshiftnsu: {
9458     EVT VT = N->getOperand(1).getValueType();
9459     int64_t Cnt;
9460     unsigned VShiftOpc = 0;
9461
9462     switch (IntNo) {
9463     case Intrinsic::arm_neon_vshifts:
9464     case Intrinsic::arm_neon_vshiftu:
9465       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9466         VShiftOpc = ARMISD::VSHL;
9467         break;
9468       }
9469       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9470         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9471                      ARMISD::VSHRs : ARMISD::VSHRu);
9472         break;
9473       }
9474       return SDValue();
9475
9476     case Intrinsic::arm_neon_vrshifts:
9477     case Intrinsic::arm_neon_vrshiftu:
9478       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9479         break;
9480       return SDValue();
9481
9482     case Intrinsic::arm_neon_vqshifts:
9483     case Intrinsic::arm_neon_vqshiftu:
9484       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9485         break;
9486       return SDValue();
9487
9488     case Intrinsic::arm_neon_vqshiftsu:
9489       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9490         break;
9491       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9492
9493     case Intrinsic::arm_neon_vrshiftn:
9494     case Intrinsic::arm_neon_vqshiftns:
9495     case Intrinsic::arm_neon_vqshiftnu:
9496     case Intrinsic::arm_neon_vqshiftnsu:
9497     case Intrinsic::arm_neon_vqrshiftns:
9498     case Intrinsic::arm_neon_vqrshiftnu:
9499     case Intrinsic::arm_neon_vqrshiftnsu:
9500       // Narrowing shifts require an immediate right shift.
9501       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9502         break;
9503       llvm_unreachable("invalid shift count for narrowing vector shift "
9504                        "intrinsic");
9505
9506     default:
9507       llvm_unreachable("unhandled vector shift");
9508     }
9509
9510     switch (IntNo) {
9511     case Intrinsic::arm_neon_vshifts:
9512     case Intrinsic::arm_neon_vshiftu:
9513       // Opcode already set above.
9514       break;
9515     case Intrinsic::arm_neon_vrshifts:
9516       VShiftOpc = ARMISD::VRSHRs; break;
9517     case Intrinsic::arm_neon_vrshiftu:
9518       VShiftOpc = ARMISD::VRSHRu; break;
9519     case Intrinsic::arm_neon_vrshiftn:
9520       VShiftOpc = ARMISD::VRSHRN; break;
9521     case Intrinsic::arm_neon_vqshifts:
9522       VShiftOpc = ARMISD::VQSHLs; break;
9523     case Intrinsic::arm_neon_vqshiftu:
9524       VShiftOpc = ARMISD::VQSHLu; break;
9525     case Intrinsic::arm_neon_vqshiftsu:
9526       VShiftOpc = ARMISD::VQSHLsu; break;
9527     case Intrinsic::arm_neon_vqshiftns:
9528       VShiftOpc = ARMISD::VQSHRNs; break;
9529     case Intrinsic::arm_neon_vqshiftnu:
9530       VShiftOpc = ARMISD::VQSHRNu; break;
9531     case Intrinsic::arm_neon_vqshiftnsu:
9532       VShiftOpc = ARMISD::VQSHRNsu; break;
9533     case Intrinsic::arm_neon_vqrshiftns:
9534       VShiftOpc = ARMISD::VQRSHRNs; break;
9535     case Intrinsic::arm_neon_vqrshiftnu:
9536       VShiftOpc = ARMISD::VQRSHRNu; break;
9537     case Intrinsic::arm_neon_vqrshiftnsu:
9538       VShiftOpc = ARMISD::VQRSHRNsu; break;
9539     }
9540
9541     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9542                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9543   }
9544
9545   case Intrinsic::arm_neon_vshiftins: {
9546     EVT VT = N->getOperand(1).getValueType();
9547     int64_t Cnt;
9548     unsigned VShiftOpc = 0;
9549
9550     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9551       VShiftOpc = ARMISD::VSLI;
9552     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9553       VShiftOpc = ARMISD::VSRI;
9554     else {
9555       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9556     }
9557
9558     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9559                        N->getOperand(1), N->getOperand(2),
9560                        DAG.getConstant(Cnt, MVT::i32));
9561   }
9562
9563   case Intrinsic::arm_neon_vqrshifts:
9564   case Intrinsic::arm_neon_vqrshiftu:
9565     // No immediate versions of these to check for.
9566     break;
9567   }
9568
9569   return SDValue();
9570 }
9571
9572 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9573 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9574 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9575 /// vector element shift counts are generally not legal, and it is hard to see
9576 /// their values after they get legalized to loads from a constant pool.
9577 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9578                                    const ARMSubtarget *ST) {
9579   EVT VT = N->getValueType(0);
9580   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9581     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9582     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9583     SDValue N1 = N->getOperand(1);
9584     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9585       SDValue N0 = N->getOperand(0);
9586       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9587           DAG.MaskedValueIsZero(N0.getOperand(0),
9588                                 APInt::getHighBitsSet(32, 16)))
9589         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9590     }
9591   }
9592
9593   // Nothing to be done for scalar shifts.
9594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9595   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9596     return SDValue();
9597
9598   assert(ST->hasNEON() && "unexpected vector shift");
9599   int64_t Cnt;
9600
9601   switch (N->getOpcode()) {
9602   default: llvm_unreachable("unexpected shift opcode");
9603
9604   case ISD::SHL:
9605     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9606       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9607                          DAG.getConstant(Cnt, MVT::i32));
9608     break;
9609
9610   case ISD::SRA:
9611   case ISD::SRL:
9612     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9613       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9614                             ARMISD::VSHRs : ARMISD::VSHRu);
9615       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9616                          DAG.getConstant(Cnt, MVT::i32));
9617     }
9618   }
9619   return SDValue();
9620 }
9621
9622 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9623 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9624 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9625                                     const ARMSubtarget *ST) {
9626   SDValue N0 = N->getOperand(0);
9627
9628   // Check for sign- and zero-extensions of vector extract operations of 8-
9629   // and 16-bit vector elements.  NEON supports these directly.  They are
9630   // handled during DAG combining because type legalization will promote them
9631   // to 32-bit types and it is messy to recognize the operations after that.
9632   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9633     SDValue Vec = N0.getOperand(0);
9634     SDValue Lane = N0.getOperand(1);
9635     EVT VT = N->getValueType(0);
9636     EVT EltVT = N0.getValueType();
9637     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9638
9639     if (VT == MVT::i32 &&
9640         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9641         TLI.isTypeLegal(Vec.getValueType()) &&
9642         isa<ConstantSDNode>(Lane)) {
9643
9644       unsigned Opc = 0;
9645       switch (N->getOpcode()) {
9646       default: llvm_unreachable("unexpected opcode");
9647       case ISD::SIGN_EXTEND:
9648         Opc = ARMISD::VGETLANEs;
9649         break;
9650       case ISD::ZERO_EXTEND:
9651       case ISD::ANY_EXTEND:
9652         Opc = ARMISD::VGETLANEu;
9653         break;
9654       }
9655       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9656     }
9657   }
9658
9659   return SDValue();
9660 }
9661
9662 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9663 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9664 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9665                                        const ARMSubtarget *ST) {
9666   // If the target supports NEON, try to use vmax/vmin instructions for f32
9667   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9668   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9669   // a NaN; only do the transformation when it matches that behavior.
9670
9671   // For now only do this when using NEON for FP operations; if using VFP, it
9672   // is not obvious that the benefit outweighs the cost of switching to the
9673   // NEON pipeline.
9674   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9675       N->getValueType(0) != MVT::f32)
9676     return SDValue();
9677
9678   SDValue CondLHS = N->getOperand(0);
9679   SDValue CondRHS = N->getOperand(1);
9680   SDValue LHS = N->getOperand(2);
9681   SDValue RHS = N->getOperand(3);
9682   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9683
9684   unsigned Opcode = 0;
9685   bool IsReversed;
9686   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9687     IsReversed = false; // x CC y ? x : y
9688   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9689     IsReversed = true ; // x CC y ? y : x
9690   } else {
9691     return SDValue();
9692   }
9693
9694   bool IsUnordered;
9695   switch (CC) {
9696   default: break;
9697   case ISD::SETOLT:
9698   case ISD::SETOLE:
9699   case ISD::SETLT:
9700   case ISD::SETLE:
9701   case ISD::SETULT:
9702   case ISD::SETULE:
9703     // If LHS is NaN, an ordered comparison will be false and the result will
9704     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9705     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9706     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9707     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9708       break;
9709     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9710     // will return -0, so vmin can only be used for unsafe math or if one of
9711     // the operands is known to be nonzero.
9712     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9713         !DAG.getTarget().Options.UnsafeFPMath &&
9714         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9715       break;
9716     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9717     break;
9718
9719   case ISD::SETOGT:
9720   case ISD::SETOGE:
9721   case ISD::SETGT:
9722   case ISD::SETGE:
9723   case ISD::SETUGT:
9724   case ISD::SETUGE:
9725     // If LHS is NaN, an ordered comparison will be false and the result will
9726     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9727     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9728     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9729     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9730       break;
9731     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9732     // will return +0, so vmax can only be used for unsafe math or if one of
9733     // the operands is known to be nonzero.
9734     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9735         !DAG.getTarget().Options.UnsafeFPMath &&
9736         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9737       break;
9738     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9739     break;
9740   }
9741
9742   if (!Opcode)
9743     return SDValue();
9744   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9745 }
9746
9747 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9748 SDValue
9749 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9750   SDValue Cmp = N->getOperand(4);
9751   if (Cmp.getOpcode() != ARMISD::CMPZ)
9752     // Only looking at EQ and NE cases.
9753     return SDValue();
9754
9755   EVT VT = N->getValueType(0);
9756   SDLoc dl(N);
9757   SDValue LHS = Cmp.getOperand(0);
9758   SDValue RHS = Cmp.getOperand(1);
9759   SDValue FalseVal = N->getOperand(0);
9760   SDValue TrueVal = N->getOperand(1);
9761   SDValue ARMcc = N->getOperand(2);
9762   ARMCC::CondCodes CC =
9763     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9764
9765   // Simplify
9766   //   mov     r1, r0
9767   //   cmp     r1, x
9768   //   mov     r0, y
9769   //   moveq   r0, x
9770   // to
9771   //   cmp     r0, x
9772   //   movne   r0, y
9773   //
9774   //   mov     r1, r0
9775   //   cmp     r1, x
9776   //   mov     r0, x
9777   //   movne   r0, y
9778   // to
9779   //   cmp     r0, x
9780   //   movne   r0, y
9781   /// FIXME: Turn this into a target neutral optimization?
9782   SDValue Res;
9783   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9784     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9785                       N->getOperand(3), Cmp);
9786   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9787     SDValue ARMcc;
9788     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9789     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9790                       N->getOperand(3), NewCmp);
9791   }
9792
9793   if (Res.getNode()) {
9794     APInt KnownZero, KnownOne;
9795     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9796     // Capture demanded bits information that would be otherwise lost.
9797     if (KnownZero == 0xfffffffe)
9798       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9799                         DAG.getValueType(MVT::i1));
9800     else if (KnownZero == 0xffffff00)
9801       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9802                         DAG.getValueType(MVT::i8));
9803     else if (KnownZero == 0xffff0000)
9804       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9805                         DAG.getValueType(MVT::i16));
9806   }
9807
9808   return Res;
9809 }
9810
9811 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9812                                              DAGCombinerInfo &DCI) const {
9813   switch (N->getOpcode()) {
9814   default: break;
9815   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9816   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9817   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9818   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9819   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9820   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9821   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9822   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9823   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9824   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9825   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9826   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9827   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9828   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9829   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9830   case ISD::FP_TO_SINT:
9831   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9832   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9833   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9834   case ISD::SHL:
9835   case ISD::SRA:
9836   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9837   case ISD::SIGN_EXTEND:
9838   case ISD::ZERO_EXTEND:
9839   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9840   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9841   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9842   case ARMISD::VLD2DUP:
9843   case ARMISD::VLD3DUP:
9844   case ARMISD::VLD4DUP:
9845     return CombineBaseUpdate(N, DCI);
9846   case ARMISD::BUILD_VECTOR:
9847     return PerformARMBUILD_VECTORCombine(N, DCI);
9848   case ISD::INTRINSIC_VOID:
9849   case ISD::INTRINSIC_W_CHAIN:
9850     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9851     case Intrinsic::arm_neon_vld1:
9852     case Intrinsic::arm_neon_vld2:
9853     case Intrinsic::arm_neon_vld3:
9854     case Intrinsic::arm_neon_vld4:
9855     case Intrinsic::arm_neon_vld2lane:
9856     case Intrinsic::arm_neon_vld3lane:
9857     case Intrinsic::arm_neon_vld4lane:
9858     case Intrinsic::arm_neon_vst1:
9859     case Intrinsic::arm_neon_vst2:
9860     case Intrinsic::arm_neon_vst3:
9861     case Intrinsic::arm_neon_vst4:
9862     case Intrinsic::arm_neon_vst2lane:
9863     case Intrinsic::arm_neon_vst3lane:
9864     case Intrinsic::arm_neon_vst4lane:
9865       return CombineBaseUpdate(N, DCI);
9866     default: break;
9867     }
9868     break;
9869   }
9870   return SDValue();
9871 }
9872
9873 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9874                                                           EVT VT) const {
9875   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9876 }
9877
9878 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9879                                                        unsigned,
9880                                                        unsigned,
9881                                                        bool *Fast) const {
9882   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9883   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9884
9885   switch (VT.getSimpleVT().SimpleTy) {
9886   default:
9887     return false;
9888   case MVT::i8:
9889   case MVT::i16:
9890   case MVT::i32: {
9891     // Unaligned access can use (for example) LRDB, LRDH, LDR
9892     if (AllowsUnaligned) {
9893       if (Fast)
9894         *Fast = Subtarget->hasV7Ops();
9895       return true;
9896     }
9897     return false;
9898   }
9899   case MVT::f64:
9900   case MVT::v2f64: {
9901     // For any little-endian targets with neon, we can support unaligned ld/st
9902     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9903     // A big-endian target may also explicitly support unaligned accesses
9904     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9905       if (Fast)
9906         *Fast = true;
9907       return true;
9908     }
9909     return false;
9910   }
9911   }
9912 }
9913
9914 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9915                        unsigned AlignCheck) {
9916   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9917           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9918 }
9919
9920 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9921                                            unsigned DstAlign, unsigned SrcAlign,
9922                                            bool IsMemset, bool ZeroMemset,
9923                                            bool MemcpyStrSrc,
9924                                            MachineFunction &MF) const {
9925   const Function *F = MF.getFunction();
9926
9927   // See if we can use NEON instructions for this...
9928   if ((!IsMemset || ZeroMemset) &&
9929       Subtarget->hasNEON() &&
9930       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9931                                        Attribute::NoImplicitFloat)) {
9932     bool Fast;
9933     if (Size >= 16 &&
9934         (memOpAlign(SrcAlign, DstAlign, 16) ||
9935          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9936       return MVT::v2f64;
9937     } else if (Size >= 8 &&
9938                (memOpAlign(SrcAlign, DstAlign, 8) ||
9939                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9940                  Fast))) {
9941       return MVT::f64;
9942     }
9943   }
9944
9945   // Lowering to i32/i16 if the size permits.
9946   if (Size >= 4)
9947     return MVT::i32;
9948   else if (Size >= 2)
9949     return MVT::i16;
9950
9951   // Let the target-independent logic figure it out.
9952   return MVT::Other;
9953 }
9954
9955 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9956   if (Val.getOpcode() != ISD::LOAD)
9957     return false;
9958
9959   EVT VT1 = Val.getValueType();
9960   if (!VT1.isSimple() || !VT1.isInteger() ||
9961       !VT2.isSimple() || !VT2.isInteger())
9962     return false;
9963
9964   switch (VT1.getSimpleVT().SimpleTy) {
9965   default: break;
9966   case MVT::i1:
9967   case MVT::i8:
9968   case MVT::i16:
9969     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9970     return true;
9971   }
9972
9973   return false;
9974 }
9975
9976 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9977   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9978     return false;
9979
9980   if (!isTypeLegal(EVT::getEVT(Ty1)))
9981     return false;
9982
9983   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9984
9985   // Assuming the caller doesn't have a zeroext or signext return parameter,
9986   // truncation all the way down to i1 is valid.
9987   return true;
9988 }
9989
9990
9991 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9992   if (V < 0)
9993     return false;
9994
9995   unsigned Scale = 1;
9996   switch (VT.getSimpleVT().SimpleTy) {
9997   default: return false;
9998   case MVT::i1:
9999   case MVT::i8:
10000     // Scale == 1;
10001     break;
10002   case MVT::i16:
10003     // Scale == 2;
10004     Scale = 2;
10005     break;
10006   case MVT::i32:
10007     // Scale == 4;
10008     Scale = 4;
10009     break;
10010   }
10011
10012   if ((V & (Scale - 1)) != 0)
10013     return false;
10014   V /= Scale;
10015   return V == (V & ((1LL << 5) - 1));
10016 }
10017
10018 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10019                                       const ARMSubtarget *Subtarget) {
10020   bool isNeg = false;
10021   if (V < 0) {
10022     isNeg = true;
10023     V = - V;
10024   }
10025
10026   switch (VT.getSimpleVT().SimpleTy) {
10027   default: return false;
10028   case MVT::i1:
10029   case MVT::i8:
10030   case MVT::i16:
10031   case MVT::i32:
10032     // + imm12 or - imm8
10033     if (isNeg)
10034       return V == (V & ((1LL << 8) - 1));
10035     return V == (V & ((1LL << 12) - 1));
10036   case MVT::f32:
10037   case MVT::f64:
10038     // Same as ARM mode. FIXME: NEON?
10039     if (!Subtarget->hasVFP2())
10040       return false;
10041     if ((V & 3) != 0)
10042       return false;
10043     V >>= 2;
10044     return V == (V & ((1LL << 8) - 1));
10045   }
10046 }
10047
10048 /// isLegalAddressImmediate - Return true if the integer value can be used
10049 /// as the offset of the target addressing mode for load / store of the
10050 /// given type.
10051 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10052                                     const ARMSubtarget *Subtarget) {
10053   if (V == 0)
10054     return true;
10055
10056   if (!VT.isSimple())
10057     return false;
10058
10059   if (Subtarget->isThumb1Only())
10060     return isLegalT1AddressImmediate(V, VT);
10061   else if (Subtarget->isThumb2())
10062     return isLegalT2AddressImmediate(V, VT, Subtarget);
10063
10064   // ARM mode.
10065   if (V < 0)
10066     V = - V;
10067   switch (VT.getSimpleVT().SimpleTy) {
10068   default: return false;
10069   case MVT::i1:
10070   case MVT::i8:
10071   case MVT::i32:
10072     // +- imm12
10073     return V == (V & ((1LL << 12) - 1));
10074   case MVT::i16:
10075     // +- imm8
10076     return V == (V & ((1LL << 8) - 1));
10077   case MVT::f32:
10078   case MVT::f64:
10079     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10080       return false;
10081     if ((V & 3) != 0)
10082       return false;
10083     V >>= 2;
10084     return V == (V & ((1LL << 8) - 1));
10085   }
10086 }
10087
10088 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10089                                                       EVT VT) const {
10090   int Scale = AM.Scale;
10091   if (Scale < 0)
10092     return false;
10093
10094   switch (VT.getSimpleVT().SimpleTy) {
10095   default: return false;
10096   case MVT::i1:
10097   case MVT::i8:
10098   case MVT::i16:
10099   case MVT::i32:
10100     if (Scale == 1)
10101       return true;
10102     // r + r << imm
10103     Scale = Scale & ~1;
10104     return Scale == 2 || Scale == 4 || Scale == 8;
10105   case MVT::i64:
10106     // r + r
10107     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10108       return true;
10109     return false;
10110   case MVT::isVoid:
10111     // Note, we allow "void" uses (basically, uses that aren't loads or
10112     // stores), because arm allows folding a scale into many arithmetic
10113     // operations.  This should be made more precise and revisited later.
10114
10115     // Allow r << imm, but the imm has to be a multiple of two.
10116     if (Scale & 1) return false;
10117     return isPowerOf2_32(Scale);
10118   }
10119 }
10120
10121 /// isLegalAddressingMode - Return true if the addressing mode represented
10122 /// by AM is legal for this target, for a load/store of the specified type.
10123 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10124                                               Type *Ty) const {
10125   EVT VT = getValueType(Ty, true);
10126   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10127     return false;
10128
10129   // Can never fold addr of global into load/store.
10130   if (AM.BaseGV)
10131     return false;
10132
10133   switch (AM.Scale) {
10134   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10135     break;
10136   case 1:
10137     if (Subtarget->isThumb1Only())
10138       return false;
10139     // FALL THROUGH.
10140   default:
10141     // ARM doesn't support any R+R*scale+imm addr modes.
10142     if (AM.BaseOffs)
10143       return false;
10144
10145     if (!VT.isSimple())
10146       return false;
10147
10148     if (Subtarget->isThumb2())
10149       return isLegalT2ScaledAddressingMode(AM, VT);
10150
10151     int Scale = AM.Scale;
10152     switch (VT.getSimpleVT().SimpleTy) {
10153     default: return false;
10154     case MVT::i1:
10155     case MVT::i8:
10156     case MVT::i32:
10157       if (Scale < 0) Scale = -Scale;
10158       if (Scale == 1)
10159         return true;
10160       // r + r << imm
10161       return isPowerOf2_32(Scale & ~1);
10162     case MVT::i16:
10163     case MVT::i64:
10164       // r + r
10165       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10166         return true;
10167       return false;
10168
10169     case MVT::isVoid:
10170       // Note, we allow "void" uses (basically, uses that aren't loads or
10171       // stores), because arm allows folding a scale into many arithmetic
10172       // operations.  This should be made more precise and revisited later.
10173
10174       // Allow r << imm, but the imm has to be a multiple of two.
10175       if (Scale & 1) return false;
10176       return isPowerOf2_32(Scale);
10177     }
10178   }
10179   return true;
10180 }
10181
10182 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10183 /// icmp immediate, that is the target has icmp instructions which can compare
10184 /// a register against the immediate without having to materialize the
10185 /// immediate into a register.
10186 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10187   // Thumb2 and ARM modes can use cmn for negative immediates.
10188   if (!Subtarget->isThumb())
10189     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10190   if (Subtarget->isThumb2())
10191     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10192   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10193   return Imm >= 0 && Imm <= 255;
10194 }
10195
10196 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10197 /// *or sub* immediate, that is the target has add or sub instructions which can
10198 /// add a register with the immediate without having to materialize the
10199 /// immediate into a register.
10200 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10201   // Same encoding for add/sub, just flip the sign.
10202   int64_t AbsImm = llvm::abs64(Imm);
10203   if (!Subtarget->isThumb())
10204     return ARM_AM::getSOImmVal(AbsImm) != -1;
10205   if (Subtarget->isThumb2())
10206     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10207   // Thumb1 only has 8-bit unsigned immediate.
10208   return AbsImm >= 0 && AbsImm <= 255;
10209 }
10210
10211 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10212                                       bool isSEXTLoad, SDValue &Base,
10213                                       SDValue &Offset, bool &isInc,
10214                                       SelectionDAG &DAG) {
10215   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10216     return false;
10217
10218   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10219     // AddressingMode 3
10220     Base = Ptr->getOperand(0);
10221     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10222       int RHSC = (int)RHS->getZExtValue();
10223       if (RHSC < 0 && RHSC > -256) {
10224         assert(Ptr->getOpcode() == ISD::ADD);
10225         isInc = false;
10226         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10227         return true;
10228       }
10229     }
10230     isInc = (Ptr->getOpcode() == ISD::ADD);
10231     Offset = Ptr->getOperand(1);
10232     return true;
10233   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10234     // AddressingMode 2
10235     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10236       int RHSC = (int)RHS->getZExtValue();
10237       if (RHSC < 0 && RHSC > -0x1000) {
10238         assert(Ptr->getOpcode() == ISD::ADD);
10239         isInc = false;
10240         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10241         Base = Ptr->getOperand(0);
10242         return true;
10243       }
10244     }
10245
10246     if (Ptr->getOpcode() == ISD::ADD) {
10247       isInc = true;
10248       ARM_AM::ShiftOpc ShOpcVal=
10249         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10250       if (ShOpcVal != ARM_AM::no_shift) {
10251         Base = Ptr->getOperand(1);
10252         Offset = Ptr->getOperand(0);
10253       } else {
10254         Base = Ptr->getOperand(0);
10255         Offset = Ptr->getOperand(1);
10256       }
10257       return true;
10258     }
10259
10260     isInc = (Ptr->getOpcode() == ISD::ADD);
10261     Base = Ptr->getOperand(0);
10262     Offset = Ptr->getOperand(1);
10263     return true;
10264   }
10265
10266   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10267   return false;
10268 }
10269
10270 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10271                                      bool isSEXTLoad, SDValue &Base,
10272                                      SDValue &Offset, bool &isInc,
10273                                      SelectionDAG &DAG) {
10274   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10275     return false;
10276
10277   Base = Ptr->getOperand(0);
10278   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10279     int RHSC = (int)RHS->getZExtValue();
10280     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10281       assert(Ptr->getOpcode() == ISD::ADD);
10282       isInc = false;
10283       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10284       return true;
10285     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10286       isInc = Ptr->getOpcode() == ISD::ADD;
10287       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10288       return true;
10289     }
10290   }
10291
10292   return false;
10293 }
10294
10295 /// getPreIndexedAddressParts - returns true by value, base pointer and
10296 /// offset pointer and addressing mode by reference if the node's address
10297 /// can be legally represented as pre-indexed load / store address.
10298 bool
10299 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10300                                              SDValue &Offset,
10301                                              ISD::MemIndexedMode &AM,
10302                                              SelectionDAG &DAG) const {
10303   if (Subtarget->isThumb1Only())
10304     return false;
10305
10306   EVT VT;
10307   SDValue Ptr;
10308   bool isSEXTLoad = false;
10309   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10310     Ptr = LD->getBasePtr();
10311     VT  = LD->getMemoryVT();
10312     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10313   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10314     Ptr = ST->getBasePtr();
10315     VT  = ST->getMemoryVT();
10316   } else
10317     return false;
10318
10319   bool isInc;
10320   bool isLegal = false;
10321   if (Subtarget->isThumb2())
10322     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10323                                        Offset, isInc, DAG);
10324   else
10325     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10326                                         Offset, isInc, DAG);
10327   if (!isLegal)
10328     return false;
10329
10330   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10331   return true;
10332 }
10333
10334 /// getPostIndexedAddressParts - returns true by value, base pointer and
10335 /// offset pointer and addressing mode by reference if this node can be
10336 /// combined with a load / store to form a post-indexed load / store.
10337 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10338                                                    SDValue &Base,
10339                                                    SDValue &Offset,
10340                                                    ISD::MemIndexedMode &AM,
10341                                                    SelectionDAG &DAG) const {
10342   if (Subtarget->isThumb1Only())
10343     return false;
10344
10345   EVT VT;
10346   SDValue Ptr;
10347   bool isSEXTLoad = false;
10348   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10349     VT  = LD->getMemoryVT();
10350     Ptr = LD->getBasePtr();
10351     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10352   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10353     VT  = ST->getMemoryVT();
10354     Ptr = ST->getBasePtr();
10355   } else
10356     return false;
10357
10358   bool isInc;
10359   bool isLegal = false;
10360   if (Subtarget->isThumb2())
10361     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10362                                        isInc, DAG);
10363   else
10364     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10365                                         isInc, DAG);
10366   if (!isLegal)
10367     return false;
10368
10369   if (Ptr != Base) {
10370     // Swap base ptr and offset to catch more post-index load / store when
10371     // it's legal. In Thumb2 mode, offset must be an immediate.
10372     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10373         !Subtarget->isThumb2())
10374       std::swap(Base, Offset);
10375
10376     // Post-indexed load / store update the base pointer.
10377     if (Ptr != Base)
10378       return false;
10379   }
10380
10381   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10382   return true;
10383 }
10384
10385 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10386                                                       APInt &KnownZero,
10387                                                       APInt &KnownOne,
10388                                                       const SelectionDAG &DAG,
10389                                                       unsigned Depth) const {
10390   unsigned BitWidth = KnownOne.getBitWidth();
10391   KnownZero = KnownOne = APInt(BitWidth, 0);
10392   switch (Op.getOpcode()) {
10393   default: break;
10394   case ARMISD::ADDC:
10395   case ARMISD::ADDE:
10396   case ARMISD::SUBC:
10397   case ARMISD::SUBE:
10398     // These nodes' second result is a boolean
10399     if (Op.getResNo() == 0)
10400       break;
10401     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10402     break;
10403   case ARMISD::CMOV: {
10404     // Bits are known zero/one if known on the LHS and RHS.
10405     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10406     if (KnownZero == 0 && KnownOne == 0) return;
10407
10408     APInt KnownZeroRHS, KnownOneRHS;
10409     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10410     KnownZero &= KnownZeroRHS;
10411     KnownOne  &= KnownOneRHS;
10412     return;
10413   }
10414   case ISD::INTRINSIC_W_CHAIN: {
10415     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10416     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10417     switch (IntID) {
10418     default: return;
10419     case Intrinsic::arm_ldaex:
10420     case Intrinsic::arm_ldrex: {
10421       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10422       unsigned MemBits = VT.getScalarType().getSizeInBits();
10423       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10424       return;
10425     }
10426     }
10427   }
10428   }
10429 }
10430
10431 //===----------------------------------------------------------------------===//
10432 //                           ARM Inline Assembly Support
10433 //===----------------------------------------------------------------------===//
10434
10435 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10436   // Looking for "rev" which is V6+.
10437   if (!Subtarget->hasV6Ops())
10438     return false;
10439
10440   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10441   std::string AsmStr = IA->getAsmString();
10442   SmallVector<StringRef, 4> AsmPieces;
10443   SplitString(AsmStr, AsmPieces, ";\n");
10444
10445   switch (AsmPieces.size()) {
10446   default: return false;
10447   case 1:
10448     AsmStr = AsmPieces[0];
10449     AsmPieces.clear();
10450     SplitString(AsmStr, AsmPieces, " \t,");
10451
10452     // rev $0, $1
10453     if (AsmPieces.size() == 3 &&
10454         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10455         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10456       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10457       if (Ty && Ty->getBitWidth() == 32)
10458         return IntrinsicLowering::LowerToByteSwap(CI);
10459     }
10460     break;
10461   }
10462
10463   return false;
10464 }
10465
10466 /// getConstraintType - Given a constraint letter, return the type of
10467 /// constraint it is for this target.
10468 ARMTargetLowering::ConstraintType
10469 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10470   if (Constraint.size() == 1) {
10471     switch (Constraint[0]) {
10472     default:  break;
10473     case 'l': return C_RegisterClass;
10474     case 'w': return C_RegisterClass;
10475     case 'h': return C_RegisterClass;
10476     case 'x': return C_RegisterClass;
10477     case 't': return C_RegisterClass;
10478     case 'j': return C_Other; // Constant for movw.
10479       // An address with a single base register. Due to the way we
10480       // currently handle addresses it is the same as an 'r' memory constraint.
10481     case 'Q': return C_Memory;
10482     }
10483   } else if (Constraint.size() == 2) {
10484     switch (Constraint[0]) {
10485     default: break;
10486     // All 'U+' constraints are addresses.
10487     case 'U': return C_Memory;
10488     }
10489   }
10490   return TargetLowering::getConstraintType(Constraint);
10491 }
10492
10493 /// Examine constraint type and operand type and determine a weight value.
10494 /// This object must already have been set up with the operand type
10495 /// and the current alternative constraint selected.
10496 TargetLowering::ConstraintWeight
10497 ARMTargetLowering::getSingleConstraintMatchWeight(
10498     AsmOperandInfo &info, const char *constraint) const {
10499   ConstraintWeight weight = CW_Invalid;
10500   Value *CallOperandVal = info.CallOperandVal;
10501     // If we don't have a value, we can't do a match,
10502     // but allow it at the lowest weight.
10503   if (!CallOperandVal)
10504     return CW_Default;
10505   Type *type = CallOperandVal->getType();
10506   // Look at the constraint type.
10507   switch (*constraint) {
10508   default:
10509     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10510     break;
10511   case 'l':
10512     if (type->isIntegerTy()) {
10513       if (Subtarget->isThumb())
10514         weight = CW_SpecificReg;
10515       else
10516         weight = CW_Register;
10517     }
10518     break;
10519   case 'w':
10520     if (type->isFloatingPointTy())
10521       weight = CW_Register;
10522     break;
10523   }
10524   return weight;
10525 }
10526
10527 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10528 RCPair
10529 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10530                                                 MVT VT) const {
10531   if (Constraint.size() == 1) {
10532     // GCC ARM Constraint Letters
10533     switch (Constraint[0]) {
10534     case 'l': // Low regs or general regs.
10535       if (Subtarget->isThumb())
10536         return RCPair(0U, &ARM::tGPRRegClass);
10537       return RCPair(0U, &ARM::GPRRegClass);
10538     case 'h': // High regs or no regs.
10539       if (Subtarget->isThumb())
10540         return RCPair(0U, &ARM::hGPRRegClass);
10541       break;
10542     case 'r':
10543       return RCPair(0U, &ARM::GPRRegClass);
10544     case 'w':
10545       if (VT == MVT::Other)
10546         break;
10547       if (VT == MVT::f32)
10548         return RCPair(0U, &ARM::SPRRegClass);
10549       if (VT.getSizeInBits() == 64)
10550         return RCPair(0U, &ARM::DPRRegClass);
10551       if (VT.getSizeInBits() == 128)
10552         return RCPair(0U, &ARM::QPRRegClass);
10553       break;
10554     case 'x':
10555       if (VT == MVT::Other)
10556         break;
10557       if (VT == MVT::f32)
10558         return RCPair(0U, &ARM::SPR_8RegClass);
10559       if (VT.getSizeInBits() == 64)
10560         return RCPair(0U, &ARM::DPR_8RegClass);
10561       if (VT.getSizeInBits() == 128)
10562         return RCPair(0U, &ARM::QPR_8RegClass);
10563       break;
10564     case 't':
10565       if (VT == MVT::f32)
10566         return RCPair(0U, &ARM::SPRRegClass);
10567       break;
10568     }
10569   }
10570   if (StringRef("{cc}").equals_lower(Constraint))
10571     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10572
10573   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10574 }
10575
10576 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10577 /// vector.  If it is invalid, don't add anything to Ops.
10578 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10579                                                      std::string &Constraint,
10580                                                      std::vector<SDValue>&Ops,
10581                                                      SelectionDAG &DAG) const {
10582   SDValue Result;
10583
10584   // Currently only support length 1 constraints.
10585   if (Constraint.length() != 1) return;
10586
10587   char ConstraintLetter = Constraint[0];
10588   switch (ConstraintLetter) {
10589   default: break;
10590   case 'j':
10591   case 'I': case 'J': case 'K': case 'L':
10592   case 'M': case 'N': case 'O':
10593     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10594     if (!C)
10595       return;
10596
10597     int64_t CVal64 = C->getSExtValue();
10598     int CVal = (int) CVal64;
10599     // None of these constraints allow values larger than 32 bits.  Check
10600     // that the value fits in an int.
10601     if (CVal != CVal64)
10602       return;
10603
10604     switch (ConstraintLetter) {
10605       case 'j':
10606         // Constant suitable for movw, must be between 0 and
10607         // 65535.
10608         if (Subtarget->hasV6T2Ops())
10609           if (CVal >= 0 && CVal <= 65535)
10610             break;
10611         return;
10612       case 'I':
10613         if (Subtarget->isThumb1Only()) {
10614           // This must be a constant between 0 and 255, for ADD
10615           // immediates.
10616           if (CVal >= 0 && CVal <= 255)
10617             break;
10618         } else if (Subtarget->isThumb2()) {
10619           // A constant that can be used as an immediate value in a
10620           // data-processing instruction.
10621           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10622             break;
10623         } else {
10624           // A constant that can be used as an immediate value in a
10625           // data-processing instruction.
10626           if (ARM_AM::getSOImmVal(CVal) != -1)
10627             break;
10628         }
10629         return;
10630
10631       case 'J':
10632         if (Subtarget->isThumb()) {  // FIXME thumb2
10633           // This must be a constant between -255 and -1, for negated ADD
10634           // immediates. This can be used in GCC with an "n" modifier that
10635           // prints the negated value, for use with SUB instructions. It is
10636           // not useful otherwise but is implemented for compatibility.
10637           if (CVal >= -255 && CVal <= -1)
10638             break;
10639         } else {
10640           // This must be a constant between -4095 and 4095. It is not clear
10641           // what this constraint is intended for. Implemented for
10642           // compatibility with GCC.
10643           if (CVal >= -4095 && CVal <= 4095)
10644             break;
10645         }
10646         return;
10647
10648       case 'K':
10649         if (Subtarget->isThumb1Only()) {
10650           // A 32-bit value where only one byte has a nonzero value. Exclude
10651           // zero to match GCC. This constraint is used by GCC internally for
10652           // constants that can be loaded with a move/shift combination.
10653           // It is not useful otherwise but is implemented for compatibility.
10654           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10655             break;
10656         } else if (Subtarget->isThumb2()) {
10657           // A constant whose bitwise inverse can be used as an immediate
10658           // value in a data-processing instruction. This can be used in GCC
10659           // with a "B" modifier that prints the inverted value, for use with
10660           // BIC and MVN instructions. It is not useful otherwise but is
10661           // implemented for compatibility.
10662           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10663             break;
10664         } else {
10665           // A constant whose bitwise inverse can be used as an immediate
10666           // value in a data-processing instruction. This can be used in GCC
10667           // with a "B" modifier that prints the inverted value, for use with
10668           // BIC and MVN instructions. It is not useful otherwise but is
10669           // implemented for compatibility.
10670           if (ARM_AM::getSOImmVal(~CVal) != -1)
10671             break;
10672         }
10673         return;
10674
10675       case 'L':
10676         if (Subtarget->isThumb1Only()) {
10677           // This must be a constant between -7 and 7,
10678           // for 3-operand ADD/SUB immediate instructions.
10679           if (CVal >= -7 && CVal < 7)
10680             break;
10681         } else if (Subtarget->isThumb2()) {
10682           // A constant whose negation can be used as an immediate value in a
10683           // data-processing instruction. This can be used in GCC with an "n"
10684           // modifier that prints the negated value, for use with SUB
10685           // instructions. It is not useful otherwise but is implemented for
10686           // compatibility.
10687           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10688             break;
10689         } else {
10690           // A constant whose negation can be used as an immediate value in a
10691           // data-processing instruction. This can be used in GCC with an "n"
10692           // modifier that prints the negated value, for use with SUB
10693           // instructions. It is not useful otherwise but is implemented for
10694           // compatibility.
10695           if (ARM_AM::getSOImmVal(-CVal) != -1)
10696             break;
10697         }
10698         return;
10699
10700       case 'M':
10701         if (Subtarget->isThumb()) { // FIXME thumb2
10702           // This must be a multiple of 4 between 0 and 1020, for
10703           // ADD sp + immediate.
10704           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10705             break;
10706         } else {
10707           // A power of two or a constant between 0 and 32.  This is used in
10708           // GCC for the shift amount on shifted register operands, but it is
10709           // useful in general for any shift amounts.
10710           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10711             break;
10712         }
10713         return;
10714
10715       case 'N':
10716         if (Subtarget->isThumb()) {  // FIXME thumb2
10717           // This must be a constant between 0 and 31, for shift amounts.
10718           if (CVal >= 0 && CVal <= 31)
10719             break;
10720         }
10721         return;
10722
10723       case 'O':
10724         if (Subtarget->isThumb()) {  // FIXME thumb2
10725           // This must be a multiple of 4 between -508 and 508, for
10726           // ADD/SUB sp = sp + immediate.
10727           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10728             break;
10729         }
10730         return;
10731     }
10732     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10733     break;
10734   }
10735
10736   if (Result.getNode()) {
10737     Ops.push_back(Result);
10738     return;
10739   }
10740   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10741 }
10742
10743 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10744   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10745   unsigned Opcode = Op->getOpcode();
10746   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10747          "Invalid opcode for Div/Rem lowering");
10748   bool isSigned = (Opcode == ISD::SDIVREM);
10749   EVT VT = Op->getValueType(0);
10750   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10751
10752   RTLIB::Libcall LC;
10753   switch (VT.getSimpleVT().SimpleTy) {
10754   default: llvm_unreachable("Unexpected request for libcall!");
10755   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10756   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10757   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10758   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10759   }
10760
10761   SDValue InChain = DAG.getEntryNode();
10762
10763   TargetLowering::ArgListTy Args;
10764   TargetLowering::ArgListEntry Entry;
10765   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10766     EVT ArgVT = Op->getOperand(i).getValueType();
10767     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10768     Entry.Node = Op->getOperand(i);
10769     Entry.Ty = ArgTy;
10770     Entry.isSExt = isSigned;
10771     Entry.isZExt = !isSigned;
10772     Args.push_back(Entry);
10773   }
10774
10775   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10776                                          getPointerTy());
10777
10778   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10779
10780   SDLoc dl(Op);
10781   TargetLowering::CallLoweringInfo CLI(DAG);
10782   CLI.setDebugLoc(dl).setChain(InChain)
10783     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10784     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10785
10786   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10787   return CallInfo.first;
10788 }
10789
10790 SDValue
10791 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10792   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10793   SDLoc DL(Op);
10794
10795   // Get the inputs.
10796   SDValue Chain = Op.getOperand(0);
10797   SDValue Size  = Op.getOperand(1);
10798
10799   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10800                               DAG.getConstant(2, MVT::i32));
10801
10802   SDValue Flag;
10803   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10804   Flag = Chain.getValue(1);
10805
10806   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10807   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10808
10809   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10810   Chain = NewSP.getValue(1);
10811
10812   SDValue Ops[2] = { NewSP, Chain };
10813   return DAG.getMergeValues(Ops, DL);
10814 }
10815
10816 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10817   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10818          "Unexpected type for custom-lowering FP_EXTEND");
10819
10820   RTLIB::Libcall LC;
10821   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10822
10823   SDValue SrcVal = Op.getOperand(0);
10824   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10825                      /*isSigned*/ false, SDLoc(Op)).first;
10826 }
10827
10828 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10829   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10830          Subtarget->isFPOnlySP() &&
10831          "Unexpected type for custom-lowering FP_ROUND");
10832
10833   RTLIB::Libcall LC;
10834   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10835
10836   SDValue SrcVal = Op.getOperand(0);
10837   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10838                      /*isSigned*/ false, SDLoc(Op)).first;
10839 }
10840
10841 bool
10842 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10843   // The ARM target isn't yet aware of offsets.
10844   return false;
10845 }
10846
10847 bool ARM::isBitFieldInvertedMask(unsigned v) {
10848   if (v == 0xffffffff)
10849     return false;
10850
10851   // there can be 1's on either or both "outsides", all the "inside"
10852   // bits must be 0's
10853   unsigned TO = CountTrailingOnes_32(v);
10854   unsigned LO = CountLeadingOnes_32(v);
10855   v = (v >> TO) << TO;
10856   v = (v << LO) >> LO;
10857   return v == 0;
10858 }
10859
10860 /// isFPImmLegal - Returns true if the target can instruction select the
10861 /// specified FP immediate natively. If false, the legalizer will
10862 /// materialize the FP immediate as a load from a constant pool.
10863 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10864   if (!Subtarget->hasVFP3())
10865     return false;
10866   if (VT == MVT::f32)
10867     return ARM_AM::getFP32Imm(Imm) != -1;
10868   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10869     return ARM_AM::getFP64Imm(Imm) != -1;
10870   return false;
10871 }
10872
10873 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10874 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10875 /// specified in the intrinsic calls.
10876 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10877                                            const CallInst &I,
10878                                            unsigned Intrinsic) const {
10879   switch (Intrinsic) {
10880   case Intrinsic::arm_neon_vld1:
10881   case Intrinsic::arm_neon_vld2:
10882   case Intrinsic::arm_neon_vld3:
10883   case Intrinsic::arm_neon_vld4:
10884   case Intrinsic::arm_neon_vld2lane:
10885   case Intrinsic::arm_neon_vld3lane:
10886   case Intrinsic::arm_neon_vld4lane: {
10887     Info.opc = ISD::INTRINSIC_W_CHAIN;
10888     // Conservatively set memVT to the entire set of vectors loaded.
10889     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10890     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10891     Info.ptrVal = I.getArgOperand(0);
10892     Info.offset = 0;
10893     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10894     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10895     Info.vol = false; // volatile loads with NEON intrinsics not supported
10896     Info.readMem = true;
10897     Info.writeMem = false;
10898     return true;
10899   }
10900   case Intrinsic::arm_neon_vst1:
10901   case Intrinsic::arm_neon_vst2:
10902   case Intrinsic::arm_neon_vst3:
10903   case Intrinsic::arm_neon_vst4:
10904   case Intrinsic::arm_neon_vst2lane:
10905   case Intrinsic::arm_neon_vst3lane:
10906   case Intrinsic::arm_neon_vst4lane: {
10907     Info.opc = ISD::INTRINSIC_VOID;
10908     // Conservatively set memVT to the entire set of vectors stored.
10909     unsigned NumElts = 0;
10910     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10911       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10912       if (!ArgTy->isVectorTy())
10913         break;
10914       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10915     }
10916     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10917     Info.ptrVal = I.getArgOperand(0);
10918     Info.offset = 0;
10919     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10920     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10921     Info.vol = false; // volatile stores with NEON intrinsics not supported
10922     Info.readMem = false;
10923     Info.writeMem = true;
10924     return true;
10925   }
10926   case Intrinsic::arm_ldaex:
10927   case Intrinsic::arm_ldrex: {
10928     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10929     Info.opc = ISD::INTRINSIC_W_CHAIN;
10930     Info.memVT = MVT::getVT(PtrTy->getElementType());
10931     Info.ptrVal = I.getArgOperand(0);
10932     Info.offset = 0;
10933     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10934     Info.vol = true;
10935     Info.readMem = true;
10936     Info.writeMem = false;
10937     return true;
10938   }
10939   case Intrinsic::arm_stlex:
10940   case Intrinsic::arm_strex: {
10941     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10942     Info.opc = ISD::INTRINSIC_W_CHAIN;
10943     Info.memVT = MVT::getVT(PtrTy->getElementType());
10944     Info.ptrVal = I.getArgOperand(1);
10945     Info.offset = 0;
10946     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10947     Info.vol = true;
10948     Info.readMem = false;
10949     Info.writeMem = true;
10950     return true;
10951   }
10952   case Intrinsic::arm_stlexd:
10953   case Intrinsic::arm_strexd: {
10954     Info.opc = ISD::INTRINSIC_W_CHAIN;
10955     Info.memVT = MVT::i64;
10956     Info.ptrVal = I.getArgOperand(2);
10957     Info.offset = 0;
10958     Info.align = 8;
10959     Info.vol = true;
10960     Info.readMem = false;
10961     Info.writeMem = true;
10962     return true;
10963   }
10964   case Intrinsic::arm_ldaexd:
10965   case Intrinsic::arm_ldrexd: {
10966     Info.opc = ISD::INTRINSIC_W_CHAIN;
10967     Info.memVT = MVT::i64;
10968     Info.ptrVal = I.getArgOperand(0);
10969     Info.offset = 0;
10970     Info.align = 8;
10971     Info.vol = true;
10972     Info.readMem = true;
10973     Info.writeMem = false;
10974     return true;
10975   }
10976   default:
10977     break;
10978   }
10979
10980   return false;
10981 }
10982
10983 /// \brief Returns true if it is beneficial to convert a load of a constant
10984 /// to just the constant itself.
10985 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10986                                                           Type *Ty) const {
10987   assert(Ty->isIntegerTy());
10988
10989   unsigned Bits = Ty->getPrimitiveSizeInBits();
10990   if (Bits == 0 || Bits > 32)
10991     return false;
10992   return true;
10993 }
10994
10995 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
10996
10997 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
10998                                         ARM_MB::MemBOpt Domain) const {
10999   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11000
11001   // First, if the target has no DMB, see what fallback we can use.
11002   if (!Subtarget->hasDataBarrier()) {
11003     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11004     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11005     // here.
11006     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11007       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11008       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11009                         Builder.getInt32(0), Builder.getInt32(7),
11010                         Builder.getInt32(10), Builder.getInt32(5)};
11011       return Builder.CreateCall(MCR, args);
11012     } else {
11013       // Instead of using barriers, atomic accesses on these subtargets use
11014       // libcalls.
11015       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11016     }
11017   } else {
11018     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11019     // Only a full system barrier exists in the M-class architectures.
11020     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11021     Constant *CDomain = Builder.getInt32(Domain);
11022     return Builder.CreateCall(DMB, CDomain);
11023   }
11024 }
11025
11026 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11027 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11028                                          AtomicOrdering Ord, bool IsStore,
11029                                          bool IsLoad) const {
11030   if (!getInsertFencesForAtomic())
11031     return nullptr;
11032
11033   switch (Ord) {
11034   case NotAtomic:
11035   case Unordered:
11036     llvm_unreachable("Invalid fence: unordered/non-atomic");
11037   case Monotonic:
11038   case Acquire:
11039     return nullptr; // Nothing to do
11040   case SequentiallyConsistent:
11041     if (!IsStore)
11042       return nullptr; // Nothing to do
11043     /*FALLTHROUGH*/
11044   case Release:
11045   case AcquireRelease:
11046     if (Subtarget->isSwift())
11047       return makeDMB(Builder, ARM_MB::ISHST);
11048     // FIXME: add a comment with a link to documentation justifying this.
11049     else
11050       return makeDMB(Builder, ARM_MB::ISH);
11051   }
11052   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11053 }
11054
11055 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11056                                           AtomicOrdering Ord, bool IsStore,
11057                                           bool IsLoad) const {
11058   if (!getInsertFencesForAtomic())
11059     return nullptr;
11060
11061   switch (Ord) {
11062   case NotAtomic:
11063   case Unordered:
11064     llvm_unreachable("Invalid fence: unordered/not-atomic");
11065   case Monotonic:
11066   case Release:
11067     return nullptr; // Nothing to do
11068   case Acquire:
11069   case AcquireRelease:
11070   case SequentiallyConsistent:
11071     return makeDMB(Builder, ARM_MB::ISH);
11072   }
11073   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11074 }
11075
11076 // Loads and stores less than 64-bits are already atomic; ones above that
11077 // are doomed anyway, so defer to the default libcall and blame the OS when
11078 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11079 // anything for those.
11080 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11081   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11082   return (Size == 64) && !Subtarget->isMClass();
11083 }
11084
11085 // Loads and stores less than 64-bits are already atomic; ones above that
11086 // are doomed anyway, so defer to the default libcall and blame the OS when
11087 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11088 // anything for those.
11089 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11090 // guarantee, see DDI0406C ARM architecture reference manual,
11091 // sections A8.8.72-74 LDRD)
11092 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11093   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11094   return (Size == 64) && !Subtarget->isMClass();
11095 }
11096
11097 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11098 // and up to 64 bits on the non-M profiles
11099 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11100   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11101   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11102 }
11103
11104 // This has so far only been implemented for MachO.
11105 bool ARMTargetLowering::useLoadStackGuardNode() const {
11106   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11107 }
11108
11109 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11110                                          AtomicOrdering Ord) const {
11111   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11112   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11113   bool IsAcquire = isAtLeastAcquire(Ord);
11114
11115   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11116   // intrinsic must return {i32, i32} and we have to recombine them into a
11117   // single i64 here.
11118   if (ValTy->getPrimitiveSizeInBits() == 64) {
11119     Intrinsic::ID Int =
11120         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11121     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11122
11123     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11124     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11125
11126     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11127     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11128     if (!Subtarget->isLittle())
11129       std::swap (Lo, Hi);
11130     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11131     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11132     return Builder.CreateOr(
11133         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11134   }
11135
11136   Type *Tys[] = { Addr->getType() };
11137   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11138   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11139
11140   return Builder.CreateTruncOrBitCast(
11141       Builder.CreateCall(Ldrex, Addr),
11142       cast<PointerType>(Addr->getType())->getElementType());
11143 }
11144
11145 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11146                                                Value *Addr,
11147                                                AtomicOrdering Ord) const {
11148   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11149   bool IsRelease = isAtLeastRelease(Ord);
11150
11151   // Since the intrinsics must have legal type, the i64 intrinsics take two
11152   // parameters: "i32, i32". We must marshal Val into the appropriate form
11153   // before the call.
11154   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11155     Intrinsic::ID Int =
11156         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11157     Function *Strex = Intrinsic::getDeclaration(M, Int);
11158     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11159
11160     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11161     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11162     if (!Subtarget->isLittle())
11163       std::swap (Lo, Hi);
11164     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11165     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11166   }
11167
11168   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11169   Type *Tys[] = { Addr->getType() };
11170   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11171
11172   return Builder.CreateCall2(
11173       Strex, Builder.CreateZExtOrBitCast(
11174                  Val, Strex->getFunctionType()->getParamType(0)),
11175       Addr);
11176 }
11177
11178 enum HABaseType {
11179   HA_UNKNOWN = 0,
11180   HA_FLOAT,
11181   HA_DOUBLE,
11182   HA_VECT64,
11183   HA_VECT128
11184 };
11185
11186 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11187                                    uint64_t &Members) {
11188   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11189     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11190       uint64_t SubMembers = 0;
11191       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11192         return false;
11193       Members += SubMembers;
11194     }
11195   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11196     uint64_t SubMembers = 0;
11197     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11198       return false;
11199     Members += SubMembers * AT->getNumElements();
11200   } else if (Ty->isFloatTy()) {
11201     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11202       return false;
11203     Members = 1;
11204     Base = HA_FLOAT;
11205   } else if (Ty->isDoubleTy()) {
11206     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11207       return false;
11208     Members = 1;
11209     Base = HA_DOUBLE;
11210   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11211     Members = 1;
11212     switch (Base) {
11213     case HA_FLOAT:
11214     case HA_DOUBLE:
11215       return false;
11216     case HA_VECT64:
11217       return VT->getBitWidth() == 64;
11218     case HA_VECT128:
11219       return VT->getBitWidth() == 128;
11220     case HA_UNKNOWN:
11221       switch (VT->getBitWidth()) {
11222       case 64:
11223         Base = HA_VECT64;
11224         return true;
11225       case 128:
11226         Base = HA_VECT128;
11227         return true;
11228       default:
11229         return false;
11230       }
11231     }
11232   }
11233
11234   return (Members > 0 && Members <= 4);
11235 }
11236
11237 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11238 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11239     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11240   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11241       CallingConv::ARM_AAPCS_VFP)
11242     return false;
11243
11244   HABaseType Base = HA_UNKNOWN;
11245   uint64_t Members = 0;
11246   bool result = isHomogeneousAggregate(Ty, Base, Members);
11247   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11248   return result;
11249 }