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 "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSelectionDAGInfo.h"
24 #include "ARMSubtarget.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "MCTargetDesc/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/MachineValueType.h"
56 #include "llvm/CodeGen/RuntimeLibcalls.h"
57 #include "llvm/CodeGen/SelectionDAG.h"
58 #include "llvm/CodeGen/SelectionDAGNodes.h"
59 #include "llvm/CodeGen/ValueTypes.h"
60 #include "llvm/IR/Attributes.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/Constants.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugLoc.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GlobalAlias.h"
70 #include "llvm/IR/GlobalValue.h"
71 #include "llvm/IR/GlobalVariable.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/Instruction.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/User.h"
81 #include "llvm/IR/Value.h"
82 #include "llvm/MC/MCInstrDesc.h"
83 #include "llvm/MC/MCInstrItineraries.h"
84 #include "llvm/MC/MCRegisterInfo.h"
85 #include "llvm/MC/MCSchedule.h"
86 #include "llvm/Support/AtomicOrdering.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CodeGen.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Compiler.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/ErrorHandling.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetInstrInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
99 #include <algorithm>
100 #include <cassert>
101 #include <cstdint>
102 #include <cstdlib>
103 #include <iterator>
104 #include <limits>
105 #include <tuple>
106 #include <string>
107 #include <utility>
108 #include <vector>
109 
110 using namespace llvm;
111 
112 #define DEBUG_TYPE "arm-isel"
113 
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
116 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
117 STATISTIC(NumConstpoolPromoted,
118   "Number of constants with their storage promoted into constant pools");
119 
120 static cl::opt<bool>
121 ARMInterworking("arm-interworking", cl::Hidden,
122   cl::desc("Enable / disable ARM interworking (for debugging only)"),
123   cl::init(true));
124 
125 static cl::opt<bool> EnableConstpoolPromotion(
126     "arm-promote-constant", cl::Hidden,
127     cl::desc("Enable / disable promotion of unnamed_addr constants into "
128              "constant pools"),
129     cl::init(true));
130 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
131     "arm-promote-constant-max-size", cl::Hidden,
132     cl::desc("Maximum size of constant to promote into a constant pool"),
133     cl::init(64));
134 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
135     "arm-promote-constant-max-total", cl::Hidden,
136     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
137     cl::init(128));
138 
139 // The APCS parameter registers.
140 static const MCPhysReg GPRArgRegs[] = {
141   ARM::R0, ARM::R1, ARM::R2, ARM::R3
142 };
143 
144 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
145                                        MVT PromotedBitwiseVT) {
146   if (VT != PromotedLdStVT) {
147     setOperationAction(ISD::LOAD, VT, Promote);
148     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
149 
150     setOperationAction(ISD::STORE, VT, Promote);
151     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
152   }
153 
154   MVT ElemTy = VT.getVectorElementType();
155   if (ElemTy != MVT::f64)
156     setOperationAction(ISD::SETCC, VT, Custom);
157   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
158   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
159   if (ElemTy == MVT::i32) {
160     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
161     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
162     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
163     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
164   } else {
165     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
166     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
167     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
168     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
169   }
170   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
171   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
172   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
173   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
174   setOperationAction(ISD::SELECT,            VT, Expand);
175   setOperationAction(ISD::SELECT_CC,         VT, Expand);
176   setOperationAction(ISD::VSELECT,           VT, Expand);
177   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
178   if (VT.isInteger()) {
179     setOperationAction(ISD::SHL, VT, Custom);
180     setOperationAction(ISD::SRA, VT, Custom);
181     setOperationAction(ISD::SRL, VT, Custom);
182   }
183 
184   // Promote all bit-wise operations.
185   if (VT.isInteger() && VT != PromotedBitwiseVT) {
186     setOperationAction(ISD::AND, VT, Promote);
187     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
188     setOperationAction(ISD::OR,  VT, Promote);
189     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
190     setOperationAction(ISD::XOR, VT, Promote);
191     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
192   }
193 
194   // Neon does not support vector divide/remainder operations.
195   setOperationAction(ISD::SDIV, VT, Expand);
196   setOperationAction(ISD::UDIV, VT, Expand);
197   setOperationAction(ISD::FDIV, VT, Expand);
198   setOperationAction(ISD::SREM, VT, Expand);
199   setOperationAction(ISD::UREM, VT, Expand);
200   setOperationAction(ISD::FREM, VT, Expand);
201 
202   if (!VT.isFloatingPoint() &&
203       VT != MVT::v2i64 && VT != MVT::v1i64)
204     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
205       setOperationAction(Opcode, VT, Legal);
206 }
207 
208 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
209   addRegisterClass(VT, &ARM::DPRRegClass);
210   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
211 }
212 
213 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
214   addRegisterClass(VT, &ARM::DPairRegClass);
215   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
216 }
217 
218 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
219                                      const ARMSubtarget &STI)
220     : TargetLowering(TM), Subtarget(&STI) {
221   RegInfo = Subtarget->getRegisterInfo();
222   Itins = Subtarget->getInstrItineraryData();
223 
224   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
225 
226   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
227       !Subtarget->isTargetWatchOS()) {
228     const auto &E = Subtarget->getTargetTriple().getEnvironment();
229 
230     bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
231                       E == Triple::MuslEABIHF;
232     // Windows is a special case.  Technically, we will replace all of the "GNU"
233     // calls with calls to MSVCRT if appropriate and adjust the calling
234     // convention then.
235     IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
236 
237     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
238       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
239                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
240                                        : CallingConv::ARM_AAPCS);
241   }
242 
243   if (Subtarget->isTargetMachO()) {
244     // Uses VFP for Thumb libfuncs if available.
245     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
246         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
247       static const struct {
248         const RTLIB::Libcall Op;
249         const char * const Name;
250         const ISD::CondCode Cond;
251       } LibraryCalls[] = {
252         // Single-precision floating-point arithmetic.
253         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
254         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
255         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
256         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
257 
258         // Double-precision floating-point arithmetic.
259         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
261         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
262         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
263 
264         // Single-precision comparisons.
265         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
266         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
267         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
268         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
269         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
270         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
271         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
272         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
273 
274         // Double-precision comparisons.
275         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
276         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
277         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
278         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
279         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
280         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
281         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
282         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
283 
284         // Floating-point to integer conversions.
285         // i64 conversions are done via library routines even when generating VFP
286         // instructions, so use the same ones.
287         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
288         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
289         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
290         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
291 
292         // Conversions between floating types.
293         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
294         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
295 
296         // Integer to floating-point conversions.
297         // i64 conversions are done via library routines even when generating VFP
298         // instructions, so use the same ones.
299         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
300         // e.g., __floatunsidf vs. __floatunssidfvfp.
301         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
302         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
303         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
304         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
305       };
306 
307       for (const auto &LC : LibraryCalls) {
308         setLibcallName(LC.Op, LC.Name);
309         if (LC.Cond != ISD::SETCC_INVALID)
310           setCmpLibcallCC(LC.Op, LC.Cond);
311       }
312     }
313 
314     // Set the correct calling convention for ARMv7k WatchOS. It's just
315     // AAPCS_VFP for functions as simple as libcalls.
316     if (Subtarget->isTargetWatchABI()) {
317       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
318         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
319     }
320   }
321 
322   // These libcalls are not available in 32-bit.
323   setLibcallName(RTLIB::SHL_I128, nullptr);
324   setLibcallName(RTLIB::SRL_I128, nullptr);
325   setLibcallName(RTLIB::SRA_I128, nullptr);
326 
327   // RTLIB
328   if (Subtarget->isAAPCS_ABI() &&
329       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
330        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
331     static const struct {
332       const RTLIB::Libcall Op;
333       const char * const Name;
334       const CallingConv::ID CC;
335       const ISD::CondCode Cond;
336     } LibraryCalls[] = {
337       // Double-precision floating-point arithmetic helper functions
338       // RTABI chapter 4.1.2, Table 2
339       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 
344       // Double-precision floating-point comparison helper functions
345       // RTABI chapter 4.1.2, Table 3
346       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
347       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
348       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
349       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
350       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
351       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
352       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
353       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
354 
355       // Single-precision floating-point arithmetic helper functions
356       // RTABI chapter 4.1.2, Table 4
357       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
358       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
361 
362       // Single-precision floating-point comparison helper functions
363       // RTABI chapter 4.1.2, Table 5
364       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
365       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
366       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
367       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
368       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
369       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
370       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
371       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
372 
373       // Floating-point to integer conversions.
374       // RTABI chapter 4.1.2, Table 6
375       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
376       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383 
384       // Conversions between floating types.
385       // RTABI chapter 4.1.2, Table 7
386       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389 
390       // Integer to floating-point conversions.
391       // RTABI chapter 4.1.2, Table 8
392       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
400 
401       // Long long helper functions
402       // RTABI chapter 4.2, Table 9
403       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407 
408       // Integer division functions
409       // RTABI chapter 4.3.1
410       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
418     };
419 
420     for (const auto &LC : LibraryCalls) {
421       setLibcallName(LC.Op, LC.Name);
422       setLibcallCallingConv(LC.Op, LC.CC);
423       if (LC.Cond != ISD::SETCC_INVALID)
424         setCmpLibcallCC(LC.Op, LC.Cond);
425     }
426 
427     // EABI dependent RTLIB
428     if (TM.Options.EABIVersion == EABI::EABI4 ||
429         TM.Options.EABIVersion == EABI::EABI5) {
430       static const struct {
431         const RTLIB::Libcall Op;
432         const char *const Name;
433         const CallingConv::ID CC;
434         const ISD::CondCode Cond;
435       } MemOpsLibraryCalls[] = {
436         // Memory operations
437         // RTABI chapter 4.3.4
438         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
440         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
441       };
442 
443       for (const auto &LC : MemOpsLibraryCalls) {
444         setLibcallName(LC.Op, LC.Name);
445         setLibcallCallingConv(LC.Op, LC.CC);
446         if (LC.Cond != ISD::SETCC_INVALID)
447           setCmpLibcallCC(LC.Op, LC.Cond);
448       }
449     }
450   }
451 
452   if (Subtarget->isTargetWindows()) {
453     static const struct {
454       const RTLIB::Libcall Op;
455       const char * const Name;
456       const CallingConv::ID CC;
457     } LibraryCalls[] = {
458       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
459       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
460       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
461       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
462       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
463       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
464       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
465       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
466     };
467 
468     for (const auto &LC : LibraryCalls) {
469       setLibcallName(LC.Op, LC.Name);
470       setLibcallCallingConv(LC.Op, LC.CC);
471     }
472   }
473 
474   // Use divmod compiler-rt calls for iOS 5.0 and later.
475   if (Subtarget->isTargetWatchOS() ||
476       (Subtarget->isTargetIOS() &&
477        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
478     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
479     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
480   }
481 
482   // The half <-> float conversion functions are always soft-float on
483   // non-watchos platforms, but are needed for some targets which use a
484   // hard-float calling convention by default.
485   if (!Subtarget->isTargetWatchABI()) {
486     if (Subtarget->isAAPCS_ABI()) {
487       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
488       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
489       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
490     } else {
491       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
492       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
493       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
494     }
495   }
496 
497   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
498   // a __gnu_ prefix (which is the default).
499   if (Subtarget->isTargetAEABI()) {
500     static const struct {
501       const RTLIB::Libcall Op;
502       const char * const Name;
503       const CallingConv::ID CC;
504     } LibraryCalls[] = {
505       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
506       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
507       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
508     };
509 
510     for (const auto &LC : LibraryCalls) {
511       setLibcallName(LC.Op, LC.Name);
512       setLibcallCallingConv(LC.Op, LC.CC);
513     }
514   }
515 
516   if (Subtarget->isThumb1Only())
517     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
518   else
519     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
520 
521   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
522       !Subtarget->isThumb1Only()) {
523     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
524     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
525   }
526 
527   for (MVT VT : MVT::vector_valuetypes()) {
528     for (MVT InnerVT : MVT::vector_valuetypes()) {
529       setTruncStoreAction(VT, InnerVT, Expand);
530       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
531       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
532       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
533     }
534 
535     setOperationAction(ISD::MULHS, VT, Expand);
536     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
537     setOperationAction(ISD::MULHU, VT, Expand);
538     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
539 
540     setOperationAction(ISD::BSWAP, VT, Expand);
541   }
542 
543   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
544   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
545 
546   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
547   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
548 
549   if (Subtarget->hasNEON()) {
550     addDRTypeForNEON(MVT::v2f32);
551     addDRTypeForNEON(MVT::v8i8);
552     addDRTypeForNEON(MVT::v4i16);
553     addDRTypeForNEON(MVT::v2i32);
554     addDRTypeForNEON(MVT::v1i64);
555 
556     addQRTypeForNEON(MVT::v4f32);
557     addQRTypeForNEON(MVT::v2f64);
558     addQRTypeForNEON(MVT::v16i8);
559     addQRTypeForNEON(MVT::v8i16);
560     addQRTypeForNEON(MVT::v4i32);
561     addQRTypeForNEON(MVT::v2i64);
562 
563     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
564     // neither Neon nor VFP support any arithmetic operations on it.
565     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
566     // supported for v4f32.
567     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
568     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
569     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
570     // FIXME: Code duplication: FDIV and FREM are expanded always, see
571     // ARMTargetLowering::addTypeForNEON method for details.
572     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
573     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
574     // FIXME: Create unittest.
575     // In another words, find a way when "copysign" appears in DAG with vector
576     // operands.
577     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
578     // FIXME: Code duplication: SETCC has custom operation action, see
579     // ARMTargetLowering::addTypeForNEON method for details.
580     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
581     // FIXME: Create unittest for FNEG and for FABS.
582     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
583     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
584     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
585     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
586     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
587     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
588     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
589     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
590     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
591     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
592     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
593     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
594     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
595     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
596     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
597     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
598     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
599     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
600     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
601 
602     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
603     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
604     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
605     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
606     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
607     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
608     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
609     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
610     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
611     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
612     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
613     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
614     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
615     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
616     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
617 
618     // Mark v2f32 intrinsics.
619     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
620     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
621     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
622     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
623     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
624     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
625     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
626     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
627     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
628     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
629     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
630     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
631     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
632     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
633     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
634 
635     // Neon does not support some operations on v1i64 and v2i64 types.
636     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
637     // Custom handling for some quad-vector types to detect VMULL.
638     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
639     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
640     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
641     // Custom handling for some vector types to avoid expensive expansions
642     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
643     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
644     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
645     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
646     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
647     // a destination type that is wider than the source, and nor does
648     // it have a FP_TO_[SU]INT instruction with a narrower destination than
649     // source.
650     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
651     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
652     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
653     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
654 
655     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
656     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
657 
658     // NEON does not have single instruction CTPOP for vectors with element
659     // types wider than 8-bits.  However, custom lowering can leverage the
660     // v8i8/v16i8 vcnt instruction.
661     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
662     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
663     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
664     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
665     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
666     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
667 
668     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
669     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
670 
671     // NEON does not have single instruction CTTZ for vectors.
672     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
673     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
674     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
675     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
676 
677     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
678     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
679     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
680     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
681 
682     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
683     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
684     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
686 
687     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
688     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
689     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
691 
692     // NEON only has FMA instructions as of VFP4.
693     if (!Subtarget->hasVFP4()) {
694       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
695       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
696     }
697 
698     setTargetDAGCombine(ISD::INTRINSIC_VOID);
699     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
700     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
701     setTargetDAGCombine(ISD::SHL);
702     setTargetDAGCombine(ISD::SRL);
703     setTargetDAGCombine(ISD::SRA);
704     setTargetDAGCombine(ISD::SIGN_EXTEND);
705     setTargetDAGCombine(ISD::ZERO_EXTEND);
706     setTargetDAGCombine(ISD::ANY_EXTEND);
707     setTargetDAGCombine(ISD::BUILD_VECTOR);
708     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
709     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
710     setTargetDAGCombine(ISD::STORE);
711     setTargetDAGCombine(ISD::FP_TO_SINT);
712     setTargetDAGCombine(ISD::FP_TO_UINT);
713     setTargetDAGCombine(ISD::FDIV);
714     setTargetDAGCombine(ISD::LOAD);
715 
716     // It is legal to extload from v4i8 to v4i16 or v4i32.
717     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
718                    MVT::v2i32}) {
719       for (MVT VT : MVT::integer_vector_valuetypes()) {
720         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
721         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
722         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
723       }
724     }
725   }
726 
727   if (Subtarget->isFPOnlySP()) {
728     // When targeting a floating-point unit with only single-precision
729     // operations, f64 is legal for the few double-precision instructions which
730     // are present However, no double-precision operations other than moves,
731     // loads and stores are provided by the hardware.
732     setOperationAction(ISD::FADD,       MVT::f64, Expand);
733     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
734     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
735     setOperationAction(ISD::FMA,        MVT::f64, Expand);
736     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
737     setOperationAction(ISD::FREM,       MVT::f64, Expand);
738     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
739     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
740     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
741     setOperationAction(ISD::FABS,       MVT::f64, Expand);
742     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
743     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
744     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
745     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
746     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
747     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
748     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
749     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
750     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
751     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
752     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
753     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
754     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
755     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
756     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
757     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
758     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
759     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
760     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
761     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
762     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
763     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
764     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
765   }
766 
767   computeRegisterProperties(Subtarget->getRegisterInfo());
768 
769   // ARM does not have floating-point extending loads.
770   for (MVT VT : MVT::fp_valuetypes()) {
771     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
772     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
773   }
774 
775   // ... or truncating stores
776   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
777   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
778   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
779 
780   // ARM does not have i1 sign extending load.
781   for (MVT VT : MVT::integer_valuetypes())
782     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
783 
784   // ARM supports all 4 flavors of integer indexed load / store.
785   if (!Subtarget->isThumb1Only()) {
786     for (unsigned im = (unsigned)ISD::PRE_INC;
787          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
788       setIndexedLoadAction(im,  MVT::i1,  Legal);
789       setIndexedLoadAction(im,  MVT::i8,  Legal);
790       setIndexedLoadAction(im,  MVT::i16, Legal);
791       setIndexedLoadAction(im,  MVT::i32, Legal);
792       setIndexedStoreAction(im, MVT::i1,  Legal);
793       setIndexedStoreAction(im, MVT::i8,  Legal);
794       setIndexedStoreAction(im, MVT::i16, Legal);
795       setIndexedStoreAction(im, MVT::i32, Legal);
796     }
797   } else {
798     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
799     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
800     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
801   }
802 
803   setOperationAction(ISD::SADDO, MVT::i32, Custom);
804   setOperationAction(ISD::UADDO, MVT::i32, Custom);
805   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
806   setOperationAction(ISD::USUBO, MVT::i32, Custom);
807 
808   // i64 operation support.
809   setOperationAction(ISD::MUL,     MVT::i64, Expand);
810   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
811   if (Subtarget->isThumb1Only()) {
812     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
813     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
814   }
815   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
816       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
817     setOperationAction(ISD::MULHS, MVT::i32, Expand);
818 
819   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
820   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
821   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
822   setOperationAction(ISD::SRL,       MVT::i64, Custom);
823   setOperationAction(ISD::SRA,       MVT::i64, Custom);
824 
825   if (!Subtarget->isThumb1Only()) {
826     // FIXME: We should do this for Thumb1 as well.
827     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
828     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
829     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
830     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
831   }
832 
833   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
834     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
835 
836   // ARM does not have ROTL.
837   setOperationAction(ISD::ROTL, MVT::i32, Expand);
838   for (MVT VT : MVT::vector_valuetypes()) {
839     setOperationAction(ISD::ROTL, VT, Expand);
840     setOperationAction(ISD::ROTR, VT, Expand);
841   }
842   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
843   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
844   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
845     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
846 
847   // @llvm.readcyclecounter requires the Performance Monitors extension.
848   // Default to the 0 expansion on unsupported platforms.
849   // FIXME: Technically there are older ARM CPUs that have
850   // implementation-specific ways of obtaining this information.
851   if (Subtarget->hasPerfMon())
852     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
853 
854   // Only ARMv6 has BSWAP.
855   if (!Subtarget->hasV6Ops())
856     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
857 
858   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
859                                         : Subtarget->hasDivideInARMMode();
860   if (!hasDivide) {
861     // These are expanded into libcalls if the cpu doesn't have HW divider.
862     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
863     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
864   }
865 
866   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
867     setOperationAction(ISD::SDIV, MVT::i32, Custom);
868     setOperationAction(ISD::UDIV, MVT::i32, Custom);
869 
870     setOperationAction(ISD::SDIV, MVT::i64, Custom);
871     setOperationAction(ISD::UDIV, MVT::i64, Custom);
872   }
873 
874   setOperationAction(ISD::SREM,  MVT::i32, Expand);
875   setOperationAction(ISD::UREM,  MVT::i32, Expand);
876 
877   // Register based DivRem for AEABI (RTABI 4.2)
878   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
879       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
880       Subtarget->isTargetWindows()) {
881     setOperationAction(ISD::SREM, MVT::i64, Custom);
882     setOperationAction(ISD::UREM, MVT::i64, Custom);
883     HasStandaloneRem = false;
884 
885     if (Subtarget->isTargetWindows()) {
886       const struct {
887         const RTLIB::Libcall Op;
888         const char * const Name;
889         const CallingConv::ID CC;
890       } LibraryCalls[] = {
891         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
892         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
893         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
894         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
895 
896         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
897         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
898         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
899         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
900       };
901 
902       for (const auto &LC : LibraryCalls) {
903         setLibcallName(LC.Op, LC.Name);
904         setLibcallCallingConv(LC.Op, LC.CC);
905       }
906     } else {
907       const struct {
908         const RTLIB::Libcall Op;
909         const char * const Name;
910         const CallingConv::ID CC;
911       } LibraryCalls[] = {
912         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
913         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
914         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
915         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
916 
917         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
918         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
919         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
920         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
921       };
922 
923       for (const auto &LC : LibraryCalls) {
924         setLibcallName(LC.Op, LC.Name);
925         setLibcallCallingConv(LC.Op, LC.CC);
926       }
927     }
928 
929     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
930     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
931     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
932     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
933   } else {
934     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
935     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
936   }
937 
938   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
939     for (auto &VT : {MVT::f32, MVT::f64})
940       setOperationAction(ISD::FPOWI, VT, Custom);
941 
942   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
943   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
944   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
945   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
946 
947   setOperationAction(ISD::TRAP, MVT::Other, Legal);
948 
949   // Use the default implementation.
950   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
951   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
952   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
953   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
954   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
955   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
956 
957   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
958     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
959   else
960     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
961 
962   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
963   // the default expansion.
964   InsertFencesForAtomic = false;
965   if (Subtarget->hasAnyDataBarrier() &&
966       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
967     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
968     // to ldrex/strex loops already.
969     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
970     if (!Subtarget->isThumb() || !Subtarget->isMClass())
971       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
972 
973     // On v8, we have particularly efficient implementations of atomic fences
974     // if they can be combined with nearby atomic loads and stores.
975     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
976       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
977       InsertFencesForAtomic = true;
978     }
979   } else {
980     // If there's anything we can use as a barrier, go through custom lowering
981     // for ATOMIC_FENCE.
982     // If target has DMB in thumb, Fences can be inserted.
983     if (Subtarget->hasDataBarrier())
984       InsertFencesForAtomic = true;
985 
986     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
987                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
988 
989     // Set them all for expansion, which will force libcalls.
990     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
991     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
992     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
993     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
999     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1000     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1001     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1002     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1003     // Unordered/Monotonic case.
1004     if (!InsertFencesForAtomic) {
1005       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1006       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1007     }
1008   }
1009 
1010   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1011 
1012   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1013   if (!Subtarget->hasV6Ops()) {
1014     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1015     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1016   }
1017   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1018 
1019   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1020       !Subtarget->isThumb1Only()) {
1021     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1022     // iff target supports vfp2.
1023     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1024     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1025   }
1026 
1027   // We want to custom lower some of our intrinsics.
1028   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1029   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1030   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1031   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1032   if (Subtarget->useSjLjEH())
1033     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1034 
1035   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1036   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1037   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1038   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1039   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1040   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1041   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1042   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1043   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1044 
1045   // Thumb-1 cannot currently select ARMISD::SUBE.
1046   if (!Subtarget->isThumb1Only())
1047     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1048 
1049   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1050   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1051   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1052   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1053   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1054 
1055   // We don't support sin/cos/fmod/copysign/pow
1056   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1057   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1058   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1059   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1060   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1061   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1062   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1063   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1064   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1065       !Subtarget->isThumb1Only()) {
1066     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1067     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1068   }
1069   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1070   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1071 
1072   if (!Subtarget->hasVFP4()) {
1073     setOperationAction(ISD::FMA, MVT::f64, Expand);
1074     setOperationAction(ISD::FMA, MVT::f32, Expand);
1075   }
1076 
1077   // Various VFP goodness
1078   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1079     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1080     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1081       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1082       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1083     }
1084 
1085     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1086     if (!Subtarget->hasFP16()) {
1087       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1088       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1089     }
1090   }
1091 
1092   // Combine sin / cos into one node or libcall if possible.
1093   if (Subtarget->hasSinCos()) {
1094     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1095     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1096     if (Subtarget->isTargetWatchABI()) {
1097       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1098       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1099     }
1100     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1101       // For iOS, we don't want to the normal expansion of a libcall to
1102       // sincos. We want to issue a libcall to __sincos_stret.
1103       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1104       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1105     }
1106   }
1107 
1108   // FP-ARMv8 implements a lot of rounding-like FP operations.
1109   if (Subtarget->hasFPARMv8()) {
1110     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1111     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1112     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1113     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1114     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1115     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1116     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1117     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1118     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1119     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1120     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1121     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1122 
1123     if (!Subtarget->isFPOnlySP()) {
1124       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1125       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1126       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1127       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1128       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1129       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1130       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1131       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1132     }
1133   }
1134 
1135   if (Subtarget->hasNEON()) {
1136     // vmin and vmax aren't available in a scalar form, so we use
1137     // a NEON instruction with an undef lane instead.
1138     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1139     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1140     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1141     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1142     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1143     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1144   }
1145 
1146   // We have target-specific dag combine patterns for the following nodes:
1147   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1148   setTargetDAGCombine(ISD::ADD);
1149   setTargetDAGCombine(ISD::SUB);
1150   setTargetDAGCombine(ISD::MUL);
1151   setTargetDAGCombine(ISD::AND);
1152   setTargetDAGCombine(ISD::OR);
1153   setTargetDAGCombine(ISD::XOR);
1154 
1155   if (Subtarget->hasV6Ops())
1156     setTargetDAGCombine(ISD::SRL);
1157 
1158   setStackPointerRegisterToSaveRestore(ARM::SP);
1159 
1160   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1161       !Subtarget->hasVFP2())
1162     setSchedulingPreference(Sched::RegPressure);
1163   else
1164     setSchedulingPreference(Sched::Hybrid);
1165 
1166   //// temporary - rewrite interface to use type
1167   MaxStoresPerMemset = 8;
1168   MaxStoresPerMemsetOptSize = 4;
1169   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1170   MaxStoresPerMemcpyOptSize = 2;
1171   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1172   MaxStoresPerMemmoveOptSize = 2;
1173 
1174   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1175   // are at least 4 bytes aligned.
1176   setMinStackArgumentAlignment(4);
1177 
1178   // Prefer likely predicted branches to selects on out-of-order cores.
1179   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1180 
1181   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1182 }
1183 
1184 bool ARMTargetLowering::useSoftFloat() const {
1185   return Subtarget->useSoftFloat();
1186 }
1187 
1188 // FIXME: It might make sense to define the representative register class as the
1189 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1190 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1191 // SPR's representative would be DPR_VFP2. This should work well if register
1192 // pressure tracking were modified such that a register use would increment the
1193 // pressure of the register class's representative and all of it's super
1194 // classes' representatives transitively. We have not implemented this because
1195 // of the difficulty prior to coalescing of modeling operand register classes
1196 // due to the common occurrence of cross class copies and subregister insertions
1197 // and extractions.
1198 std::pair<const TargetRegisterClass *, uint8_t>
1199 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1200                                            MVT VT) const {
1201   const TargetRegisterClass *RRC = nullptr;
1202   uint8_t Cost = 1;
1203   switch (VT.SimpleTy) {
1204   default:
1205     return TargetLowering::findRepresentativeClass(TRI, VT);
1206   // Use DPR as representative register class for all floating point
1207   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1208   // the cost is 1 for both f32 and f64.
1209   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1210   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1211     RRC = &ARM::DPRRegClass;
1212     // When NEON is used for SP, only half of the register file is available
1213     // because operations that define both SP and DP results will be constrained
1214     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1215     // coalescing by double-counting the SP regs. See the FIXME above.
1216     if (Subtarget->useNEONForSinglePrecisionFP())
1217       Cost = 2;
1218     break;
1219   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1220   case MVT::v4f32: case MVT::v2f64:
1221     RRC = &ARM::DPRRegClass;
1222     Cost = 2;
1223     break;
1224   case MVT::v4i64:
1225     RRC = &ARM::DPRRegClass;
1226     Cost = 4;
1227     break;
1228   case MVT::v8i64:
1229     RRC = &ARM::DPRRegClass;
1230     Cost = 8;
1231     break;
1232   }
1233   return std::make_pair(RRC, Cost);
1234 }
1235 
1236 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1237   switch ((ARMISD::NodeType)Opcode) {
1238   case ARMISD::FIRST_NUMBER:  break;
1239   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1240   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1241   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1242   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1243   case ARMISD::CALL:          return "ARMISD::CALL";
1244   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1245   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1246   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1247   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1248   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1249   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1250   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1251   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1252   case ARMISD::CMP:           return "ARMISD::CMP";
1253   case ARMISD::CMN:           return "ARMISD::CMN";
1254   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1255   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1256   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1257   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1258   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1259 
1260   case ARMISD::CMOV:          return "ARMISD::CMOV";
1261 
1262   case ARMISD::SSAT:          return "ARMISD::SSAT";
1263 
1264   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1265   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1266   case ARMISD::RRX:           return "ARMISD::RRX";
1267 
1268   case ARMISD::ADDC:          return "ARMISD::ADDC";
1269   case ARMISD::ADDE:          return "ARMISD::ADDE";
1270   case ARMISD::SUBC:          return "ARMISD::SUBC";
1271   case ARMISD::SUBE:          return "ARMISD::SUBE";
1272 
1273   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1274   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1275 
1276   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1277   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1278   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1279 
1280   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1281 
1282   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1283 
1284   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1285 
1286   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1287 
1288   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1289 
1290   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1291   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1292 
1293   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1294   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1295   case ARMISD::VCGE:          return "ARMISD::VCGE";
1296   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1297   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1298   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1299   case ARMISD::VCGT:          return "ARMISD::VCGT";
1300   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1301   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1302   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1303   case ARMISD::VTST:          return "ARMISD::VTST";
1304 
1305   case ARMISD::VSHL:          return "ARMISD::VSHL";
1306   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1307   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1308   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1309   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1310   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1311   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1312   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1313   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1314   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1315   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1316   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1317   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1318   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1319   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1320   case ARMISD::VSLI:          return "ARMISD::VSLI";
1321   case ARMISD::VSRI:          return "ARMISD::VSRI";
1322   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1323   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1324   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1325   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1326   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1327   case ARMISD::VDUP:          return "ARMISD::VDUP";
1328   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1329   case ARMISD::VEXT:          return "ARMISD::VEXT";
1330   case ARMISD::VREV64:        return "ARMISD::VREV64";
1331   case ARMISD::VREV32:        return "ARMISD::VREV32";
1332   case ARMISD::VREV16:        return "ARMISD::VREV16";
1333   case ARMISD::VZIP:          return "ARMISD::VZIP";
1334   case ARMISD::VUZP:          return "ARMISD::VUZP";
1335   case ARMISD::VTRN:          return "ARMISD::VTRN";
1336   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1337   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1338   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1339   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1340   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1341   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1342   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1343   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1344   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1345   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1346   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1347   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1348   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1349   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1350   case ARMISD::BFI:           return "ARMISD::BFI";
1351   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1352   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1353   case ARMISD::VBSL:          return "ARMISD::VBSL";
1354   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1355   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1356   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1357   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1358   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1359   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1360   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1361   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1362   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1363   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1364   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1365   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1366   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1367   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1368   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1369   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1370   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1371   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1372   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1373   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1374   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1375   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1376   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1377   }
1378   return nullptr;
1379 }
1380 
1381 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1382                                           EVT VT) const {
1383   if (!VT.isVector())
1384     return getPointerTy(DL);
1385   return VT.changeVectorElementTypeToInteger();
1386 }
1387 
1388 /// getRegClassFor - Return the register class that should be used for the
1389 /// specified value type.
1390 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1391   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1392   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1393   // load / store 4 to 8 consecutive D registers.
1394   if (Subtarget->hasNEON()) {
1395     if (VT == MVT::v4i64)
1396       return &ARM::QQPRRegClass;
1397     if (VT == MVT::v8i64)
1398       return &ARM::QQQQPRRegClass;
1399   }
1400   return TargetLowering::getRegClassFor(VT);
1401 }
1402 
1403 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1404 // source/dest is aligned and the copy size is large enough. We therefore want
1405 // to align such objects passed to memory intrinsics.
1406 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1407                                                unsigned &PrefAlign) const {
1408   if (!isa<MemIntrinsic>(CI))
1409     return false;
1410   MinSize = 8;
1411   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1412   // cycle faster than 4-byte aligned LDM.
1413   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1414   return true;
1415 }
1416 
1417 // Create a fast isel object.
1418 FastISel *
1419 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1420                                   const TargetLibraryInfo *libInfo) const {
1421   return ARM::createFastISel(funcInfo, libInfo);
1422 }
1423 
1424 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1425   unsigned NumVals = N->getNumValues();
1426   if (!NumVals)
1427     return Sched::RegPressure;
1428 
1429   for (unsigned i = 0; i != NumVals; ++i) {
1430     EVT VT = N->getValueType(i);
1431     if (VT == MVT::Glue || VT == MVT::Other)
1432       continue;
1433     if (VT.isFloatingPoint() || VT.isVector())
1434       return Sched::ILP;
1435   }
1436 
1437   if (!N->isMachineOpcode())
1438     return Sched::RegPressure;
1439 
1440   // Load are scheduled for latency even if there instruction itinerary
1441   // is not available.
1442   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1443   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1444 
1445   if (MCID.getNumDefs() == 0)
1446     return Sched::RegPressure;
1447   if (!Itins->isEmpty() &&
1448       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1449     return Sched::ILP;
1450 
1451   return Sched::RegPressure;
1452 }
1453 
1454 //===----------------------------------------------------------------------===//
1455 // Lowering Code
1456 //===----------------------------------------------------------------------===//
1457 
1458 static bool isSRL16(const SDValue &Op) {
1459   if (Op.getOpcode() != ISD::SRL)
1460     return false;
1461   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1462     return Const->getZExtValue() == 16;
1463   return false;
1464 }
1465 
1466 static bool isSRA16(const SDValue &Op) {
1467   if (Op.getOpcode() != ISD::SRA)
1468     return false;
1469   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1470     return Const->getZExtValue() == 16;
1471   return false;
1472 }
1473 
1474 static bool isSHL16(const SDValue &Op) {
1475   if (Op.getOpcode() != ISD::SHL)
1476     return false;
1477   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1478     return Const->getZExtValue() == 16;
1479   return false;
1480 }
1481 
1482 // Check for a signed 16-bit value. We special case SRA because it makes it
1483 // more simple when also looking for SRAs that aren't sign extending a
1484 // smaller value. Without the check, we'd need to take extra care with
1485 // checking order for some operations.
1486 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1487   if (isSRA16(Op))
1488     return isSHL16(Op.getOperand(0));
1489   return DAG.ComputeNumSignBits(Op) == 17;
1490 }
1491 
1492 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1493 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1494   switch (CC) {
1495   default: llvm_unreachable("Unknown condition code!");
1496   case ISD::SETNE:  return ARMCC::NE;
1497   case ISD::SETEQ:  return ARMCC::EQ;
1498   case ISD::SETGT:  return ARMCC::GT;
1499   case ISD::SETGE:  return ARMCC::GE;
1500   case ISD::SETLT:  return ARMCC::LT;
1501   case ISD::SETLE:  return ARMCC::LE;
1502   case ISD::SETUGT: return ARMCC::HI;
1503   case ISD::SETUGE: return ARMCC::HS;
1504   case ISD::SETULT: return ARMCC::LO;
1505   case ISD::SETULE: return ARMCC::LS;
1506   }
1507 }
1508 
1509 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1510 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1511                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1512   CondCode2 = ARMCC::AL;
1513   InvalidOnQNaN = true;
1514   switch (CC) {
1515   default: llvm_unreachable("Unknown FP condition!");
1516   case ISD::SETEQ:
1517   case ISD::SETOEQ:
1518     CondCode = ARMCC::EQ;
1519     InvalidOnQNaN = false;
1520     break;
1521   case ISD::SETGT:
1522   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1523   case ISD::SETGE:
1524   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1525   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1526   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1527   case ISD::SETONE:
1528     CondCode = ARMCC::MI;
1529     CondCode2 = ARMCC::GT;
1530     InvalidOnQNaN = false;
1531     break;
1532   case ISD::SETO:   CondCode = ARMCC::VC; break;
1533   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1534   case ISD::SETUEQ:
1535     CondCode = ARMCC::EQ;
1536     CondCode2 = ARMCC::VS;
1537     InvalidOnQNaN = false;
1538     break;
1539   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1540   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1541   case ISD::SETLT:
1542   case ISD::SETULT: CondCode = ARMCC::LT; break;
1543   case ISD::SETLE:
1544   case ISD::SETULE: CondCode = ARMCC::LE; break;
1545   case ISD::SETNE:
1546   case ISD::SETUNE:
1547     CondCode = ARMCC::NE;
1548     InvalidOnQNaN = false;
1549     break;
1550   }
1551 }
1552 
1553 //===----------------------------------------------------------------------===//
1554 //                      Calling Convention Implementation
1555 //===----------------------------------------------------------------------===//
1556 
1557 #include "ARMGenCallingConv.inc"
1558 
1559 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1560 /// account presence of floating point hardware and calling convention
1561 /// limitations, such as support for variadic functions.
1562 CallingConv::ID
1563 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1564                                            bool isVarArg) const {
1565   switch (CC) {
1566   default:
1567     llvm_unreachable("Unsupported calling convention");
1568   case CallingConv::ARM_AAPCS:
1569   case CallingConv::ARM_APCS:
1570   case CallingConv::GHC:
1571     return CC;
1572   case CallingConv::PreserveMost:
1573     return CallingConv::PreserveMost;
1574   case CallingConv::ARM_AAPCS_VFP:
1575   case CallingConv::Swift:
1576     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1577   case CallingConv::C:
1578     if (!Subtarget->isAAPCS_ABI())
1579       return CallingConv::ARM_APCS;
1580     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1581              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1582              !isVarArg)
1583       return CallingConv::ARM_AAPCS_VFP;
1584     else
1585       return CallingConv::ARM_AAPCS;
1586   case CallingConv::Fast:
1587   case CallingConv::CXX_FAST_TLS:
1588     if (!Subtarget->isAAPCS_ABI()) {
1589       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1590         return CallingConv::Fast;
1591       return CallingConv::ARM_APCS;
1592     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1593       return CallingConv::ARM_AAPCS_VFP;
1594     else
1595       return CallingConv::ARM_AAPCS;
1596   }
1597 }
1598 
1599 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1600                                                  bool isVarArg) const {
1601   return CCAssignFnForNode(CC, false, isVarArg);
1602 }
1603 
1604 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1605                                                    bool isVarArg) const {
1606   return CCAssignFnForNode(CC, true, isVarArg);
1607 }
1608 
1609 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1610 /// CallingConvention.
1611 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1612                                                  bool Return,
1613                                                  bool isVarArg) const {
1614   switch (getEffectiveCallingConv(CC, isVarArg)) {
1615   default:
1616     llvm_unreachable("Unsupported calling convention");
1617   case CallingConv::ARM_APCS:
1618     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1619   case CallingConv::ARM_AAPCS:
1620     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1621   case CallingConv::ARM_AAPCS_VFP:
1622     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1623   case CallingConv::Fast:
1624     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1625   case CallingConv::GHC:
1626     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1627   case CallingConv::PreserveMost:
1628     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1629   }
1630 }
1631 
1632 /// LowerCallResult - Lower the result values of a call into the
1633 /// appropriate copies out of appropriate physical registers.
1634 SDValue ARMTargetLowering::LowerCallResult(
1635     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1636     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1637     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1638     SDValue ThisVal) const {
1639 
1640   // Assign locations to each value returned by this call.
1641   SmallVector<CCValAssign, 16> RVLocs;
1642   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1643                  *DAG.getContext());
1644   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1645 
1646   // Copy all of the result registers out of their specified physreg.
1647   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1648     CCValAssign VA = RVLocs[i];
1649 
1650     // Pass 'this' value directly from the argument to return value, to avoid
1651     // reg unit interference
1652     if (i == 0 && isThisReturn) {
1653       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1654              "unexpected return calling convention register assignment");
1655       InVals.push_back(ThisVal);
1656       continue;
1657     }
1658 
1659     SDValue Val;
1660     if (VA.needsCustom()) {
1661       // Handle f64 or half of a v2f64.
1662       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1663                                       InFlag);
1664       Chain = Lo.getValue(1);
1665       InFlag = Lo.getValue(2);
1666       VA = RVLocs[++i]; // skip ahead to next loc
1667       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1668                                       InFlag);
1669       Chain = Hi.getValue(1);
1670       InFlag = Hi.getValue(2);
1671       if (!Subtarget->isLittle())
1672         std::swap (Lo, Hi);
1673       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1674 
1675       if (VA.getLocVT() == MVT::v2f64) {
1676         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1677         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1678                           DAG.getConstant(0, dl, MVT::i32));
1679 
1680         VA = RVLocs[++i]; // skip ahead to next loc
1681         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1682         Chain = Lo.getValue(1);
1683         InFlag = Lo.getValue(2);
1684         VA = RVLocs[++i]; // skip ahead to next loc
1685         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1686         Chain = Hi.getValue(1);
1687         InFlag = Hi.getValue(2);
1688         if (!Subtarget->isLittle())
1689           std::swap (Lo, Hi);
1690         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1691         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1692                           DAG.getConstant(1, dl, MVT::i32));
1693       }
1694     } else {
1695       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1696                                InFlag);
1697       Chain = Val.getValue(1);
1698       InFlag = Val.getValue(2);
1699     }
1700 
1701     switch (VA.getLocInfo()) {
1702     default: llvm_unreachable("Unknown loc info!");
1703     case CCValAssign::Full: break;
1704     case CCValAssign::BCvt:
1705       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1706       break;
1707     }
1708 
1709     InVals.push_back(Val);
1710   }
1711 
1712   return Chain;
1713 }
1714 
1715 /// LowerMemOpCallTo - Store the argument to the stack.
1716 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1717                                             SDValue Arg, const SDLoc &dl,
1718                                             SelectionDAG &DAG,
1719                                             const CCValAssign &VA,
1720                                             ISD::ArgFlagsTy Flags) const {
1721   unsigned LocMemOffset = VA.getLocMemOffset();
1722   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1723   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1724                        StackPtr, PtrOff);
1725   return DAG.getStore(
1726       Chain, dl, Arg, PtrOff,
1727       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1728 }
1729 
1730 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1731                                          SDValue Chain, SDValue &Arg,
1732                                          RegsToPassVector &RegsToPass,
1733                                          CCValAssign &VA, CCValAssign &NextVA,
1734                                          SDValue &StackPtr,
1735                                          SmallVectorImpl<SDValue> &MemOpChains,
1736                                          ISD::ArgFlagsTy Flags) const {
1737 
1738   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1739                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1740   unsigned id = Subtarget->isLittle() ? 0 : 1;
1741   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1742 
1743   if (NextVA.isRegLoc())
1744     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1745   else {
1746     assert(NextVA.isMemLoc());
1747     if (!StackPtr.getNode())
1748       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1749                                     getPointerTy(DAG.getDataLayout()));
1750 
1751     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1752                                            dl, DAG, NextVA,
1753                                            Flags));
1754   }
1755 }
1756 
1757 /// LowerCall - Lowering a call into a callseq_start <-
1758 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1759 /// nodes.
1760 SDValue
1761 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1762                              SmallVectorImpl<SDValue> &InVals) const {
1763   SelectionDAG &DAG                     = CLI.DAG;
1764   SDLoc &dl                             = CLI.DL;
1765   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1766   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1767   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1768   SDValue Chain                         = CLI.Chain;
1769   SDValue Callee                        = CLI.Callee;
1770   bool &isTailCall                      = CLI.IsTailCall;
1771   CallingConv::ID CallConv              = CLI.CallConv;
1772   bool doesNotRet                       = CLI.DoesNotReturn;
1773   bool isVarArg                         = CLI.IsVarArg;
1774 
1775   MachineFunction &MF = DAG.getMachineFunction();
1776   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1777   bool isThisReturn   = false;
1778   bool isSibCall      = false;
1779   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1780 
1781   // Disable tail calls if they're not supported.
1782   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1783     isTailCall = false;
1784 
1785   if (isTailCall) {
1786     // Check if it's really possible to do a tail call.
1787     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1788                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1789                                                    Outs, OutVals, Ins, DAG);
1790     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1791       report_fatal_error("failed to perform tail call elimination on a call "
1792                          "site marked musttail");
1793     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1794     // detected sibcalls.
1795     if (isTailCall) {
1796       ++NumTailCalls;
1797       isSibCall = true;
1798     }
1799   }
1800 
1801   // Analyze operands of the call, assigning locations to each operand.
1802   SmallVector<CCValAssign, 16> ArgLocs;
1803   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1804                  *DAG.getContext());
1805   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1806 
1807   // Get a count of how many bytes are to be pushed on the stack.
1808   unsigned NumBytes = CCInfo.getNextStackOffset();
1809 
1810   // For tail calls, memory operands are available in our caller's stack.
1811   if (isSibCall)
1812     NumBytes = 0;
1813 
1814   // Adjust the stack pointer for the new arguments...
1815   // These operations are automatically eliminated by the prolog/epilog pass
1816   if (!isSibCall)
1817     Chain = DAG.getCALLSEQ_START(Chain,
1818                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1819 
1820   SDValue StackPtr =
1821       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1822 
1823   RegsToPassVector RegsToPass;
1824   SmallVector<SDValue, 8> MemOpChains;
1825 
1826   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1827   // of tail call optimization, arguments are handled later.
1828   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1829        i != e;
1830        ++i, ++realArgIdx) {
1831     CCValAssign &VA = ArgLocs[i];
1832     SDValue Arg = OutVals[realArgIdx];
1833     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1834     bool isByVal = Flags.isByVal();
1835 
1836     // Promote the value if needed.
1837     switch (VA.getLocInfo()) {
1838     default: llvm_unreachable("Unknown loc info!");
1839     case CCValAssign::Full: break;
1840     case CCValAssign::SExt:
1841       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1842       break;
1843     case CCValAssign::ZExt:
1844       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1845       break;
1846     case CCValAssign::AExt:
1847       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1848       break;
1849     case CCValAssign::BCvt:
1850       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1851       break;
1852     }
1853 
1854     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1855     if (VA.needsCustom()) {
1856       if (VA.getLocVT() == MVT::v2f64) {
1857         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1858                                   DAG.getConstant(0, dl, MVT::i32));
1859         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1860                                   DAG.getConstant(1, dl, MVT::i32));
1861 
1862         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1863                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1864 
1865         VA = ArgLocs[++i]; // skip ahead to next loc
1866         if (VA.isRegLoc()) {
1867           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1868                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1869         } else {
1870           assert(VA.isMemLoc());
1871 
1872           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1873                                                  dl, DAG, VA, Flags));
1874         }
1875       } else {
1876         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1877                          StackPtr, MemOpChains, Flags);
1878       }
1879     } else if (VA.isRegLoc()) {
1880       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1881           Outs[0].VT == MVT::i32) {
1882         assert(VA.getLocVT() == MVT::i32 &&
1883                "unexpected calling convention register assignment");
1884         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1885                "unexpected use of 'returned'");
1886         isThisReturn = true;
1887       }
1888       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1889     } else if (isByVal) {
1890       assert(VA.isMemLoc());
1891       unsigned offset = 0;
1892 
1893       // True if this byval aggregate will be split between registers
1894       // and memory.
1895       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1896       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1897 
1898       if (CurByValIdx < ByValArgsCount) {
1899 
1900         unsigned RegBegin, RegEnd;
1901         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1902 
1903         EVT PtrVT =
1904             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1905         unsigned int i, j;
1906         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1907           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1908           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1909           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1910                                      MachinePointerInfo(),
1911                                      DAG.InferPtrAlignment(AddArg));
1912           MemOpChains.push_back(Load.getValue(1));
1913           RegsToPass.push_back(std::make_pair(j, Load));
1914         }
1915 
1916         // If parameter size outsides register area, "offset" value
1917         // helps us to calculate stack slot for remained part properly.
1918         offset = RegEnd - RegBegin;
1919 
1920         CCInfo.nextInRegsParam();
1921       }
1922 
1923       if (Flags.getByValSize() > 4*offset) {
1924         auto PtrVT = getPointerTy(DAG.getDataLayout());
1925         unsigned LocMemOffset = VA.getLocMemOffset();
1926         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1927         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1928         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1929         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1930         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1931                                            MVT::i32);
1932         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1933                                             MVT::i32);
1934 
1935         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1936         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1937         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1938                                           Ops));
1939       }
1940     } else if (!isSibCall) {
1941       assert(VA.isMemLoc());
1942 
1943       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1944                                              dl, DAG, VA, Flags));
1945     }
1946   }
1947 
1948   if (!MemOpChains.empty())
1949     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1950 
1951   // Build a sequence of copy-to-reg nodes chained together with token chain
1952   // and flag operands which copy the outgoing args into the appropriate regs.
1953   SDValue InFlag;
1954   // Tail call byval lowering might overwrite argument registers so in case of
1955   // tail call optimization the copies to registers are lowered later.
1956   if (!isTailCall)
1957     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1958       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1959                                RegsToPass[i].second, InFlag);
1960       InFlag = Chain.getValue(1);
1961     }
1962 
1963   // For tail calls lower the arguments to the 'real' stack slot.
1964   if (isTailCall) {
1965     // Force all the incoming stack arguments to be loaded from the stack
1966     // before any new outgoing arguments are stored to the stack, because the
1967     // outgoing stack slots may alias the incoming argument stack slots, and
1968     // the alias isn't otherwise explicit. This is slightly more conservative
1969     // than necessary, because it means that each store effectively depends
1970     // on every argument instead of just those arguments it would clobber.
1971 
1972     // Do not flag preceding copytoreg stuff together with the following stuff.
1973     InFlag = SDValue();
1974     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1975       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1976                                RegsToPass[i].second, InFlag);
1977       InFlag = Chain.getValue(1);
1978     }
1979     InFlag = SDValue();
1980   }
1981 
1982   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1983   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1984   // node so that legalize doesn't hack it.
1985   bool isDirect = false;
1986 
1987   const TargetMachine &TM = getTargetMachine();
1988   const Module *Mod = MF.getFunction()->getParent();
1989   const GlobalValue *GV = nullptr;
1990   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1991     GV = G->getGlobal();
1992   bool isStub =
1993       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1994 
1995   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1996   bool isLocalARMFunc = false;
1997   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1998   auto PtrVt = getPointerTy(DAG.getDataLayout());
1999 
2000   if (Subtarget->genLongCalls()) {
2001     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2002            "long-calls codegen is not position independent!");
2003     // Handle a global address or an external symbol. If it's not one of
2004     // those, the target's already in a register, so we don't need to do
2005     // anything extra.
2006     if (isa<GlobalAddressSDNode>(Callee)) {
2007       // Create a constant pool entry for the callee address
2008       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2009       ARMConstantPoolValue *CPV =
2010         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2011 
2012       // Get the address of the callee into a register
2013       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2014       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2015       Callee = DAG.getLoad(
2016           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2017           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2018     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2019       const char *Sym = S->getSymbol();
2020 
2021       // Create a constant pool entry for the callee address
2022       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2023       ARMConstantPoolValue *CPV =
2024         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2025                                       ARMPCLabelIndex, 0);
2026       // Get the address of the callee into a register
2027       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2028       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2029       Callee = DAG.getLoad(
2030           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2031           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2032     }
2033   } else if (isa<GlobalAddressSDNode>(Callee)) {
2034     // If we're optimizing for minimum size and the function is called three or
2035     // more times in this block, we can improve codesize by calling indirectly
2036     // as BLXr has a 16-bit encoding.
2037     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2038     auto *BB = CLI.CS->getParent();
2039     bool PreferIndirect =
2040         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2041         count_if(GV->users(), [&BB](const User *U) {
2042           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2043         }) > 2;
2044 
2045     if (!PreferIndirect) {
2046       isDirect = true;
2047       bool isDef = GV->isStrongDefinitionForLinker();
2048 
2049       // ARM call to a local ARM function is predicable.
2050       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2051       // tBX takes a register source operand.
2052       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2053         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2054         Callee = DAG.getNode(
2055             ARMISD::WrapperPIC, dl, PtrVt,
2056             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2057         Callee = DAG.getLoad(
2058             PtrVt, dl, DAG.getEntryNode(), Callee,
2059             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2060             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2061                                      MachineMemOperand::MOInvariant);
2062       } else if (Subtarget->isTargetCOFF()) {
2063         assert(Subtarget->isTargetWindows() &&
2064                "Windows is the only supported COFF target");
2065         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2066                                    ? ARMII::MO_DLLIMPORT
2067                                    : ARMII::MO_NO_FLAG;
2068         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2069                                             TargetFlags);
2070         if (GV->hasDLLImportStorageClass())
2071           Callee =
2072               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2073                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2074                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2075       } else {
2076         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2077       }
2078     }
2079   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2080     isDirect = true;
2081     // tBX takes a register source operand.
2082     const char *Sym = S->getSymbol();
2083     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2084       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2085       ARMConstantPoolValue *CPV =
2086         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2087                                       ARMPCLabelIndex, 4);
2088       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2089       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2090       Callee = DAG.getLoad(
2091           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2092           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2093       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2094       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2095     } else {
2096       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2097     }
2098   }
2099 
2100   // FIXME: handle tail calls differently.
2101   unsigned CallOpc;
2102   if (Subtarget->isThumb()) {
2103     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2104       CallOpc = ARMISD::CALL_NOLINK;
2105     else
2106       CallOpc = ARMISD::CALL;
2107   } else {
2108     if (!isDirect && !Subtarget->hasV5TOps())
2109       CallOpc = ARMISD::CALL_NOLINK;
2110     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2111              // Emit regular call when code size is the priority
2112              !MF.getFunction()->optForMinSize())
2113       // "mov lr, pc; b _foo" to avoid confusing the RSP
2114       CallOpc = ARMISD::CALL_NOLINK;
2115     else
2116       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2117   }
2118 
2119   std::vector<SDValue> Ops;
2120   Ops.push_back(Chain);
2121   Ops.push_back(Callee);
2122 
2123   // Add argument registers to the end of the list so that they are known live
2124   // into the call.
2125   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2126     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2127                                   RegsToPass[i].second.getValueType()));
2128 
2129   // Add a register mask operand representing the call-preserved registers.
2130   if (!isTailCall) {
2131     const uint32_t *Mask;
2132     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2133     if (isThisReturn) {
2134       // For 'this' returns, use the R0-preserving mask if applicable
2135       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2136       if (!Mask) {
2137         // Set isThisReturn to false if the calling convention is not one that
2138         // allows 'returned' to be modeled in this way, so LowerCallResult does
2139         // not try to pass 'this' straight through
2140         isThisReturn = false;
2141         Mask = ARI->getCallPreservedMask(MF, CallConv);
2142       }
2143     } else
2144       Mask = ARI->getCallPreservedMask(MF, CallConv);
2145 
2146     assert(Mask && "Missing call preserved mask for calling convention");
2147     Ops.push_back(DAG.getRegisterMask(Mask));
2148   }
2149 
2150   if (InFlag.getNode())
2151     Ops.push_back(InFlag);
2152 
2153   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2154   if (isTailCall) {
2155     MF.getFrameInfo().setHasTailCall();
2156     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2157   }
2158 
2159   // Returns a chain and a flag for retval copy to use.
2160   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2161   InFlag = Chain.getValue(1);
2162 
2163   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2164                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2165   if (!Ins.empty())
2166     InFlag = Chain.getValue(1);
2167 
2168   // Handle result values, copying them out of physregs into vregs that we
2169   // return.
2170   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2171                          InVals, isThisReturn,
2172                          isThisReturn ? OutVals[0] : SDValue());
2173 }
2174 
2175 /// HandleByVal - Every parameter *after* a byval parameter is passed
2176 /// on the stack.  Remember the next parameter register to allocate,
2177 /// and then confiscate the rest of the parameter registers to insure
2178 /// this.
2179 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2180                                     unsigned Align) const {
2181   // Byval (as with any stack) slots are always at least 4 byte aligned.
2182   Align = std::max(Align, 4U);
2183 
2184   unsigned Reg = State->AllocateReg(GPRArgRegs);
2185   if (!Reg)
2186     return;
2187 
2188   unsigned AlignInRegs = Align / 4;
2189   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2190   for (unsigned i = 0; i < Waste; ++i)
2191     Reg = State->AllocateReg(GPRArgRegs);
2192 
2193   if (!Reg)
2194     return;
2195 
2196   unsigned Excess = 4 * (ARM::R4 - Reg);
2197 
2198   // Special case when NSAA != SP and parameter size greater than size of
2199   // all remained GPR regs. In that case we can't split parameter, we must
2200   // send it to stack. We also must set NCRN to R4, so waste all
2201   // remained registers.
2202   const unsigned NSAAOffset = State->getNextStackOffset();
2203   if (NSAAOffset != 0 && Size > Excess) {
2204     while (State->AllocateReg(GPRArgRegs))
2205       ;
2206     return;
2207   }
2208 
2209   // First register for byval parameter is the first register that wasn't
2210   // allocated before this method call, so it would be "reg".
2211   // If parameter is small enough to be saved in range [reg, r4), then
2212   // the end (first after last) register would be reg + param-size-in-regs,
2213   // else parameter would be splitted between registers and stack,
2214   // end register would be r4 in this case.
2215   unsigned ByValRegBegin = Reg;
2216   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2217   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2218   // Note, first register is allocated in the beginning of function already,
2219   // allocate remained amount of registers we need.
2220   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2221     State->AllocateReg(GPRArgRegs);
2222   // A byval parameter that is split between registers and memory needs its
2223   // size truncated here.
2224   // In the case where the entire structure fits in registers, we set the
2225   // size in memory to zero.
2226   Size = std::max<int>(Size - Excess, 0);
2227 }
2228 
2229 /// MatchingStackOffset - Return true if the given stack call argument is
2230 /// already available in the same position (relatively) of the caller's
2231 /// incoming argument stack.
2232 static
2233 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2234                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2235                          const TargetInstrInfo *TII) {
2236   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2237   int FI = std::numeric_limits<int>::max();
2238   if (Arg.getOpcode() == ISD::CopyFromReg) {
2239     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2240     if (!TargetRegisterInfo::isVirtualRegister(VR))
2241       return false;
2242     MachineInstr *Def = MRI->getVRegDef(VR);
2243     if (!Def)
2244       return false;
2245     if (!Flags.isByVal()) {
2246       if (!TII->isLoadFromStackSlot(*Def, FI))
2247         return false;
2248     } else {
2249       return false;
2250     }
2251   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2252     if (Flags.isByVal())
2253       // ByVal argument is passed in as a pointer but it's now being
2254       // dereferenced. e.g.
2255       // define @foo(%struct.X* %A) {
2256       //   tail call @bar(%struct.X* byval %A)
2257       // }
2258       return false;
2259     SDValue Ptr = Ld->getBasePtr();
2260     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2261     if (!FINode)
2262       return false;
2263     FI = FINode->getIndex();
2264   } else
2265     return false;
2266 
2267   assert(FI != std::numeric_limits<int>::max());
2268   if (!MFI.isFixedObjectIndex(FI))
2269     return false;
2270   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2271 }
2272 
2273 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2274 /// for tail call optimization. Targets which want to do tail call
2275 /// optimization should implement this function.
2276 bool
2277 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2278                                                      CallingConv::ID CalleeCC,
2279                                                      bool isVarArg,
2280                                                      bool isCalleeStructRet,
2281                                                      bool isCallerStructRet,
2282                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2283                                     const SmallVectorImpl<SDValue> &OutVals,
2284                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2285                                                      SelectionDAG& DAG) const {
2286   MachineFunction &MF = DAG.getMachineFunction();
2287   const Function *CallerF = MF.getFunction();
2288   CallingConv::ID CallerCC = CallerF->getCallingConv();
2289 
2290   assert(Subtarget->supportsTailCall());
2291 
2292   // Look for obvious safe cases to perform tail call optimization that do not
2293   // require ABI changes. This is what gcc calls sibcall.
2294 
2295   // Exception-handling functions need a special set of instructions to indicate
2296   // a return to the hardware. Tail-calling another function would probably
2297   // break this.
2298   if (CallerF->hasFnAttribute("interrupt"))
2299     return false;
2300 
2301   // Also avoid sibcall optimization if either caller or callee uses struct
2302   // return semantics.
2303   if (isCalleeStructRet || isCallerStructRet)
2304     return false;
2305 
2306   // Externally-defined functions with weak linkage should not be
2307   // tail-called on ARM when the OS does not support dynamic
2308   // pre-emption of symbols, as the AAELF spec requires normal calls
2309   // to undefined weak functions to be replaced with a NOP or jump to the
2310   // next instruction. The behaviour of branch instructions in this
2311   // situation (as used for tail calls) is implementation-defined, so we
2312   // cannot rely on the linker replacing the tail call with a return.
2313   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2314     const GlobalValue *GV = G->getGlobal();
2315     const Triple &TT = getTargetMachine().getTargetTriple();
2316     if (GV->hasExternalWeakLinkage() &&
2317         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2318       return false;
2319   }
2320 
2321   // Check that the call results are passed in the same way.
2322   LLVMContext &C = *DAG.getContext();
2323   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2324                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2325                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2326     return false;
2327   // The callee has to preserve all registers the caller needs to preserve.
2328   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2329   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2330   if (CalleeCC != CallerCC) {
2331     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2332     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2333       return false;
2334   }
2335 
2336   // If Caller's vararg or byval argument has been split between registers and
2337   // stack, do not perform tail call, since part of the argument is in caller's
2338   // local frame.
2339   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2340   if (AFI_Caller->getArgRegsSaveSize())
2341     return false;
2342 
2343   // If the callee takes no arguments then go on to check the results of the
2344   // call.
2345   if (!Outs.empty()) {
2346     // Check if stack adjustment is needed. For now, do not do this if any
2347     // argument is passed on the stack.
2348     SmallVector<CCValAssign, 16> ArgLocs;
2349     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2350     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2351     if (CCInfo.getNextStackOffset()) {
2352       // Check if the arguments are already laid out in the right way as
2353       // the caller's fixed stack objects.
2354       MachineFrameInfo &MFI = MF.getFrameInfo();
2355       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2356       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2357       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2358            i != e;
2359            ++i, ++realArgIdx) {
2360         CCValAssign &VA = ArgLocs[i];
2361         EVT RegVT = VA.getLocVT();
2362         SDValue Arg = OutVals[realArgIdx];
2363         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2364         if (VA.getLocInfo() == CCValAssign::Indirect)
2365           return false;
2366         if (VA.needsCustom()) {
2367           // f64 and vector types are split into multiple registers or
2368           // register/stack-slot combinations.  The types will not match
2369           // the registers; give up on memory f64 refs until we figure
2370           // out what to do about this.
2371           if (!VA.isRegLoc())
2372             return false;
2373           if (!ArgLocs[++i].isRegLoc())
2374             return false;
2375           if (RegVT == MVT::v2f64) {
2376             if (!ArgLocs[++i].isRegLoc())
2377               return false;
2378             if (!ArgLocs[++i].isRegLoc())
2379               return false;
2380           }
2381         } else if (!VA.isRegLoc()) {
2382           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2383                                    MFI, MRI, TII))
2384             return false;
2385         }
2386       }
2387     }
2388 
2389     const MachineRegisterInfo &MRI = MF.getRegInfo();
2390     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2391       return false;
2392   }
2393 
2394   return true;
2395 }
2396 
2397 bool
2398 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2399                                   MachineFunction &MF, bool isVarArg,
2400                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2401                                   LLVMContext &Context) const {
2402   SmallVector<CCValAssign, 16> RVLocs;
2403   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2404   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2405 }
2406 
2407 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2408                                     const SDLoc &DL, SelectionDAG &DAG) {
2409   const MachineFunction &MF = DAG.getMachineFunction();
2410   const Function *F = MF.getFunction();
2411 
2412   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2413 
2414   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2415   // version of the "preferred return address". These offsets affect the return
2416   // instruction if this is a return from PL1 without hypervisor extensions.
2417   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2418   //    SWI:     0      "subs pc, lr, #0"
2419   //    ABORT:   +4     "subs pc, lr, #4"
2420   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2421   // UNDEF varies depending on where the exception came from ARM or Thumb
2422   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2423 
2424   int64_t LROffset;
2425   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2426       IntKind == "ABORT")
2427     LROffset = 4;
2428   else if (IntKind == "SWI" || IntKind == "UNDEF")
2429     LROffset = 0;
2430   else
2431     report_fatal_error("Unsupported interrupt attribute. If present, value "
2432                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2433 
2434   RetOps.insert(RetOps.begin() + 1,
2435                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2436 
2437   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2438 }
2439 
2440 SDValue
2441 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2442                                bool isVarArg,
2443                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2444                                const SmallVectorImpl<SDValue> &OutVals,
2445                                const SDLoc &dl, SelectionDAG &DAG) const {
2446 
2447   // CCValAssign - represent the assignment of the return value to a location.
2448   SmallVector<CCValAssign, 16> RVLocs;
2449 
2450   // CCState - Info about the registers and stack slots.
2451   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2452                  *DAG.getContext());
2453 
2454   // Analyze outgoing return values.
2455   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2456 
2457   SDValue Flag;
2458   SmallVector<SDValue, 4> RetOps;
2459   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2460   bool isLittleEndian = Subtarget->isLittle();
2461 
2462   MachineFunction &MF = DAG.getMachineFunction();
2463   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2464   AFI->setReturnRegsCount(RVLocs.size());
2465 
2466   // Copy the result values into the output registers.
2467   for (unsigned i = 0, realRVLocIdx = 0;
2468        i != RVLocs.size();
2469        ++i, ++realRVLocIdx) {
2470     CCValAssign &VA = RVLocs[i];
2471     assert(VA.isRegLoc() && "Can only return in registers!");
2472 
2473     SDValue Arg = OutVals[realRVLocIdx];
2474 
2475     switch (VA.getLocInfo()) {
2476     default: llvm_unreachable("Unknown loc info!");
2477     case CCValAssign::Full: break;
2478     case CCValAssign::BCvt:
2479       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2480       break;
2481     }
2482 
2483     if (VA.needsCustom()) {
2484       if (VA.getLocVT() == MVT::v2f64) {
2485         // Extract the first half and return it in two registers.
2486         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2487                                    DAG.getConstant(0, dl, MVT::i32));
2488         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2489                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2490 
2491         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2492                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2493                                  Flag);
2494         Flag = Chain.getValue(1);
2495         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2496         VA = RVLocs[++i]; // skip ahead to next loc
2497         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2498                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2499                                  Flag);
2500         Flag = Chain.getValue(1);
2501         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2502         VA = RVLocs[++i]; // skip ahead to next loc
2503 
2504         // Extract the 2nd half and fall through to handle it as an f64 value.
2505         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2506                           DAG.getConstant(1, dl, MVT::i32));
2507       }
2508       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2509       // available.
2510       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2511                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2512       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2513                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2514                                Flag);
2515       Flag = Chain.getValue(1);
2516       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2517       VA = RVLocs[++i]; // skip ahead to next loc
2518       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2519                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2520                                Flag);
2521     } else
2522       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2523 
2524     // Guarantee that all emitted copies are
2525     // stuck together, avoiding something bad.
2526     Flag = Chain.getValue(1);
2527     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2528   }
2529   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2530   const MCPhysReg *I =
2531       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2532   if (I) {
2533     for (; *I; ++I) {
2534       if (ARM::GPRRegClass.contains(*I))
2535         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2536       else if (ARM::DPRRegClass.contains(*I))
2537         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2538       else
2539         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2540     }
2541   }
2542 
2543   // Update chain and glue.
2544   RetOps[0] = Chain;
2545   if (Flag.getNode())
2546     RetOps.push_back(Flag);
2547 
2548   // CPUs which aren't M-class use a special sequence to return from
2549   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2550   // though we use "subs pc, lr, #N").
2551   //
2552   // M-class CPUs actually use a normal return sequence with a special
2553   // (hardware-provided) value in LR, so the normal code path works.
2554   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2555       !Subtarget->isMClass()) {
2556     if (Subtarget->isThumb1Only())
2557       report_fatal_error("interrupt attribute is not supported in Thumb1");
2558     return LowerInterruptReturn(RetOps, dl, DAG);
2559   }
2560 
2561   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2562 }
2563 
2564 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2565   if (N->getNumValues() != 1)
2566     return false;
2567   if (!N->hasNUsesOfValue(1, 0))
2568     return false;
2569 
2570   SDValue TCChain = Chain;
2571   SDNode *Copy = *N->use_begin();
2572   if (Copy->getOpcode() == ISD::CopyToReg) {
2573     // If the copy has a glue operand, we conservatively assume it isn't safe to
2574     // perform a tail call.
2575     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2576       return false;
2577     TCChain = Copy->getOperand(0);
2578   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2579     SDNode *VMov = Copy;
2580     // f64 returned in a pair of GPRs.
2581     SmallPtrSet<SDNode*, 2> Copies;
2582     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2583          UI != UE; ++UI) {
2584       if (UI->getOpcode() != ISD::CopyToReg)
2585         return false;
2586       Copies.insert(*UI);
2587     }
2588     if (Copies.size() > 2)
2589       return false;
2590 
2591     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2592          UI != UE; ++UI) {
2593       SDValue UseChain = UI->getOperand(0);
2594       if (Copies.count(UseChain.getNode()))
2595         // Second CopyToReg
2596         Copy = *UI;
2597       else {
2598         // We are at the top of this chain.
2599         // If the copy has a glue operand, we conservatively assume it
2600         // isn't safe to perform a tail call.
2601         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2602           return false;
2603         // First CopyToReg
2604         TCChain = UseChain;
2605       }
2606     }
2607   } else if (Copy->getOpcode() == ISD::BITCAST) {
2608     // f32 returned in a single GPR.
2609     if (!Copy->hasOneUse())
2610       return false;
2611     Copy = *Copy->use_begin();
2612     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2613       return false;
2614     // If the copy has a glue operand, we conservatively assume it isn't safe to
2615     // perform a tail call.
2616     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2617       return false;
2618     TCChain = Copy->getOperand(0);
2619   } else {
2620     return false;
2621   }
2622 
2623   bool HasRet = false;
2624   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2625        UI != UE; ++UI) {
2626     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2627         UI->getOpcode() != ARMISD::INTRET_FLAG)
2628       return false;
2629     HasRet = true;
2630   }
2631 
2632   if (!HasRet)
2633     return false;
2634 
2635   Chain = TCChain;
2636   return true;
2637 }
2638 
2639 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2640   if (!Subtarget->supportsTailCall())
2641     return false;
2642 
2643   auto Attr =
2644       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2645   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2646     return false;
2647 
2648   return true;
2649 }
2650 
2651 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2652 // and pass the lower and high parts through.
2653 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2654   SDLoc DL(Op);
2655   SDValue WriteValue = Op->getOperand(2);
2656 
2657   // This function is only supposed to be called for i64 type argument.
2658   assert(WriteValue.getValueType() == MVT::i64
2659           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2660 
2661   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2662                            DAG.getConstant(0, DL, MVT::i32));
2663   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2664                            DAG.getConstant(1, DL, MVT::i32));
2665   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2666   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2667 }
2668 
2669 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2670 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2671 // one of the above mentioned nodes. It has to be wrapped because otherwise
2672 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2673 // be used to form addressing mode. These wrapped nodes will be selected
2674 // into MOVi.
2675 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2676   EVT PtrVT = Op.getValueType();
2677   // FIXME there is no actual debug info here
2678   SDLoc dl(Op);
2679   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2680   SDValue Res;
2681   if (CP->isMachineConstantPoolEntry())
2682     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2683                                     CP->getAlignment());
2684   else
2685     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2686                                     CP->getAlignment());
2687   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2688 }
2689 
2690 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2691   return MachineJumpTableInfo::EK_Inline;
2692 }
2693 
2694 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2695                                              SelectionDAG &DAG) const {
2696   MachineFunction &MF = DAG.getMachineFunction();
2697   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2698   unsigned ARMPCLabelIndex = 0;
2699   SDLoc DL(Op);
2700   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2701   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2702   SDValue CPAddr;
2703   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2704   if (!IsPositionIndependent) {
2705     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2706   } else {
2707     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2708     ARMPCLabelIndex = AFI->createPICLabelUId();
2709     ARMConstantPoolValue *CPV =
2710       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2711                                       ARMCP::CPBlockAddress, PCAdj);
2712     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2713   }
2714   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2715   SDValue Result = DAG.getLoad(
2716       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2717       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2718   if (!IsPositionIndependent)
2719     return Result;
2720   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2721   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2722 }
2723 
2724 /// \brief Convert a TLS address reference into the correct sequence of loads
2725 /// and calls to compute the variable's address for Darwin, and return an
2726 /// SDValue containing the final node.
2727 
2728 /// Darwin only has one TLS scheme which must be capable of dealing with the
2729 /// fully general situation, in the worst case. This means:
2730 ///     + "extern __thread" declaration.
2731 ///     + Defined in a possibly unknown dynamic library.
2732 ///
2733 /// The general system is that each __thread variable has a [3 x i32] descriptor
2734 /// which contains information used by the runtime to calculate the address. The
2735 /// only part of this the compiler needs to know about is the first word, which
2736 /// contains a function pointer that must be called with the address of the
2737 /// entire descriptor in "r0".
2738 ///
2739 /// Since this descriptor may be in a different unit, in general access must
2740 /// proceed along the usual ARM rules. A common sequence to produce is:
2741 ///
2742 ///     movw rT1, :lower16:_var$non_lazy_ptr
2743 ///     movt rT1, :upper16:_var$non_lazy_ptr
2744 ///     ldr r0, [rT1]
2745 ///     ldr rT2, [r0]
2746 ///     blx rT2
2747 ///     [...address now in r0...]
2748 SDValue
2749 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2750                                                SelectionDAG &DAG) const {
2751   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2752   SDLoc DL(Op);
2753 
2754   // First step is to get the address of the actua global symbol. This is where
2755   // the TLS descriptor lives.
2756   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2757 
2758   // The first entry in the descriptor is a function pointer that we must call
2759   // to obtain the address of the variable.
2760   SDValue Chain = DAG.getEntryNode();
2761   SDValue FuncTLVGet = DAG.getLoad(
2762       MVT::i32, DL, Chain, DescAddr,
2763       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2764       /* Alignment = */ 4,
2765       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2766           MachineMemOperand::MOInvariant);
2767   Chain = FuncTLVGet.getValue(1);
2768 
2769   MachineFunction &F = DAG.getMachineFunction();
2770   MachineFrameInfo &MFI = F.getFrameInfo();
2771   MFI.setAdjustsStack(true);
2772 
2773   // TLS calls preserve all registers except those that absolutely must be
2774   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2775   // silly).
2776   auto TRI =
2777       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2778   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2779   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2780 
2781   // Finally, we can make the call. This is just a degenerate version of a
2782   // normal AArch64 call node: r0 takes the address of the descriptor, and
2783   // returns the address of the variable in this thread.
2784   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2785   Chain =
2786       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2787                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2788                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2789   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2790 }
2791 
2792 SDValue
2793 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2794                                                 SelectionDAG &DAG) const {
2795   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2796 
2797   SDValue Chain = DAG.getEntryNode();
2798   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2799   SDLoc DL(Op);
2800 
2801   // Load the current TEB (thread environment block)
2802   SDValue Ops[] = {Chain,
2803                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2804                    DAG.getConstant(15, DL, MVT::i32),
2805                    DAG.getConstant(0, DL, MVT::i32),
2806                    DAG.getConstant(13, DL, MVT::i32),
2807                    DAG.getConstant(0, DL, MVT::i32),
2808                    DAG.getConstant(2, DL, MVT::i32)};
2809   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2810                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2811 
2812   SDValue TEB = CurrentTEB.getValue(0);
2813   Chain = CurrentTEB.getValue(1);
2814 
2815   // Load the ThreadLocalStoragePointer from the TEB
2816   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2817   SDValue TLSArray =
2818       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2819   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2820 
2821   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2822   // offset into the TLSArray.
2823 
2824   // Load the TLS index from the C runtime
2825   SDValue TLSIndex =
2826       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2827   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2828   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2829 
2830   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2831                               DAG.getConstant(2, DL, MVT::i32));
2832   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2833                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2834                             MachinePointerInfo());
2835 
2836   // Get the offset of the start of the .tls section (section base)
2837   const auto *GA = cast<GlobalAddressSDNode>(Op);
2838   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2839   SDValue Offset = DAG.getLoad(
2840       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2841                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2842       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2843 
2844   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2845 }
2846 
2847 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2848 SDValue
2849 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2850                                                  SelectionDAG &DAG) const {
2851   SDLoc dl(GA);
2852   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2853   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2854   MachineFunction &MF = DAG.getMachineFunction();
2855   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2856   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2857   ARMConstantPoolValue *CPV =
2858     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2859                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2860   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2861   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2862   Argument = DAG.getLoad(
2863       PtrVT, dl, DAG.getEntryNode(), Argument,
2864       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2865   SDValue Chain = Argument.getValue(1);
2866 
2867   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2868   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2869 
2870   // call __tls_get_addr.
2871   ArgListTy Args;
2872   ArgListEntry Entry;
2873   Entry.Node = Argument;
2874   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2875   Args.push_back(Entry);
2876 
2877   // FIXME: is there useful debug info available here?
2878   TargetLowering::CallLoweringInfo CLI(DAG);
2879   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2880       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2881       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2882 
2883   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2884   return CallResult.first;
2885 }
2886 
2887 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2888 // "local exec" model.
2889 SDValue
2890 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2891                                         SelectionDAG &DAG,
2892                                         TLSModel::Model model) const {
2893   const GlobalValue *GV = GA->getGlobal();
2894   SDLoc dl(GA);
2895   SDValue Offset;
2896   SDValue Chain = DAG.getEntryNode();
2897   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2898   // Get the Thread Pointer
2899   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2900 
2901   if (model == TLSModel::InitialExec) {
2902     MachineFunction &MF = DAG.getMachineFunction();
2903     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2904     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2905     // Initial exec model.
2906     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2907     ARMConstantPoolValue *CPV =
2908       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2909                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2910                                       true);
2911     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2912     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2913     Offset = DAG.getLoad(
2914         PtrVT, dl, Chain, Offset,
2915         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2916     Chain = Offset.getValue(1);
2917 
2918     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2919     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2920 
2921     Offset = DAG.getLoad(
2922         PtrVT, dl, Chain, Offset,
2923         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2924   } else {
2925     // local exec model
2926     assert(model == TLSModel::LocalExec);
2927     ARMConstantPoolValue *CPV =
2928       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2929     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2930     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2931     Offset = DAG.getLoad(
2932         PtrVT, dl, Chain, Offset,
2933         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2934   }
2935 
2936   // The address of the thread local variable is the add of the thread
2937   // pointer with the offset of the variable.
2938   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2939 }
2940 
2941 SDValue
2942 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2943   if (Subtarget->isTargetDarwin())
2944     return LowerGlobalTLSAddressDarwin(Op, DAG);
2945 
2946   if (Subtarget->isTargetWindows())
2947     return LowerGlobalTLSAddressWindows(Op, DAG);
2948 
2949   // TODO: implement the "local dynamic" model
2950   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2951   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2952   if (DAG.getTarget().Options.EmulatedTLS)
2953     return LowerToTLSEmulatedModel(GA, DAG);
2954 
2955   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2956 
2957   switch (model) {
2958     case TLSModel::GeneralDynamic:
2959     case TLSModel::LocalDynamic:
2960       return LowerToTLSGeneralDynamicModel(GA, DAG);
2961     case TLSModel::InitialExec:
2962     case TLSModel::LocalExec:
2963       return LowerToTLSExecModels(GA, DAG, model);
2964   }
2965   llvm_unreachable("bogus TLS model");
2966 }
2967 
2968 /// Return true if all users of V are within function F, looking through
2969 /// ConstantExprs.
2970 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2971   SmallVector<const User*,4> Worklist;
2972   for (auto *U : V->users())
2973     Worklist.push_back(U);
2974   while (!Worklist.empty()) {
2975     auto *U = Worklist.pop_back_val();
2976     if (isa<ConstantExpr>(U)) {
2977       for (auto *UU : U->users())
2978         Worklist.push_back(UU);
2979       continue;
2980     }
2981 
2982     auto *I = dyn_cast<Instruction>(U);
2983     if (!I || I->getParent()->getParent() != F)
2984       return false;
2985   }
2986   return true;
2987 }
2988 
2989 /// Return true if all users of V are within some (any) function, looking through
2990 /// ConstantExprs. In other words, are there any global constant users?
2991 static bool allUsersAreInFunctions(const Value *V) {
2992   SmallVector<const User*,4> Worklist;
2993   for (auto *U : V->users())
2994     Worklist.push_back(U);
2995   while (!Worklist.empty()) {
2996     auto *U = Worklist.pop_back_val();
2997     if (isa<ConstantExpr>(U)) {
2998       for (auto *UU : U->users())
2999         Worklist.push_back(UU);
3000       continue;
3001     }
3002 
3003     if (!isa<Instruction>(U))
3004       return false;
3005   }
3006   return true;
3007 }
3008 
3009 // Return true if T is an integer, float or an array/vector of either.
3010 static bool isSimpleType(Type *T) {
3011   if (T->isIntegerTy() || T->isFloatingPointTy())
3012     return true;
3013   Type *SubT = nullptr;
3014   if (T->isArrayTy())
3015     SubT = T->getArrayElementType();
3016   else if (T->isVectorTy())
3017     SubT = T->getVectorElementType();
3018   else
3019     return false;
3020   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3021 }
3022 
3023 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3024                                      EVT PtrVT, const SDLoc &dl) {
3025   // If we're creating a pool entry for a constant global with unnamed address,
3026   // and the global is small enough, we can emit it inline into the constant pool
3027   // to save ourselves an indirection.
3028   //
3029   // This is a win if the constant is only used in one function (so it doesn't
3030   // need to be duplicated) or duplicating the constant wouldn't increase code
3031   // size (implying the constant is no larger than 4 bytes).
3032   const Function *F = DAG.getMachineFunction().getFunction();
3033 
3034   // We rely on this decision to inline being idemopotent and unrelated to the
3035   // use-site. We know that if we inline a variable at one use site, we'll
3036   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3037   // doesn't know about this optimization, so bail out if it's enabled else
3038   // we could decide to inline here (and thus never emit the GV) but require
3039   // the GV from fast-isel generated code.
3040   if (!EnableConstpoolPromotion ||
3041       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3042       return SDValue();
3043 
3044   auto *GVar = dyn_cast<GlobalVariable>(GV);
3045   if (!GVar || !GVar->hasInitializer() ||
3046       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3047       !GVar->hasLocalLinkage())
3048     return SDValue();
3049 
3050   // Ensure that we don't try and inline any type that contains pointers. If
3051   // we inline a value that contains relocations, we move the relocations from
3052   // .data to .text which is not ideal.
3053   auto *Init = GVar->getInitializer();
3054   if (!isSimpleType(Init->getType()))
3055     return SDValue();
3056 
3057   // The constant islands pass can only really deal with alignment requests
3058   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3059   // any type wanting greater alignment requirements than 4 bytes. We also
3060   // can only promote constants that are multiples of 4 bytes in size or
3061   // are paddable to a multiple of 4. Currently we only try and pad constants
3062   // that are strings for simplicity.
3063   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3064   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3065   unsigned Align = GVar->getAlignment();
3066   unsigned RequiredPadding = 4 - (Size % 4);
3067   bool PaddingPossible =
3068     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3069   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3070       Size == 0)
3071     return SDValue();
3072 
3073   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3074   MachineFunction &MF = DAG.getMachineFunction();
3075   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3076 
3077   // We can't bloat the constant pool too much, else the ConstantIslands pass
3078   // may fail to converge. If we haven't promoted this global yet (it may have
3079   // multiple uses), and promoting it would increase the constant pool size (Sz
3080   // > 4), ensure we have space to do so up to MaxTotal.
3081   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3082     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3083         ConstpoolPromotionMaxTotal)
3084       return SDValue();
3085 
3086   // This is only valid if all users are in a single function OR it has users
3087   // in multiple functions but it no larger than a pointer. We also check if
3088   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3089   // address taken.
3090   if (!allUsersAreInFunction(GVar, F) &&
3091       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3092     return SDValue();
3093 
3094   // We're going to inline this global. Pad it out if needed.
3095   if (RequiredPadding != 4) {
3096     StringRef S = CDAInit->getAsString();
3097 
3098     SmallVector<uint8_t,16> V(S.size());
3099     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3100     while (RequiredPadding--)
3101       V.push_back(0);
3102     Init = ConstantDataArray::get(*DAG.getContext(), V);
3103   }
3104 
3105   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3106   SDValue CPAddr =
3107     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3108   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3109     AFI->markGlobalAsPromotedToConstantPool(GVar);
3110     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3111                                       PaddedSize - 4);
3112   }
3113   ++NumConstpoolPromoted;
3114   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3115 }
3116 
3117 static bool isReadOnly(const GlobalValue *GV) {
3118   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3119     GV = GA->getBaseObject();
3120   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3121          isa<Function>(GV);
3122 }
3123 
3124 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3125                                                  SelectionDAG &DAG) const {
3126   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3127   SDLoc dl(Op);
3128   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3129   const TargetMachine &TM = getTargetMachine();
3130   bool IsRO = isReadOnly(GV);
3131 
3132   // promoteToConstantPool only if not generating XO text section
3133   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3134     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3135       return V;
3136 
3137   if (isPositionIndependent()) {
3138     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3139 
3140     MachineFunction &MF = DAG.getMachineFunction();
3141     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3142     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3143     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3144     SDLoc dl(Op);
3145     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3146     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3147         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3148         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3149         /*AddCurrentAddress=*/UseGOT_PREL);
3150     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3151     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3152     SDValue Result = DAG.getLoad(
3153         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3154         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3155     SDValue Chain = Result.getValue(1);
3156     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3157     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3158     if (UseGOT_PREL)
3159       Result =
3160           DAG.getLoad(PtrVT, dl, Chain, Result,
3161                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3162     return Result;
3163   } else if (Subtarget->isROPI() && IsRO) {
3164     // PC-relative.
3165     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3166     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3167     return Result;
3168   } else if (Subtarget->isRWPI() && !IsRO) {
3169     // SB-relative.
3170     SDValue RelAddr;
3171     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3172       ++NumMovwMovt;
3173       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3174       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3175     } else { // use literal pool for address constant
3176       ARMConstantPoolValue *CPV =
3177         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3178       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3179       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3180       RelAddr = DAG.getLoad(
3181           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3182           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3183     }
3184     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3185     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3186     return Result;
3187   }
3188 
3189   // If we have T2 ops, we can materialize the address directly via movt/movw
3190   // pair. This is always cheaper.
3191   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3192     ++NumMovwMovt;
3193     // FIXME: Once remat is capable of dealing with instructions with register
3194     // operands, expand this into two nodes.
3195     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3196                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3197   } else {
3198     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3199     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3200     return DAG.getLoad(
3201         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3202         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3203   }
3204 }
3205 
3206 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3207                                                     SelectionDAG &DAG) const {
3208   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3209          "ROPI/RWPI not currently supported for Darwin");
3210   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3211   SDLoc dl(Op);
3212   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3213 
3214   if (Subtarget->useMovt(DAG.getMachineFunction()))
3215     ++NumMovwMovt;
3216 
3217   // FIXME: Once remat is capable of dealing with instructions with register
3218   // operands, expand this into multiple nodes
3219   unsigned Wrapper =
3220       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3221 
3222   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3223   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3224 
3225   if (Subtarget->isGVIndirectSymbol(GV))
3226     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3227                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3228   return Result;
3229 }
3230 
3231 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3232                                                      SelectionDAG &DAG) const {
3233   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3234   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3235          "Windows on ARM expects to use movw/movt");
3236   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3237          "ROPI/RWPI not currently supported for Windows");
3238 
3239   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3240   const ARMII::TOF TargetFlags =
3241     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3242   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3243   SDValue Result;
3244   SDLoc DL(Op);
3245 
3246   ++NumMovwMovt;
3247 
3248   // FIXME: Once remat is capable of dealing with instructions with register
3249   // operands, expand this into two nodes.
3250   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3251                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3252                                                   TargetFlags));
3253   if (GV->hasDLLImportStorageClass())
3254     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3255                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3256   return Result;
3257 }
3258 
3259 SDValue
3260 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3261   SDLoc dl(Op);
3262   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3263   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3264                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3265                      Op.getOperand(1), Val);
3266 }
3267 
3268 SDValue
3269 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3270   SDLoc dl(Op);
3271   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3272                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3273 }
3274 
3275 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3276                                                       SelectionDAG &DAG) const {
3277   SDLoc dl(Op);
3278   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3279                      Op.getOperand(0));
3280 }
3281 
3282 SDValue
3283 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3284                                           const ARMSubtarget *Subtarget) const {
3285   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3286   SDLoc dl(Op);
3287   switch (IntNo) {
3288   default: return SDValue();    // Don't custom lower most intrinsics.
3289   case Intrinsic::thread_pointer: {
3290     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3291     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3292   }
3293   case Intrinsic::eh_sjlj_lsda: {
3294     MachineFunction &MF = DAG.getMachineFunction();
3295     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3296     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3297     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3298     SDValue CPAddr;
3299     bool IsPositionIndependent = isPositionIndependent();
3300     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3301     ARMConstantPoolValue *CPV =
3302       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3303                                       ARMCP::CPLSDA, PCAdj);
3304     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3305     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3306     SDValue Result = DAG.getLoad(
3307         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3308         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3309 
3310     if (IsPositionIndependent) {
3311       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3312       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3313     }
3314     return Result;
3315   }
3316   case Intrinsic::arm_neon_vmulls:
3317   case Intrinsic::arm_neon_vmullu: {
3318     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3319       ? ARMISD::VMULLs : ARMISD::VMULLu;
3320     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3321                        Op.getOperand(1), Op.getOperand(2));
3322   }
3323   case Intrinsic::arm_neon_vminnm:
3324   case Intrinsic::arm_neon_vmaxnm: {
3325     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3326       ? ISD::FMINNUM : ISD::FMAXNUM;
3327     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3328                        Op.getOperand(1), Op.getOperand(2));
3329   }
3330   case Intrinsic::arm_neon_vminu:
3331   case Intrinsic::arm_neon_vmaxu: {
3332     if (Op.getValueType().isFloatingPoint())
3333       return SDValue();
3334     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3335       ? ISD::UMIN : ISD::UMAX;
3336     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3337                          Op.getOperand(1), Op.getOperand(2));
3338   }
3339   case Intrinsic::arm_neon_vmins:
3340   case Intrinsic::arm_neon_vmaxs: {
3341     // v{min,max}s is overloaded between signed integers and floats.
3342     if (!Op.getValueType().isFloatingPoint()) {
3343       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3344         ? ISD::SMIN : ISD::SMAX;
3345       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3346                          Op.getOperand(1), Op.getOperand(2));
3347     }
3348     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3349       ? ISD::FMINNAN : ISD::FMAXNAN;
3350     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3351                        Op.getOperand(1), Op.getOperand(2));
3352   }
3353   }
3354 }
3355 
3356 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3357                                  const ARMSubtarget *Subtarget) {
3358   // FIXME: handle "fence singlethread" more efficiently.
3359   SDLoc dl(Op);
3360   if (!Subtarget->hasDataBarrier()) {
3361     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3362     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3363     // here.
3364     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3365            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3366     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3367                        DAG.getConstant(0, dl, MVT::i32));
3368   }
3369 
3370   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3371   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3372   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3373   if (Subtarget->isMClass()) {
3374     // Only a full system barrier exists in the M-class architectures.
3375     Domain = ARM_MB::SY;
3376   } else if (Subtarget->preferISHSTBarriers() &&
3377              Ord == AtomicOrdering::Release) {
3378     // Swift happens to implement ISHST barriers in a way that's compatible with
3379     // Release semantics but weaker than ISH so we'd be fools not to use
3380     // it. Beware: other processors probably don't!
3381     Domain = ARM_MB::ISHST;
3382   }
3383 
3384   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3385                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3386                      DAG.getConstant(Domain, dl, MVT::i32));
3387 }
3388 
3389 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3390                              const ARMSubtarget *Subtarget) {
3391   // ARM pre v5TE and Thumb1 does not have preload instructions.
3392   if (!(Subtarget->isThumb2() ||
3393         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3394     // Just preserve the chain.
3395     return Op.getOperand(0);
3396 
3397   SDLoc dl(Op);
3398   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3399   if (!isRead &&
3400       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3401     // ARMv7 with MP extension has PLDW.
3402     return Op.getOperand(0);
3403 
3404   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3405   if (Subtarget->isThumb()) {
3406     // Invert the bits.
3407     isRead = ~isRead & 1;
3408     isData = ~isData & 1;
3409   }
3410 
3411   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3412                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3413                      DAG.getConstant(isData, dl, MVT::i32));
3414 }
3415 
3416 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3417   MachineFunction &MF = DAG.getMachineFunction();
3418   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3419 
3420   // vastart just stores the address of the VarArgsFrameIndex slot into the
3421   // memory location argument.
3422   SDLoc dl(Op);
3423   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3424   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3425   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3426   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3427                       MachinePointerInfo(SV));
3428 }
3429 
3430 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3431                                                 CCValAssign &NextVA,
3432                                                 SDValue &Root,
3433                                                 SelectionDAG &DAG,
3434                                                 const SDLoc &dl) const {
3435   MachineFunction &MF = DAG.getMachineFunction();
3436   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3437 
3438   const TargetRegisterClass *RC;
3439   if (AFI->isThumb1OnlyFunction())
3440     RC = &ARM::tGPRRegClass;
3441   else
3442     RC = &ARM::GPRRegClass;
3443 
3444   // Transform the arguments stored in physical registers into virtual ones.
3445   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3446   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3447 
3448   SDValue ArgValue2;
3449   if (NextVA.isMemLoc()) {
3450     MachineFrameInfo &MFI = MF.getFrameInfo();
3451     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3452 
3453     // Create load node to retrieve arguments from the stack.
3454     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3455     ArgValue2 = DAG.getLoad(
3456         MVT::i32, dl, Root, FIN,
3457         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3458   } else {
3459     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3460     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3461   }
3462   if (!Subtarget->isLittle())
3463     std::swap (ArgValue, ArgValue2);
3464   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3465 }
3466 
3467 // The remaining GPRs hold either the beginning of variable-argument
3468 // data, or the beginning of an aggregate passed by value (usually
3469 // byval).  Either way, we allocate stack slots adjacent to the data
3470 // provided by our caller, and store the unallocated registers there.
3471 // If this is a variadic function, the va_list pointer will begin with
3472 // these values; otherwise, this reassembles a (byval) structure that
3473 // was split between registers and memory.
3474 // Return: The frame index registers were stored into.
3475 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3476                                       const SDLoc &dl, SDValue &Chain,
3477                                       const Value *OrigArg,
3478                                       unsigned InRegsParamRecordIdx,
3479                                       int ArgOffset, unsigned ArgSize) const {
3480   // Currently, two use-cases possible:
3481   // Case #1. Non-var-args function, and we meet first byval parameter.
3482   //          Setup first unallocated register as first byval register;
3483   //          eat all remained registers
3484   //          (these two actions are performed by HandleByVal method).
3485   //          Then, here, we initialize stack frame with
3486   //          "store-reg" instructions.
3487   // Case #2. Var-args function, that doesn't contain byval parameters.
3488   //          The same: eat all remained unallocated registers,
3489   //          initialize stack frame.
3490 
3491   MachineFunction &MF = DAG.getMachineFunction();
3492   MachineFrameInfo &MFI = MF.getFrameInfo();
3493   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3494   unsigned RBegin, REnd;
3495   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3496     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3497   } else {
3498     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3499     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3500     REnd = ARM::R4;
3501   }
3502 
3503   if (REnd != RBegin)
3504     ArgOffset = -4 * (ARM::R4 - RBegin);
3505 
3506   auto PtrVT = getPointerTy(DAG.getDataLayout());
3507   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3508   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3509 
3510   SmallVector<SDValue, 4> MemOps;
3511   const TargetRegisterClass *RC =
3512       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3513 
3514   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3515     unsigned VReg = MF.addLiveIn(Reg, RC);
3516     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3517     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3518                                  MachinePointerInfo(OrigArg, 4 * i));
3519     MemOps.push_back(Store);
3520     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3521   }
3522 
3523   if (!MemOps.empty())
3524     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3525   return FrameIndex;
3526 }
3527 
3528 // Setup stack frame, the va_list pointer will start from.
3529 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3530                                              const SDLoc &dl, SDValue &Chain,
3531                                              unsigned ArgOffset,
3532                                              unsigned TotalArgRegsSaveSize,
3533                                              bool ForceMutable) const {
3534   MachineFunction &MF = DAG.getMachineFunction();
3535   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3536 
3537   // Try to store any remaining integer argument regs
3538   // to their spots on the stack so that they may be loaded by dereferencing
3539   // the result of va_next.
3540   // If there is no regs to be stored, just point address after last
3541   // argument passed via stack.
3542   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3543                                   CCInfo.getInRegsParamsCount(),
3544                                   CCInfo.getNextStackOffset(), 4);
3545   AFI->setVarArgsFrameIndex(FrameIndex);
3546 }
3547 
3548 SDValue ARMTargetLowering::LowerFormalArguments(
3549     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3550     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3551     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3552   MachineFunction &MF = DAG.getMachineFunction();
3553   MachineFrameInfo &MFI = MF.getFrameInfo();
3554 
3555   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3556 
3557   // Assign locations to all of the incoming arguments.
3558   SmallVector<CCValAssign, 16> ArgLocs;
3559   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3560                  *DAG.getContext());
3561   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3562 
3563   SmallVector<SDValue, 16> ArgValues;
3564   SDValue ArgValue;
3565   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3566   unsigned CurArgIdx = 0;
3567 
3568   // Initially ArgRegsSaveSize is zero.
3569   // Then we increase this value each time we meet byval parameter.
3570   // We also increase this value in case of varargs function.
3571   AFI->setArgRegsSaveSize(0);
3572 
3573   // Calculate the amount of stack space that we need to allocate to store
3574   // byval and variadic arguments that are passed in registers.
3575   // We need to know this before we allocate the first byval or variadic
3576   // argument, as they will be allocated a stack slot below the CFA (Canonical
3577   // Frame Address, the stack pointer at entry to the function).
3578   unsigned ArgRegBegin = ARM::R4;
3579   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3580     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3581       break;
3582 
3583     CCValAssign &VA = ArgLocs[i];
3584     unsigned Index = VA.getValNo();
3585     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3586     if (!Flags.isByVal())
3587       continue;
3588 
3589     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3590     unsigned RBegin, REnd;
3591     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3592     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3593 
3594     CCInfo.nextInRegsParam();
3595   }
3596   CCInfo.rewindByValRegsInfo();
3597 
3598   int lastInsIndex = -1;
3599   if (isVarArg && MFI.hasVAStart()) {
3600     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3601     if (RegIdx != array_lengthof(GPRArgRegs))
3602       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3603   }
3604 
3605   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3606   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3607   auto PtrVT = getPointerTy(DAG.getDataLayout());
3608 
3609   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3610     CCValAssign &VA = ArgLocs[i];
3611     if (Ins[VA.getValNo()].isOrigArg()) {
3612       std::advance(CurOrigArg,
3613                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3614       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3615     }
3616     // Arguments stored in registers.
3617     if (VA.isRegLoc()) {
3618       EVT RegVT = VA.getLocVT();
3619 
3620       if (VA.needsCustom()) {
3621         // f64 and vector types are split up into multiple registers or
3622         // combinations of registers and stack slots.
3623         if (VA.getLocVT() == MVT::v2f64) {
3624           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3625                                                    Chain, DAG, dl);
3626           VA = ArgLocs[++i]; // skip ahead to next loc
3627           SDValue ArgValue2;
3628           if (VA.isMemLoc()) {
3629             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3630             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3631             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3632                                     MachinePointerInfo::getFixedStack(
3633                                         DAG.getMachineFunction(), FI));
3634           } else {
3635             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3636                                              Chain, DAG, dl);
3637           }
3638           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3639           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3640                                  ArgValue, ArgValue1,
3641                                  DAG.getIntPtrConstant(0, dl));
3642           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3643                                  ArgValue, ArgValue2,
3644                                  DAG.getIntPtrConstant(1, dl));
3645         } else
3646           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3647 
3648       } else {
3649         const TargetRegisterClass *RC;
3650 
3651         if (RegVT == MVT::f32)
3652           RC = &ARM::SPRRegClass;
3653         else if (RegVT == MVT::f64)
3654           RC = &ARM::DPRRegClass;
3655         else if (RegVT == MVT::v2f64)
3656           RC = &ARM::QPRRegClass;
3657         else if (RegVT == MVT::i32)
3658           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3659                                            : &ARM::GPRRegClass;
3660         else
3661           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3662 
3663         // Transform the arguments in physical registers into virtual ones.
3664         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3665         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3666       }
3667 
3668       // If this is an 8 or 16-bit value, it is really passed promoted
3669       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3670       // truncate to the right size.
3671       switch (VA.getLocInfo()) {
3672       default: llvm_unreachable("Unknown loc info!");
3673       case CCValAssign::Full: break;
3674       case CCValAssign::BCvt:
3675         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3676         break;
3677       case CCValAssign::SExt:
3678         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3679                                DAG.getValueType(VA.getValVT()));
3680         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3681         break;
3682       case CCValAssign::ZExt:
3683         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3684                                DAG.getValueType(VA.getValVT()));
3685         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3686         break;
3687       }
3688 
3689       InVals.push_back(ArgValue);
3690 
3691     } else { // VA.isRegLoc()
3692       // sanity check
3693       assert(VA.isMemLoc());
3694       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3695 
3696       int index = VA.getValNo();
3697 
3698       // Some Ins[] entries become multiple ArgLoc[] entries.
3699       // Process them only once.
3700       if (index != lastInsIndex)
3701         {
3702           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3703           // FIXME: For now, all byval parameter objects are marked mutable.
3704           // This can be changed with more analysis.
3705           // In case of tail call optimization mark all arguments mutable.
3706           // Since they could be overwritten by lowering of arguments in case of
3707           // a tail call.
3708           if (Flags.isByVal()) {
3709             assert(Ins[index].isOrigArg() &&
3710                    "Byval arguments cannot be implicit");
3711             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3712 
3713             int FrameIndex = StoreByValRegs(
3714                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3715                 VA.getLocMemOffset(), Flags.getByValSize());
3716             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3717             CCInfo.nextInRegsParam();
3718           } else {
3719             unsigned FIOffset = VA.getLocMemOffset();
3720             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3721                                            FIOffset, true);
3722 
3723             // Create load nodes to retrieve arguments from the stack.
3724             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3725             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3726                                          MachinePointerInfo::getFixedStack(
3727                                              DAG.getMachineFunction(), FI)));
3728           }
3729           lastInsIndex = index;
3730         }
3731     }
3732   }
3733 
3734   // varargs
3735   if (isVarArg && MFI.hasVAStart())
3736     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3737                          CCInfo.getNextStackOffset(),
3738                          TotalArgRegsSaveSize);
3739 
3740   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3741 
3742   return Chain;
3743 }
3744 
3745 /// isFloatingPointZero - Return true if this is +0.0.
3746 static bool isFloatingPointZero(SDValue Op) {
3747   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3748     return CFP->getValueAPF().isPosZero();
3749   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3750     // Maybe this has already been legalized into the constant pool?
3751     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3752       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3753       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3754         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3755           return CFP->getValueAPF().isPosZero();
3756     }
3757   } else if (Op->getOpcode() == ISD::BITCAST &&
3758              Op->getValueType(0) == MVT::f64) {
3759     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3760     // created by LowerConstantFP().
3761     SDValue BitcastOp = Op->getOperand(0);
3762     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3763         isNullConstant(BitcastOp->getOperand(0)))
3764       return true;
3765   }
3766   return false;
3767 }
3768 
3769 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3770 /// the given operands.
3771 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3772                                      SDValue &ARMcc, SelectionDAG &DAG,
3773                                      const SDLoc &dl) const {
3774   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3775     unsigned C = RHSC->getZExtValue();
3776     if (!isLegalICmpImmediate(C)) {
3777       // Constant does not fit, try adjusting it by one?
3778       switch (CC) {
3779       default: break;
3780       case ISD::SETLT:
3781       case ISD::SETGE:
3782         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3783           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3784           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3785         }
3786         break;
3787       case ISD::SETULT:
3788       case ISD::SETUGE:
3789         if (C != 0 && isLegalICmpImmediate(C-1)) {
3790           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3791           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3792         }
3793         break;
3794       case ISD::SETLE:
3795       case ISD::SETGT:
3796         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3797           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3798           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3799         }
3800         break;
3801       case ISD::SETULE:
3802       case ISD::SETUGT:
3803         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3804           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3805           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3806         }
3807         break;
3808       }
3809     }
3810   }
3811 
3812   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3813   ARMISD::NodeType CompareType;
3814   switch (CondCode) {
3815   default:
3816     CompareType = ARMISD::CMP;
3817     break;
3818   case ARMCC::EQ:
3819   case ARMCC::NE:
3820     // Uses only Z Flag
3821     CompareType = ARMISD::CMPZ;
3822     break;
3823   }
3824   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3825   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3826 }
3827 
3828 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3829 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3830                                      SelectionDAG &DAG, const SDLoc &dl,
3831                                      bool InvalidOnQNaN) const {
3832   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3833   SDValue Cmp;
3834   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3835   if (!isFloatingPointZero(RHS))
3836     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3837   else
3838     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3839   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3840 }
3841 
3842 /// duplicateCmp - Glue values can have only one use, so this function
3843 /// duplicates a comparison node.
3844 SDValue
3845 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3846   unsigned Opc = Cmp.getOpcode();
3847   SDLoc DL(Cmp);
3848   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3849     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3850 
3851   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3852   Cmp = Cmp.getOperand(0);
3853   Opc = Cmp.getOpcode();
3854   if (Opc == ARMISD::CMPFP)
3855     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3856                       Cmp.getOperand(1), Cmp.getOperand(2));
3857   else {
3858     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3859     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3860                       Cmp.getOperand(1));
3861   }
3862   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3863 }
3864 
3865 std::pair<SDValue, SDValue>
3866 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3867                                  SDValue &ARMcc) const {
3868   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3869 
3870   SDValue Value, OverflowCmp;
3871   SDValue LHS = Op.getOperand(0);
3872   SDValue RHS = Op.getOperand(1);
3873   SDLoc dl(Op);
3874 
3875   // FIXME: We are currently always generating CMPs because we don't support
3876   // generating CMN through the backend. This is not as good as the natural
3877   // CMP case because it causes a register dependency and cannot be folded
3878   // later.
3879 
3880   switch (Op.getOpcode()) {
3881   default:
3882     llvm_unreachable("Unknown overflow instruction!");
3883   case ISD::SADDO:
3884     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3885     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3886     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3887     break;
3888   case ISD::UADDO:
3889     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3890     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3891     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3892     break;
3893   case ISD::SSUBO:
3894     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3895     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3896     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3897     break;
3898   case ISD::USUBO:
3899     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3900     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3901     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3902     break;
3903   } // switch (...)
3904 
3905   return std::make_pair(Value, OverflowCmp);
3906 }
3907 
3908 SDValue
3909 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3910   // Let legalize expand this if it isn't a legal type yet.
3911   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3912     return SDValue();
3913 
3914   SDValue Value, OverflowCmp;
3915   SDValue ARMcc;
3916   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3917   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3918   SDLoc dl(Op);
3919   // We use 0 and 1 as false and true values.
3920   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3921   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3922   EVT VT = Op.getValueType();
3923 
3924   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3925                                  ARMcc, CCR, OverflowCmp);
3926 
3927   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3928   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3929 }
3930 
3931 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3932   SDValue Cond = Op.getOperand(0);
3933   SDValue SelectTrue = Op.getOperand(1);
3934   SDValue SelectFalse = Op.getOperand(2);
3935   SDLoc dl(Op);
3936   unsigned Opc = Cond.getOpcode();
3937 
3938   if (Cond.getResNo() == 1 &&
3939       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3940        Opc == ISD::USUBO)) {
3941     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3942       return SDValue();
3943 
3944     SDValue Value, OverflowCmp;
3945     SDValue ARMcc;
3946     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3947     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3948     EVT VT = Op.getValueType();
3949 
3950     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3951                    OverflowCmp, DAG);
3952   }
3953 
3954   // Convert:
3955   //
3956   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3957   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3958   //
3959   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3960     const ConstantSDNode *CMOVTrue =
3961       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3962     const ConstantSDNode *CMOVFalse =
3963       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3964 
3965     if (CMOVTrue && CMOVFalse) {
3966       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3967       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3968 
3969       SDValue True;
3970       SDValue False;
3971       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3972         True = SelectTrue;
3973         False = SelectFalse;
3974       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3975         True = SelectFalse;
3976         False = SelectTrue;
3977       }
3978 
3979       if (True.getNode() && False.getNode()) {
3980         EVT VT = Op.getValueType();
3981         SDValue ARMcc = Cond.getOperand(2);
3982         SDValue CCR = Cond.getOperand(3);
3983         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3984         assert(True.getValueType() == VT);
3985         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3986       }
3987     }
3988   }
3989 
3990   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3991   // undefined bits before doing a full-word comparison with zero.
3992   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3993                      DAG.getConstant(1, dl, Cond.getValueType()));
3994 
3995   return DAG.getSelectCC(dl, Cond,
3996                          DAG.getConstant(0, dl, Cond.getValueType()),
3997                          SelectTrue, SelectFalse, ISD::SETNE);
3998 }
3999 
4000 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4001                                  bool &swpCmpOps, bool &swpVselOps) {
4002   // Start by selecting the GE condition code for opcodes that return true for
4003   // 'equality'
4004   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4005       CC == ISD::SETULE)
4006     CondCode = ARMCC::GE;
4007 
4008   // and GT for opcodes that return false for 'equality'.
4009   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4010            CC == ISD::SETULT)
4011     CondCode = ARMCC::GT;
4012 
4013   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4014   // to swap the compare operands.
4015   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4016       CC == ISD::SETULT)
4017     swpCmpOps = true;
4018 
4019   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4020   // If we have an unordered opcode, we need to swap the operands to the VSEL
4021   // instruction (effectively negating the condition).
4022   //
4023   // This also has the effect of swapping which one of 'less' or 'greater'
4024   // returns true, so we also swap the compare operands. It also switches
4025   // whether we return true for 'equality', so we compensate by picking the
4026   // opposite condition code to our original choice.
4027   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4028       CC == ISD::SETUGT) {
4029     swpCmpOps = !swpCmpOps;
4030     swpVselOps = !swpVselOps;
4031     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4032   }
4033 
4034   // 'ordered' is 'anything but unordered', so use the VS condition code and
4035   // swap the VSEL operands.
4036   if (CC == ISD::SETO) {
4037     CondCode = ARMCC::VS;
4038     swpVselOps = true;
4039   }
4040 
4041   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4042   // code and swap the VSEL operands.
4043   if (CC == ISD::SETUNE) {
4044     CondCode = ARMCC::EQ;
4045     swpVselOps = true;
4046   }
4047 }
4048 
4049 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4050                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4051                                    SDValue Cmp, SelectionDAG &DAG) const {
4052   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4053     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4054                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4055     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4056                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4057 
4058     SDValue TrueLow = TrueVal.getValue(0);
4059     SDValue TrueHigh = TrueVal.getValue(1);
4060     SDValue FalseLow = FalseVal.getValue(0);
4061     SDValue FalseHigh = FalseVal.getValue(1);
4062 
4063     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4064                               ARMcc, CCR, Cmp);
4065     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4066                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4067 
4068     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4069   } else {
4070     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4071                        Cmp);
4072   }
4073 }
4074 
4075 static bool isGTorGE(ISD::CondCode CC) {
4076   return CC == ISD::SETGT || CC == ISD::SETGE;
4077 }
4078 
4079 static bool isLTorLE(ISD::CondCode CC) {
4080   return CC == ISD::SETLT || CC == ISD::SETLE;
4081 }
4082 
4083 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4084 // All of these conditions (and their <= and >= counterparts) will do:
4085 //          x < k ? k : x
4086 //          x > k ? x : k
4087 //          k < x ? x : k
4088 //          k > x ? k : x
4089 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4090                             const SDValue TrueVal, const SDValue FalseVal,
4091                             const ISD::CondCode CC, const SDValue K) {
4092   return (isGTorGE(CC) &&
4093           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4094          (isLTorLE(CC) &&
4095           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4096 }
4097 
4098 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4099 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4100                             const SDValue TrueVal, const SDValue FalseVal,
4101                             const ISD::CondCode CC, const SDValue K) {
4102   return (isGTorGE(CC) &&
4103           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4104          (isLTorLE(CC) &&
4105           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4106 }
4107 
4108 // Check if two chained conditionals could be converted into SSAT.
4109 //
4110 // SSAT can replace a set of two conditional selectors that bound a number to an
4111 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4112 //
4113 //     x < -k ? -k : (x > k ? k : x)
4114 //     x < -k ? -k : (x < k ? x : k)
4115 //     x > -k ? (x > k ? k : x) : -k
4116 //     x < k ? (x < -k ? -k : x) : k
4117 //     etc.
4118 //
4119 // It returns true if the conversion can be done, false otherwise.
4120 // Additionally, the variable is returned in parameter V and the constant in K.
4121 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4122                                     uint64_t &K) {
4123   SDValue LHS1 = Op.getOperand(0);
4124   SDValue RHS1 = Op.getOperand(1);
4125   SDValue TrueVal1 = Op.getOperand(2);
4126   SDValue FalseVal1 = Op.getOperand(3);
4127   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4128 
4129   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4130   if (Op2.getOpcode() != ISD::SELECT_CC)
4131     return false;
4132 
4133   SDValue LHS2 = Op2.getOperand(0);
4134   SDValue RHS2 = Op2.getOperand(1);
4135   SDValue TrueVal2 = Op2.getOperand(2);
4136   SDValue FalseVal2 = Op2.getOperand(3);
4137   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4138 
4139   // Find out which are the constants and which are the variables
4140   // in each conditional
4141   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4142                                                         ? &RHS1
4143                                                         : nullptr;
4144   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4145                                                         ? &RHS2
4146                                                         : nullptr;
4147   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4148   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4149   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4150   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4151 
4152   // We must detect cases where the original operations worked with 16- or
4153   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4154   // must work with sign-extended values but the select operations return
4155   // the original non-extended value.
4156   SDValue V2TmpReg = V2Tmp;
4157   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4158     V2TmpReg = V2Tmp->getOperand(0);
4159 
4160   // Check that the registers and the constants have the correct values
4161   // in both conditionals
4162   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4163       V2TmpReg != V2)
4164     return false;
4165 
4166   // Figure out which conditional is saturating the lower/upper bound.
4167   const SDValue *LowerCheckOp =
4168       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4169           ? &Op
4170           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4171                 ? &Op2
4172                 : nullptr;
4173   const SDValue *UpperCheckOp =
4174       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4175           ? &Op
4176           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4177                 ? &Op2
4178                 : nullptr;
4179 
4180   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4181     return false;
4182 
4183   // Check that the constant in the lower-bound check is
4184   // the opposite of the constant in the upper-bound check
4185   // in 1's complement.
4186   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4187   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4188   int64_t PosVal = std::max(Val1, Val2);
4189 
4190   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4191        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4192       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4193 
4194     V = V2;
4195     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4196     return true;
4197   }
4198 
4199   return false;
4200 }
4201 
4202 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4203   EVT VT = Op.getValueType();
4204   SDLoc dl(Op);
4205 
4206   // Try to convert two saturating conditional selects into a single SSAT
4207   SDValue SatValue;
4208   uint64_t SatConstant;
4209   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4210       isSaturatingConditional(Op, SatValue, SatConstant))
4211     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4212                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4213 
4214   SDValue LHS = Op.getOperand(0);
4215   SDValue RHS = Op.getOperand(1);
4216   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4217   SDValue TrueVal = Op.getOperand(2);
4218   SDValue FalseVal = Op.getOperand(3);
4219 
4220   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4221     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4222                                                     dl);
4223 
4224     // If softenSetCCOperands only returned one value, we should compare it to
4225     // zero.
4226     if (!RHS.getNode()) {
4227       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4228       CC = ISD::SETNE;
4229     }
4230   }
4231 
4232   if (LHS.getValueType() == MVT::i32) {
4233     // Try to generate VSEL on ARMv8.
4234     // The VSEL instruction can't use all the usual ARM condition
4235     // codes: it only has two bits to select the condition code, so it's
4236     // constrained to use only GE, GT, VS and EQ.
4237     //
4238     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4239     // swap the operands of the previous compare instruction (effectively
4240     // inverting the compare condition, swapping 'less' and 'greater') and
4241     // sometimes need to swap the operands to the VSEL (which inverts the
4242     // condition in the sense of firing whenever the previous condition didn't)
4243     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4244                                     TrueVal.getValueType() == MVT::f64)) {
4245       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4246       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4247           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4248         CC = ISD::getSetCCInverse(CC, true);
4249         std::swap(TrueVal, FalseVal);
4250       }
4251     }
4252 
4253     SDValue ARMcc;
4254     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4256     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4257   }
4258 
4259   ARMCC::CondCodes CondCode, CondCode2;
4260   bool InvalidOnQNaN;
4261   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4262 
4263   // Try to generate VMAXNM/VMINNM on ARMv8.
4264   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4265                                   TrueVal.getValueType() == MVT::f64)) {
4266     bool swpCmpOps = false;
4267     bool swpVselOps = false;
4268     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4269 
4270     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4271         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4272       if (swpCmpOps)
4273         std::swap(LHS, RHS);
4274       if (swpVselOps)
4275         std::swap(TrueVal, FalseVal);
4276     }
4277   }
4278 
4279   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4280   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4281   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4282   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4283   if (CondCode2 != ARMCC::AL) {
4284     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4285     // FIXME: Needs another CMP because flag can have but one use.
4286     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4287     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4288   }
4289   return Result;
4290 }
4291 
4292 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4293 /// to morph to an integer compare sequence.
4294 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4295                            const ARMSubtarget *Subtarget) {
4296   SDNode *N = Op.getNode();
4297   if (!N->hasOneUse())
4298     // Otherwise it requires moving the value from fp to integer registers.
4299     return false;
4300   if (!N->getNumValues())
4301     return false;
4302   EVT VT = Op.getValueType();
4303   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4304     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4305     // vmrs are very slow, e.g. cortex-a8.
4306     return false;
4307 
4308   if (isFloatingPointZero(Op)) {
4309     SeenZero = true;
4310     return true;
4311   }
4312   return ISD::isNormalLoad(N);
4313 }
4314 
4315 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4316   if (isFloatingPointZero(Op))
4317     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4318 
4319   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4320     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4321                        Ld->getPointerInfo(), Ld->getAlignment(),
4322                        Ld->getMemOperand()->getFlags());
4323 
4324   llvm_unreachable("Unknown VFP cmp argument!");
4325 }
4326 
4327 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4328                            SDValue &RetVal1, SDValue &RetVal2) {
4329   SDLoc dl(Op);
4330 
4331   if (isFloatingPointZero(Op)) {
4332     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4333     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4334     return;
4335   }
4336 
4337   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4338     SDValue Ptr = Ld->getBasePtr();
4339     RetVal1 =
4340         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4341                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4342 
4343     EVT PtrType = Ptr.getValueType();
4344     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4345     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4346                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4347     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4348                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4349                           Ld->getMemOperand()->getFlags());
4350     return;
4351   }
4352 
4353   llvm_unreachable("Unknown VFP cmp argument!");
4354 }
4355 
4356 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4357 /// f32 and even f64 comparisons to integer ones.
4358 SDValue
4359 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4360   SDValue Chain = Op.getOperand(0);
4361   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4362   SDValue LHS = Op.getOperand(2);
4363   SDValue RHS = Op.getOperand(3);
4364   SDValue Dest = Op.getOperand(4);
4365   SDLoc dl(Op);
4366 
4367   bool LHSSeenZero = false;
4368   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4369   bool RHSSeenZero = false;
4370   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4371   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4372     // If unsafe fp math optimization is enabled and there are no other uses of
4373     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4374     // to an integer comparison.
4375     if (CC == ISD::SETOEQ)
4376       CC = ISD::SETEQ;
4377     else if (CC == ISD::SETUNE)
4378       CC = ISD::SETNE;
4379 
4380     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4381     SDValue ARMcc;
4382     if (LHS.getValueType() == MVT::f32) {
4383       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4384                         bitcastf32Toi32(LHS, DAG), Mask);
4385       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4386                         bitcastf32Toi32(RHS, DAG), Mask);
4387       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4388       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4389       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4390                          Chain, Dest, ARMcc, CCR, Cmp);
4391     }
4392 
4393     SDValue LHS1, LHS2;
4394     SDValue RHS1, RHS2;
4395     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4396     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4397     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4398     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4399     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4400     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4401     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4402     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4403     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4404   }
4405 
4406   return SDValue();
4407 }
4408 
4409 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4410   SDValue Chain = Op.getOperand(0);
4411   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4412   SDValue LHS = Op.getOperand(2);
4413   SDValue RHS = Op.getOperand(3);
4414   SDValue Dest = Op.getOperand(4);
4415   SDLoc dl(Op);
4416 
4417   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4418     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4419                                                     dl);
4420 
4421     // If softenSetCCOperands only returned one value, we should compare it to
4422     // zero.
4423     if (!RHS.getNode()) {
4424       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4425       CC = ISD::SETNE;
4426     }
4427   }
4428 
4429   if (LHS.getValueType() == MVT::i32) {
4430     SDValue ARMcc;
4431     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4432     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4433     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4434                        Chain, Dest, ARMcc, CCR, Cmp);
4435   }
4436 
4437   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4438 
4439   if (getTargetMachine().Options.UnsafeFPMath &&
4440       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4441        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4442     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4443       return Result;
4444   }
4445 
4446   ARMCC::CondCodes CondCode, CondCode2;
4447   bool InvalidOnQNaN;
4448   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4449 
4450   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4451   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4452   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4453   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4454   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4455   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4456   if (CondCode2 != ARMCC::AL) {
4457     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4458     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4459     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4460   }
4461   return Res;
4462 }
4463 
4464 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4465   SDValue Chain = Op.getOperand(0);
4466   SDValue Table = Op.getOperand(1);
4467   SDValue Index = Op.getOperand(2);
4468   SDLoc dl(Op);
4469 
4470   EVT PTy = getPointerTy(DAG.getDataLayout());
4471   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4472   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4473   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4474   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4475   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4476   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4477     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4478     // which does another jump to the destination. This also makes it easier
4479     // to translate it to TBB / TBH later (Thumb2 only).
4480     // FIXME: This might not work if the function is extremely large.
4481     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4482                        Addr, Op.getOperand(2), JTI);
4483   }
4484   if (isPositionIndependent() || Subtarget->isROPI()) {
4485     Addr =
4486         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4487                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4488     Chain = Addr.getValue(1);
4489     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4490     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4491   } else {
4492     Addr =
4493         DAG.getLoad(PTy, dl, Chain, Addr,
4494                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4495     Chain = Addr.getValue(1);
4496     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4497   }
4498 }
4499 
4500 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4501   EVT VT = Op.getValueType();
4502   SDLoc dl(Op);
4503 
4504   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4505     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4506       return Op;
4507     return DAG.UnrollVectorOp(Op.getNode());
4508   }
4509 
4510   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4511          "Invalid type for custom lowering!");
4512   if (VT != MVT::v4i16)
4513     return DAG.UnrollVectorOp(Op.getNode());
4514 
4515   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4516   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4517 }
4518 
4519 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4520   EVT VT = Op.getValueType();
4521   if (VT.isVector())
4522     return LowerVectorFP_TO_INT(Op, DAG);
4523   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4524     RTLIB::Libcall LC;
4525     if (Op.getOpcode() == ISD::FP_TO_SINT)
4526       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4527                               Op.getValueType());
4528     else
4529       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4530                               Op.getValueType());
4531     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4532                        /*isSigned*/ false, SDLoc(Op)).first;
4533   }
4534 
4535   return Op;
4536 }
4537 
4538 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4539   EVT VT = Op.getValueType();
4540   SDLoc dl(Op);
4541 
4542   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4543     if (VT.getVectorElementType() == MVT::f32)
4544       return Op;
4545     return DAG.UnrollVectorOp(Op.getNode());
4546   }
4547 
4548   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4549          "Invalid type for custom lowering!");
4550   if (VT != MVT::v4f32)
4551     return DAG.UnrollVectorOp(Op.getNode());
4552 
4553   unsigned CastOpc;
4554   unsigned Opc;
4555   switch (Op.getOpcode()) {
4556   default: llvm_unreachable("Invalid opcode!");
4557   case ISD::SINT_TO_FP:
4558     CastOpc = ISD::SIGN_EXTEND;
4559     Opc = ISD::SINT_TO_FP;
4560     break;
4561   case ISD::UINT_TO_FP:
4562     CastOpc = ISD::ZERO_EXTEND;
4563     Opc = ISD::UINT_TO_FP;
4564     break;
4565   }
4566 
4567   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4568   return DAG.getNode(Opc, dl, VT, Op);
4569 }
4570 
4571 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4572   EVT VT = Op.getValueType();
4573   if (VT.isVector())
4574     return LowerVectorINT_TO_FP(Op, DAG);
4575   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4576     RTLIB::Libcall LC;
4577     if (Op.getOpcode() == ISD::SINT_TO_FP)
4578       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4579                               Op.getValueType());
4580     else
4581       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4582                               Op.getValueType());
4583     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4584                        /*isSigned*/ false, SDLoc(Op)).first;
4585   }
4586 
4587   return Op;
4588 }
4589 
4590 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4591   // Implement fcopysign with a fabs and a conditional fneg.
4592   SDValue Tmp0 = Op.getOperand(0);
4593   SDValue Tmp1 = Op.getOperand(1);
4594   SDLoc dl(Op);
4595   EVT VT = Op.getValueType();
4596   EVT SrcVT = Tmp1.getValueType();
4597   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4598     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4599   bool UseNEON = !InGPR && Subtarget->hasNEON();
4600 
4601   if (UseNEON) {
4602     // Use VBSL to copy the sign bit.
4603     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4604     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4605                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4606     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4607     if (VT == MVT::f64)
4608       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4609                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4610                          DAG.getConstant(32, dl, MVT::i32));
4611     else /*if (VT == MVT::f32)*/
4612       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4613     if (SrcVT == MVT::f32) {
4614       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4615       if (VT == MVT::f64)
4616         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4617                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4618                            DAG.getConstant(32, dl, MVT::i32));
4619     } else if (VT == MVT::f32)
4620       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4621                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4622                          DAG.getConstant(32, dl, MVT::i32));
4623     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4624     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4625 
4626     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4627                                             dl, MVT::i32);
4628     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4629     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4630                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4631 
4632     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4633                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4634                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4635     if (VT == MVT::f32) {
4636       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4637       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4638                         DAG.getConstant(0, dl, MVT::i32));
4639     } else {
4640       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4641     }
4642 
4643     return Res;
4644   }
4645 
4646   // Bitcast operand 1 to i32.
4647   if (SrcVT == MVT::f64)
4648     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4649                        Tmp1).getValue(1);
4650   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4651 
4652   // Or in the signbit with integer operations.
4653   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4654   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4655   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4656   if (VT == MVT::f32) {
4657     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4658                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4659     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4660                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4661   }
4662 
4663   // f64: Or the high part with signbit and then combine two parts.
4664   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4665                      Tmp0);
4666   SDValue Lo = Tmp0.getValue(0);
4667   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4668   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4669   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4670 }
4671 
4672 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4673   MachineFunction &MF = DAG.getMachineFunction();
4674   MachineFrameInfo &MFI = MF.getFrameInfo();
4675   MFI.setReturnAddressIsTaken(true);
4676 
4677   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4678     return SDValue();
4679 
4680   EVT VT = Op.getValueType();
4681   SDLoc dl(Op);
4682   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4683   if (Depth) {
4684     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4685     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4686     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4687                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4688                        MachinePointerInfo());
4689   }
4690 
4691   // Return LR, which contains the return address. Mark it an implicit live-in.
4692   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4693   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4694 }
4695 
4696 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4697   const ARMBaseRegisterInfo &ARI =
4698     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4699   MachineFunction &MF = DAG.getMachineFunction();
4700   MachineFrameInfo &MFI = MF.getFrameInfo();
4701   MFI.setFrameAddressIsTaken(true);
4702 
4703   EVT VT = Op.getValueType();
4704   SDLoc dl(Op);  // FIXME probably not meaningful
4705   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4706   unsigned FrameReg = ARI.getFrameRegister(MF);
4707   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4708   while (Depth--)
4709     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4710                             MachinePointerInfo());
4711   return FrameAddr;
4712 }
4713 
4714 // FIXME? Maybe this could be a TableGen attribute on some registers and
4715 // this table could be generated automatically from RegInfo.
4716 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4717                                               SelectionDAG &DAG) const {
4718   unsigned Reg = StringSwitch<unsigned>(RegName)
4719                        .Case("sp", ARM::SP)
4720                        .Default(0);
4721   if (Reg)
4722     return Reg;
4723   report_fatal_error(Twine("Invalid register name \""
4724                               + StringRef(RegName)  + "\"."));
4725 }
4726 
4727 // Result is 64 bit value so split into two 32 bit values and return as a
4728 // pair of values.
4729 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4730                                 SelectionDAG &DAG) {
4731   SDLoc DL(N);
4732 
4733   // This function is only supposed to be called for i64 type destination.
4734   assert(N->getValueType(0) == MVT::i64
4735           && "ExpandREAD_REGISTER called for non-i64 type result.");
4736 
4737   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4738                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4739                              N->getOperand(0),
4740                              N->getOperand(1));
4741 
4742   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4743                     Read.getValue(1)));
4744   Results.push_back(Read.getOperand(0));
4745 }
4746 
4747 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4748 /// When \p DstVT, the destination type of \p BC, is on the vector
4749 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4750 /// it might be possible to combine them, such that everything stays on the
4751 /// vector register bank.
4752 /// \p return The node that would replace \p BT, if the combine
4753 /// is possible.
4754 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4755                                                 SelectionDAG &DAG) {
4756   SDValue Op = BC->getOperand(0);
4757   EVT DstVT = BC->getValueType(0);
4758 
4759   // The only vector instruction that can produce a scalar (remember,
4760   // since the bitcast was about to be turned into VMOVDRR, the source
4761   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4762   // Moreover, we can do this combine only if there is one use.
4763   // Finally, if the destination type is not a vector, there is not
4764   // much point on forcing everything on the vector bank.
4765   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4766       !Op.hasOneUse())
4767     return SDValue();
4768 
4769   // If the index is not constant, we will introduce an additional
4770   // multiply that will stick.
4771   // Give up in that case.
4772   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4773   if (!Index)
4774     return SDValue();
4775   unsigned DstNumElt = DstVT.getVectorNumElements();
4776 
4777   // Compute the new index.
4778   const APInt &APIntIndex = Index->getAPIntValue();
4779   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4780   NewIndex *= APIntIndex;
4781   // Check if the new constant index fits into i32.
4782   if (NewIndex.getBitWidth() > 32)
4783     return SDValue();
4784 
4785   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4786   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4787   SDLoc dl(Op);
4788   SDValue ExtractSrc = Op.getOperand(0);
4789   EVT VecVT = EVT::getVectorVT(
4790       *DAG.getContext(), DstVT.getScalarType(),
4791       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4792   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4793   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4794                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4795 }
4796 
4797 /// ExpandBITCAST - If the target supports VFP, this function is called to
4798 /// expand a bit convert where either the source or destination type is i64 to
4799 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4800 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4801 /// vectors), since the legalizer won't know what to do with that.
4802 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4804   SDLoc dl(N);
4805   SDValue Op = N->getOperand(0);
4806 
4807   // This function is only supposed to be called for i64 types, either as the
4808   // source or destination of the bit convert.
4809   EVT SrcVT = Op.getValueType();
4810   EVT DstVT = N->getValueType(0);
4811   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4812          "ExpandBITCAST called for non-i64 type");
4813 
4814   // Turn i64->f64 into VMOVDRR.
4815   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4816     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4817     // if we can combine the bitcast with its source.
4818     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4819       return Val;
4820 
4821     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4822                              DAG.getConstant(0, dl, MVT::i32));
4823     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4824                              DAG.getConstant(1, dl, MVT::i32));
4825     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4826                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4827   }
4828 
4829   // Turn f64->i64 into VMOVRRD.
4830   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4831     SDValue Cvt;
4832     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4833         SrcVT.getVectorNumElements() > 1)
4834       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4835                         DAG.getVTList(MVT::i32, MVT::i32),
4836                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4837     else
4838       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4839                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4840     // Merge the pieces into a single i64 value.
4841     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4842   }
4843 
4844   return SDValue();
4845 }
4846 
4847 /// getZeroVector - Returns a vector of specified type with all zero elements.
4848 /// Zero vectors are used to represent vector negation and in those cases
4849 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4850 /// not support i64 elements, so sometimes the zero vectors will need to be
4851 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4852 /// zero vector.
4853 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4854   assert(VT.isVector() && "Expected a vector type");
4855   // The canonical modified immediate encoding of a zero vector is....0!
4856   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4857   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4858   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4859   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4860 }
4861 
4862 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4863 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4864 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4865                                                 SelectionDAG &DAG) const {
4866   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4867   EVT VT = Op.getValueType();
4868   unsigned VTBits = VT.getSizeInBits();
4869   SDLoc dl(Op);
4870   SDValue ShOpLo = Op.getOperand(0);
4871   SDValue ShOpHi = Op.getOperand(1);
4872   SDValue ShAmt  = Op.getOperand(2);
4873   SDValue ARMcc;
4874   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4875   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4876 
4877   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4878 
4879   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4880                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4881   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4882   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4883                                    DAG.getConstant(VTBits, dl, MVT::i32));
4884   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4885   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4886   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4887   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4888                             ISD::SETGE, ARMcc, DAG, dl);
4889   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4890                            ARMcc, CCR, CmpLo);
4891 
4892 
4893   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4894   SDValue HiBigShift = Opc == ISD::SRA
4895                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
4896                                          DAG.getConstant(VTBits - 1, dl, VT))
4897                            : DAG.getConstant(0, dl, VT);
4898   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4899                             ISD::SETGE, ARMcc, DAG, dl);
4900   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4901                            ARMcc, CCR, CmpHi);
4902 
4903   SDValue Ops[2] = { Lo, Hi };
4904   return DAG.getMergeValues(Ops, dl);
4905 }
4906 
4907 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4908 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4909 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4910                                                SelectionDAG &DAG) const {
4911   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4912   EVT VT = Op.getValueType();
4913   unsigned VTBits = VT.getSizeInBits();
4914   SDLoc dl(Op);
4915   SDValue ShOpLo = Op.getOperand(0);
4916   SDValue ShOpHi = Op.getOperand(1);
4917   SDValue ShAmt  = Op.getOperand(2);
4918   SDValue ARMcc;
4919   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4920 
4921   assert(Op.getOpcode() == ISD::SHL_PARTS);
4922   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4923                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4924   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4925   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4926   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4927 
4928   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4929                                    DAG.getConstant(VTBits, dl, MVT::i32));
4930   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4931   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4932                             ISD::SETGE, ARMcc, DAG, dl);
4933   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4934                            ARMcc, CCR, CmpHi);
4935 
4936   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4937                           ISD::SETGE, ARMcc, DAG, dl);
4938   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4939   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
4940                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
4941 
4942   SDValue Ops[2] = { Lo, Hi };
4943   return DAG.getMergeValues(Ops, dl);
4944 }
4945 
4946 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4947                                             SelectionDAG &DAG) const {
4948   // The rounding mode is in bits 23:22 of the FPSCR.
4949   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4950   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4951   // so that the shift + and get folded into a bitfield extract.
4952   SDLoc dl(Op);
4953   SDValue Ops[] = { DAG.getEntryNode(),
4954                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
4955 
4956   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
4957   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4958                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4959   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4960                               DAG.getConstant(22, dl, MVT::i32));
4961   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4962                      DAG.getConstant(3, dl, MVT::i32));
4963 }
4964 
4965 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4966                          const ARMSubtarget *ST) {
4967   SDLoc dl(N);
4968   EVT VT = N->getValueType(0);
4969   if (VT.isVector()) {
4970     assert(ST->hasNEON());
4971 
4972     // Compute the least significant set bit: LSB = X & -X
4973     SDValue X = N->getOperand(0);
4974     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4975     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4976 
4977     EVT ElemTy = VT.getVectorElementType();
4978 
4979     if (ElemTy == MVT::i8) {
4980       // Compute with: cttz(x) = ctpop(lsb - 1)
4981       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4982                                 DAG.getTargetConstant(1, dl, ElemTy));
4983       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4984       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4985     }
4986 
4987     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4988         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4989       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4990       unsigned NumBits = ElemTy.getSizeInBits();
4991       SDValue WidthMinus1 =
4992           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4993                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4994       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4995       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4996     }
4997 
4998     // Compute with: cttz(x) = ctpop(lsb - 1)
4999 
5000     // Since we can only compute the number of bits in a byte with vcnt.8, we
5001     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5002     // and i64.
5003 
5004     // Compute LSB - 1.
5005     SDValue Bits;
5006     if (ElemTy == MVT::i64) {
5007       // Load constant 0xffff'ffff'ffff'ffff to register.
5008       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5009                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5010       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5011     } else {
5012       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5013                                 DAG.getTargetConstant(1, dl, ElemTy));
5014       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5015     }
5016 
5017     // Count #bits with vcnt.8.
5018     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5019     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5020     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5021 
5022     // Gather the #bits with vpaddl (pairwise add.)
5023     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5024     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5025         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5026         Cnt8);
5027     if (ElemTy == MVT::i16)
5028       return Cnt16;
5029 
5030     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5031     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5032         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5033         Cnt16);
5034     if (ElemTy == MVT::i32)
5035       return Cnt32;
5036 
5037     assert(ElemTy == MVT::i64);
5038     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5039         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5040         Cnt32);
5041     return Cnt64;
5042   }
5043 
5044   if (!ST->hasV6T2Ops())
5045     return SDValue();
5046 
5047   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5048   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5049 }
5050 
5051 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5052 /// for each 16-bit element from operand, repeated.  The basic idea is to
5053 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5054 ///
5055 /// Trace for v4i16:
5056 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5057 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5058 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5059 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5060 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5061 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5062 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5063 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5064 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5065   EVT VT = N->getValueType(0);
5066   SDLoc DL(N);
5067 
5068   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5069   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5070   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5071   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5072   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5073   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5074 }
5075 
5076 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5077 /// bit-count for each 16-bit element from the operand.  We need slightly
5078 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5079 /// 64/128-bit registers.
5080 ///
5081 /// Trace for v4i16:
5082 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5083 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5084 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5085 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5086 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5087   EVT VT = N->getValueType(0);
5088   SDLoc DL(N);
5089 
5090   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5091   if (VT.is64BitVector()) {
5092     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5093     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5094                        DAG.getIntPtrConstant(0, DL));
5095   } else {
5096     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5097                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5098     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5099   }
5100 }
5101 
5102 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5103 /// bit-count for each 32-bit element from the operand.  The idea here is
5104 /// to split the vector into 16-bit elements, leverage the 16-bit count
5105 /// routine, and then combine the results.
5106 ///
5107 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5108 /// input    = [v0    v1    ] (vi: 32-bit elements)
5109 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5110 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5111 /// vrev: N0 = [k1 k0 k3 k2 ]
5112 ///            [k0 k1 k2 k3 ]
5113 ///       N1 =+[k1 k0 k3 k2 ]
5114 ///            [k0 k2 k1 k3 ]
5115 ///       N2 =+[k1 k3 k0 k2 ]
5116 ///            [k0    k2    k1    k3    ]
5117 /// Extended =+[k1    k3    k0    k2    ]
5118 ///            [k0    k2    ]
5119 /// Extracted=+[k1    k3    ]
5120 ///
5121 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5122   EVT VT = N->getValueType(0);
5123   SDLoc DL(N);
5124 
5125   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5126 
5127   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5128   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5129   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5130   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5131   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5132 
5133   if (VT.is64BitVector()) {
5134     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5135     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5136                        DAG.getIntPtrConstant(0, DL));
5137   } else {
5138     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5139                                     DAG.getIntPtrConstant(0, DL));
5140     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5141   }
5142 }
5143 
5144 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5145                           const ARMSubtarget *ST) {
5146   EVT VT = N->getValueType(0);
5147 
5148   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5149   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5150           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5151          "Unexpected type for custom ctpop lowering");
5152 
5153   if (VT.getVectorElementType() == MVT::i32)
5154     return lowerCTPOP32BitElements(N, DAG);
5155   else
5156     return lowerCTPOP16BitElements(N, DAG);
5157 }
5158 
5159 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5160                           const ARMSubtarget *ST) {
5161   EVT VT = N->getValueType(0);
5162   SDLoc dl(N);
5163 
5164   if (!VT.isVector())
5165     return SDValue();
5166 
5167   // Lower vector shifts on NEON to use VSHL.
5168   assert(ST->hasNEON() && "unexpected vector shift");
5169 
5170   // Left shifts translate directly to the vshiftu intrinsic.
5171   if (N->getOpcode() == ISD::SHL)
5172     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5173                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5174                                        MVT::i32),
5175                        N->getOperand(0), N->getOperand(1));
5176 
5177   assert((N->getOpcode() == ISD::SRA ||
5178           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5179 
5180   // NEON uses the same intrinsics for both left and right shifts.  For
5181   // right shifts, the shift amounts are negative, so negate the vector of
5182   // shift amounts.
5183   EVT ShiftVT = N->getOperand(1).getValueType();
5184   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5185                                      getZeroVector(ShiftVT, DAG, dl),
5186                                      N->getOperand(1));
5187   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5188                              Intrinsic::arm_neon_vshifts :
5189                              Intrinsic::arm_neon_vshiftu);
5190   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5191                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5192                      N->getOperand(0), NegatedCount);
5193 }
5194 
5195 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5196                                 const ARMSubtarget *ST) {
5197   EVT VT = N->getValueType(0);
5198   SDLoc dl(N);
5199 
5200   // We can get here for a node like i32 = ISD::SHL i32, i64
5201   if (VT != MVT::i64)
5202     return SDValue();
5203 
5204   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5205          "Unknown shift to lower!");
5206 
5207   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5208   if (!isOneConstant(N->getOperand(1)))
5209     return SDValue();
5210 
5211   // If we are in thumb mode, we don't have RRX.
5212   if (ST->isThumb1Only()) return SDValue();
5213 
5214   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5215   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5216                            DAG.getConstant(0, dl, MVT::i32));
5217   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5218                            DAG.getConstant(1, dl, MVT::i32));
5219 
5220   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5221   // captures the result into a carry flag.
5222   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5223   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5224 
5225   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5226   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5227 
5228   // Merge the pieces into a single i64 value.
5229  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5230 }
5231 
5232 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5233   SDValue TmpOp0, TmpOp1;
5234   bool Invert = false;
5235   bool Swap = false;
5236   unsigned Opc = 0;
5237 
5238   SDValue Op0 = Op.getOperand(0);
5239   SDValue Op1 = Op.getOperand(1);
5240   SDValue CC = Op.getOperand(2);
5241   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5242   EVT VT = Op.getValueType();
5243   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5244   SDLoc dl(Op);
5245 
5246   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5247       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5248     // Special-case integer 64-bit equality comparisons. They aren't legal,
5249     // but they can be lowered with a few vector instructions.
5250     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5251     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5252     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5253     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5254     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5255                               DAG.getCondCode(ISD::SETEQ));
5256     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5257     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5258     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5259     if (SetCCOpcode == ISD::SETNE)
5260       Merged = DAG.getNOT(dl, Merged, CmpVT);
5261     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5262     return Merged;
5263   }
5264 
5265   if (CmpVT.getVectorElementType() == MVT::i64)
5266     // 64-bit comparisons are not legal in general.
5267     return SDValue();
5268 
5269   if (Op1.getValueType().isFloatingPoint()) {
5270     switch (SetCCOpcode) {
5271     default: llvm_unreachable("Illegal FP comparison");
5272     case ISD::SETUNE:
5273     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5274     case ISD::SETOEQ:
5275     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5276     case ISD::SETOLT:
5277     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5278     case ISD::SETOGT:
5279     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5280     case ISD::SETOLE:
5281     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5282     case ISD::SETOGE:
5283     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5284     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5285     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5286     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5287     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5288     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5289     case ISD::SETONE:
5290       // Expand this to (OLT | OGT).
5291       TmpOp0 = Op0;
5292       TmpOp1 = Op1;
5293       Opc = ISD::OR;
5294       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5295       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5296       break;
5297     case ISD::SETUO:
5298       Invert = true;
5299       LLVM_FALLTHROUGH;
5300     case ISD::SETO:
5301       // Expand this to (OLT | OGE).
5302       TmpOp0 = Op0;
5303       TmpOp1 = Op1;
5304       Opc = ISD::OR;
5305       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5306       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5307       break;
5308     }
5309   } else {
5310     // Integer comparisons.
5311     switch (SetCCOpcode) {
5312     default: llvm_unreachable("Illegal integer comparison");
5313     case ISD::SETNE:  Invert = true;
5314     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5315     case ISD::SETLT:  Swap = true;
5316     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5317     case ISD::SETLE:  Swap = true;
5318     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5319     case ISD::SETULT: Swap = true;
5320     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5321     case ISD::SETULE: Swap = true;
5322     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5323     }
5324 
5325     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5326     if (Opc == ARMISD::VCEQ) {
5327 
5328       SDValue AndOp;
5329       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5330         AndOp = Op0;
5331       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5332         AndOp = Op1;
5333 
5334       // Ignore bitconvert.
5335       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5336         AndOp = AndOp.getOperand(0);
5337 
5338       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5339         Opc = ARMISD::VTST;
5340         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5341         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5342         Invert = !Invert;
5343       }
5344     }
5345   }
5346 
5347   if (Swap)
5348     std::swap(Op0, Op1);
5349 
5350   // If one of the operands is a constant vector zero, attempt to fold the
5351   // comparison to a specialized compare-against-zero form.
5352   SDValue SingleOp;
5353   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5354     SingleOp = Op0;
5355   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5356     if (Opc == ARMISD::VCGE)
5357       Opc = ARMISD::VCLEZ;
5358     else if (Opc == ARMISD::VCGT)
5359       Opc = ARMISD::VCLTZ;
5360     SingleOp = Op1;
5361   }
5362 
5363   SDValue Result;
5364   if (SingleOp.getNode()) {
5365     switch (Opc) {
5366     case ARMISD::VCEQ:
5367       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5368     case ARMISD::VCGE:
5369       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5370     case ARMISD::VCLEZ:
5371       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5372     case ARMISD::VCGT:
5373       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5374     case ARMISD::VCLTZ:
5375       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5376     default:
5377       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5378     }
5379   } else {
5380      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5381   }
5382 
5383   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5384 
5385   if (Invert)
5386     Result = DAG.getNOT(dl, Result, VT);
5387 
5388   return Result;
5389 }
5390 
5391 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5392   SDValue LHS = Op.getOperand(0);
5393   SDValue RHS = Op.getOperand(1);
5394   SDValue Carry = Op.getOperand(2);
5395   SDValue Cond = Op.getOperand(3);
5396   SDLoc DL(Op);
5397 
5398   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5399 
5400   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5401   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5402   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5403 
5404   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5405   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5406   SDValue ARMcc = DAG.getConstant(
5407       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5408   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5409   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5410                                    Cmp.getValue(1), SDValue());
5411   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5412                      CCR, Chain.getValue(1));
5413 }
5414 
5415 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5416 /// valid vector constant for a NEON instruction with a "modified immediate"
5417 /// operand (e.g., VMOV).  If so, return the encoded value.
5418 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5419                                  unsigned SplatBitSize, SelectionDAG &DAG,
5420                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5421                                  NEONModImmType type) {
5422   unsigned OpCmode, Imm;
5423 
5424   // SplatBitSize is set to the smallest size that splats the vector, so a
5425   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5426   // immediate instructions others than VMOV do not support the 8-bit encoding
5427   // of a zero vector, and the default encoding of zero is supposed to be the
5428   // 32-bit version.
5429   if (SplatBits == 0)
5430     SplatBitSize = 32;
5431 
5432   switch (SplatBitSize) {
5433   case 8:
5434     if (type != VMOVModImm)
5435       return SDValue();
5436     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5437     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5438     OpCmode = 0xe;
5439     Imm = SplatBits;
5440     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5441     break;
5442 
5443   case 16:
5444     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5445     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5446     if ((SplatBits & ~0xff) == 0) {
5447       // Value = 0x00nn: Op=x, Cmode=100x.
5448       OpCmode = 0x8;
5449       Imm = SplatBits;
5450       break;
5451     }
5452     if ((SplatBits & ~0xff00) == 0) {
5453       // Value = 0xnn00: Op=x, Cmode=101x.
5454       OpCmode = 0xa;
5455       Imm = SplatBits >> 8;
5456       break;
5457     }
5458     return SDValue();
5459 
5460   case 32:
5461     // NEON's 32-bit VMOV supports splat values where:
5462     // * only one byte is nonzero, or
5463     // * the least significant byte is 0xff and the second byte is nonzero, or
5464     // * the least significant 2 bytes are 0xff and the third is nonzero.
5465     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5466     if ((SplatBits & ~0xff) == 0) {
5467       // Value = 0x000000nn: Op=x, Cmode=000x.
5468       OpCmode = 0;
5469       Imm = SplatBits;
5470       break;
5471     }
5472     if ((SplatBits & ~0xff00) == 0) {
5473       // Value = 0x0000nn00: Op=x, Cmode=001x.
5474       OpCmode = 0x2;
5475       Imm = SplatBits >> 8;
5476       break;
5477     }
5478     if ((SplatBits & ~0xff0000) == 0) {
5479       // Value = 0x00nn0000: Op=x, Cmode=010x.
5480       OpCmode = 0x4;
5481       Imm = SplatBits >> 16;
5482       break;
5483     }
5484     if ((SplatBits & ~0xff000000) == 0) {
5485       // Value = 0xnn000000: Op=x, Cmode=011x.
5486       OpCmode = 0x6;
5487       Imm = SplatBits >> 24;
5488       break;
5489     }
5490 
5491     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5492     if (type == OtherModImm) return SDValue();
5493 
5494     if ((SplatBits & ~0xffff) == 0 &&
5495         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5496       // Value = 0x0000nnff: Op=x, Cmode=1100.
5497       OpCmode = 0xc;
5498       Imm = SplatBits >> 8;
5499       break;
5500     }
5501 
5502     if ((SplatBits & ~0xffffff) == 0 &&
5503         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5504       // Value = 0x00nnffff: Op=x, Cmode=1101.
5505       OpCmode = 0xd;
5506       Imm = SplatBits >> 16;
5507       break;
5508     }
5509 
5510     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5511     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5512     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5513     // and fall through here to test for a valid 64-bit splat.  But, then the
5514     // caller would also need to check and handle the change in size.
5515     return SDValue();
5516 
5517   case 64: {
5518     if (type != VMOVModImm)
5519       return SDValue();
5520     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5521     uint64_t BitMask = 0xff;
5522     uint64_t Val = 0;
5523     unsigned ImmMask = 1;
5524     Imm = 0;
5525     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5526       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5527         Val |= BitMask;
5528         Imm |= ImmMask;
5529       } else if ((SplatBits & BitMask) != 0) {
5530         return SDValue();
5531       }
5532       BitMask <<= 8;
5533       ImmMask <<= 1;
5534     }
5535 
5536     if (DAG.getDataLayout().isBigEndian())
5537       // swap higher and lower 32 bit word
5538       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5539 
5540     // Op=1, Cmode=1110.
5541     OpCmode = 0x1e;
5542     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5543     break;
5544   }
5545 
5546   default:
5547     llvm_unreachable("unexpected size for isNEONModifiedImm");
5548   }
5549 
5550   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5551   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5552 }
5553 
5554 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5555                                            const ARMSubtarget *ST) const {
5556   bool IsDouble = Op.getValueType() == MVT::f64;
5557   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5558   const APFloat &FPVal = CFP->getValueAPF();
5559 
5560   // Prevent floating-point constants from using literal loads
5561   // when execute-only is enabled.
5562   if (ST->genExecuteOnly()) {
5563     APInt INTVal = FPVal.bitcastToAPInt();
5564     SDLoc DL(CFP);
5565     if (IsDouble) {
5566       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5567       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5568       if (!ST->isLittle())
5569         std::swap(Lo, Hi);
5570       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5571     } else {
5572       return DAG.getConstant(INTVal, DL, MVT::i32);
5573     }
5574   }
5575 
5576   if (!ST->hasVFP3())
5577     return SDValue();
5578 
5579   // Use the default (constant pool) lowering for double constants when we have
5580   // an SP-only FPU
5581   if (IsDouble && Subtarget->isFPOnlySP())
5582     return SDValue();
5583 
5584   // Try splatting with a VMOV.f32...
5585   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5586 
5587   if (ImmVal != -1) {
5588     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5589       // We have code in place to select a valid ConstantFP already, no need to
5590       // do any mangling.
5591       return Op;
5592     }
5593 
5594     // It's a float and we are trying to use NEON operations where
5595     // possible. Lower it to a splat followed by an extract.
5596     SDLoc DL(Op);
5597     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5598     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5599                                       NewVal);
5600     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5601                        DAG.getConstant(0, DL, MVT::i32));
5602   }
5603 
5604   // The rest of our options are NEON only, make sure that's allowed before
5605   // proceeding..
5606   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5607     return SDValue();
5608 
5609   EVT VMovVT;
5610   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5611 
5612   // It wouldn't really be worth bothering for doubles except for one very
5613   // important value, which does happen to match: 0.0. So make sure we don't do
5614   // anything stupid.
5615   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5616     return SDValue();
5617 
5618   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5619   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5620                                      VMovVT, false, VMOVModImm);
5621   if (NewVal != SDValue()) {
5622     SDLoc DL(Op);
5623     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5624                                       NewVal);
5625     if (IsDouble)
5626       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5627 
5628     // It's a float: cast and extract a vector element.
5629     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5630                                        VecConstant);
5631     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5632                        DAG.getConstant(0, DL, MVT::i32));
5633   }
5634 
5635   // Finally, try a VMVN.i32
5636   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5637                              false, VMVNModImm);
5638   if (NewVal != SDValue()) {
5639     SDLoc DL(Op);
5640     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5641 
5642     if (IsDouble)
5643       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5644 
5645     // It's a float: cast and extract a vector element.
5646     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5647                                        VecConstant);
5648     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5649                        DAG.getConstant(0, DL, MVT::i32));
5650   }
5651 
5652   return SDValue();
5653 }
5654 
5655 // check if an VEXT instruction can handle the shuffle mask when the
5656 // vector sources of the shuffle are the same.
5657 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5658   unsigned NumElts = VT.getVectorNumElements();
5659 
5660   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5661   if (M[0] < 0)
5662     return false;
5663 
5664   Imm = M[0];
5665 
5666   // If this is a VEXT shuffle, the immediate value is the index of the first
5667   // element.  The other shuffle indices must be the successive elements after
5668   // the first one.
5669   unsigned ExpectedElt = Imm;
5670   for (unsigned i = 1; i < NumElts; ++i) {
5671     // Increment the expected index.  If it wraps around, just follow it
5672     // back to index zero and keep going.
5673     ++ExpectedElt;
5674     if (ExpectedElt == NumElts)
5675       ExpectedElt = 0;
5676 
5677     if (M[i] < 0) continue; // ignore UNDEF indices
5678     if (ExpectedElt != static_cast<unsigned>(M[i]))
5679       return false;
5680   }
5681 
5682   return true;
5683 }
5684 
5685 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5686                        bool &ReverseVEXT, unsigned &Imm) {
5687   unsigned NumElts = VT.getVectorNumElements();
5688   ReverseVEXT = false;
5689 
5690   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5691   if (M[0] < 0)
5692     return false;
5693 
5694   Imm = M[0];
5695 
5696   // If this is a VEXT shuffle, the immediate value is the index of the first
5697   // element.  The other shuffle indices must be the successive elements after
5698   // the first one.
5699   unsigned ExpectedElt = Imm;
5700   for (unsigned i = 1; i < NumElts; ++i) {
5701     // Increment the expected index.  If it wraps around, it may still be
5702     // a VEXT but the source vectors must be swapped.
5703     ExpectedElt += 1;
5704     if (ExpectedElt == NumElts * 2) {
5705       ExpectedElt = 0;
5706       ReverseVEXT = true;
5707     }
5708 
5709     if (M[i] < 0) continue; // ignore UNDEF indices
5710     if (ExpectedElt != static_cast<unsigned>(M[i]))
5711       return false;
5712   }
5713 
5714   // Adjust the index value if the source operands will be swapped.
5715   if (ReverseVEXT)
5716     Imm -= NumElts;
5717 
5718   return true;
5719 }
5720 
5721 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5722 /// instruction with the specified blocksize.  (The order of the elements
5723 /// within each block of the vector is reversed.)
5724 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5725   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5726          "Only possible block sizes for VREV are: 16, 32, 64");
5727 
5728   unsigned EltSz = VT.getScalarSizeInBits();
5729   if (EltSz == 64)
5730     return false;
5731 
5732   unsigned NumElts = VT.getVectorNumElements();
5733   unsigned BlockElts = M[0] + 1;
5734   // If the first shuffle index is UNDEF, be optimistic.
5735   if (M[0] < 0)
5736     BlockElts = BlockSize / EltSz;
5737 
5738   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5739     return false;
5740 
5741   for (unsigned i = 0; i < NumElts; ++i) {
5742     if (M[i] < 0) continue; // ignore UNDEF indices
5743     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5744       return false;
5745   }
5746 
5747   return true;
5748 }
5749 
5750 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5751   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5752   // range, then 0 is placed into the resulting vector. So pretty much any mask
5753   // of 8 elements can work here.
5754   return VT == MVT::v8i8 && M.size() == 8;
5755 }
5756 
5757 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5758 // checking that pairs of elements in the shuffle mask represent the same index
5759 // in each vector, incrementing the expected index by 2 at each step.
5760 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5761 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5762 //  v2={e,f,g,h}
5763 // WhichResult gives the offset for each element in the mask based on which
5764 // of the two results it belongs to.
5765 //
5766 // The transpose can be represented either as:
5767 // result1 = shufflevector v1, v2, result1_shuffle_mask
5768 // result2 = shufflevector v1, v2, result2_shuffle_mask
5769 // where v1/v2 and the shuffle masks have the same number of elements
5770 // (here WhichResult (see below) indicates which result is being checked)
5771 //
5772 // or as:
5773 // results = shufflevector v1, v2, shuffle_mask
5774 // where both results are returned in one vector and the shuffle mask has twice
5775 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5776 // want to check the low half and high half of the shuffle mask as if it were
5777 // the other case
5778 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5779   unsigned EltSz = VT.getScalarSizeInBits();
5780   if (EltSz == 64)
5781     return false;
5782 
5783   unsigned NumElts = VT.getVectorNumElements();
5784   if (M.size() != NumElts && M.size() != NumElts*2)
5785     return false;
5786 
5787   // If the mask is twice as long as the input vector then we need to check the
5788   // upper and lower parts of the mask with a matching value for WhichResult
5789   // FIXME: A mask with only even values will be rejected in case the first
5790   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5791   // M[0] is used to determine WhichResult
5792   for (unsigned i = 0; i < M.size(); i += NumElts) {
5793     if (M.size() == NumElts * 2)
5794       WhichResult = i / NumElts;
5795     else
5796       WhichResult = M[i] == 0 ? 0 : 1;
5797     for (unsigned j = 0; j < NumElts; j += 2) {
5798       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5799           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5800         return false;
5801     }
5802   }
5803 
5804   if (M.size() == NumElts*2)
5805     WhichResult = 0;
5806 
5807   return true;
5808 }
5809 
5810 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5811 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5812 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5813 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5814   unsigned EltSz = VT.getScalarSizeInBits();
5815   if (EltSz == 64)
5816     return false;
5817 
5818   unsigned NumElts = VT.getVectorNumElements();
5819   if (M.size() != NumElts && M.size() != NumElts*2)
5820     return false;
5821 
5822   for (unsigned i = 0; i < M.size(); i += NumElts) {
5823     if (M.size() == NumElts * 2)
5824       WhichResult = i / NumElts;
5825     else
5826       WhichResult = M[i] == 0 ? 0 : 1;
5827     for (unsigned j = 0; j < NumElts; j += 2) {
5828       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5829           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5830         return false;
5831     }
5832   }
5833 
5834   if (M.size() == NumElts*2)
5835     WhichResult = 0;
5836 
5837   return true;
5838 }
5839 
5840 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5841 // that the mask elements are either all even and in steps of size 2 or all odd
5842 // and in steps of size 2.
5843 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5844 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5845 //  v2={e,f,g,h}
5846 // Requires similar checks to that of isVTRNMask with
5847 // respect the how results are returned.
5848 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5849   unsigned EltSz = VT.getScalarSizeInBits();
5850   if (EltSz == 64)
5851     return false;
5852 
5853   unsigned NumElts = VT.getVectorNumElements();
5854   if (M.size() != NumElts && M.size() != NumElts*2)
5855     return false;
5856 
5857   for (unsigned i = 0; i < M.size(); i += NumElts) {
5858     WhichResult = M[i] == 0 ? 0 : 1;
5859     for (unsigned j = 0; j < NumElts; ++j) {
5860       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5861         return false;
5862     }
5863   }
5864 
5865   if (M.size() == NumElts*2)
5866     WhichResult = 0;
5867 
5868   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5869   if (VT.is64BitVector() && EltSz == 32)
5870     return false;
5871 
5872   return true;
5873 }
5874 
5875 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5876 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5877 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5878 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5879   unsigned EltSz = VT.getScalarSizeInBits();
5880   if (EltSz == 64)
5881     return false;
5882 
5883   unsigned NumElts = VT.getVectorNumElements();
5884   if (M.size() != NumElts && M.size() != NumElts*2)
5885     return false;
5886 
5887   unsigned Half = NumElts / 2;
5888   for (unsigned i = 0; i < M.size(); i += NumElts) {
5889     WhichResult = M[i] == 0 ? 0 : 1;
5890     for (unsigned j = 0; j < NumElts; j += Half) {
5891       unsigned Idx = WhichResult;
5892       for (unsigned k = 0; k < Half; ++k) {
5893         int MIdx = M[i + j + k];
5894         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5895           return false;
5896         Idx += 2;
5897       }
5898     }
5899   }
5900 
5901   if (M.size() == NumElts*2)
5902     WhichResult = 0;
5903 
5904   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5905   if (VT.is64BitVector() && EltSz == 32)
5906     return false;
5907 
5908   return true;
5909 }
5910 
5911 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5912 // that pairs of elements of the shufflemask represent the same index in each
5913 // vector incrementing sequentially through the vectors.
5914 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5915 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5916 //  v2={e,f,g,h}
5917 // Requires similar checks to that of isVTRNMask with respect the how results
5918 // are returned.
5919 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5920   unsigned EltSz = VT.getScalarSizeInBits();
5921   if (EltSz == 64)
5922     return false;
5923 
5924   unsigned NumElts = VT.getVectorNumElements();
5925   if (M.size() != NumElts && M.size() != NumElts*2)
5926     return false;
5927 
5928   for (unsigned i = 0; i < M.size(); i += NumElts) {
5929     WhichResult = M[i] == 0 ? 0 : 1;
5930     unsigned Idx = WhichResult * NumElts / 2;
5931     for (unsigned j = 0; j < NumElts; j += 2) {
5932       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5933           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5934         return false;
5935       Idx += 1;
5936     }
5937   }
5938 
5939   if (M.size() == NumElts*2)
5940     WhichResult = 0;
5941 
5942   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5943   if (VT.is64BitVector() && EltSz == 32)
5944     return false;
5945 
5946   return true;
5947 }
5948 
5949 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5950 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5951 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5952 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5953   unsigned EltSz = VT.getScalarSizeInBits();
5954   if (EltSz == 64)
5955     return false;
5956 
5957   unsigned NumElts = VT.getVectorNumElements();
5958   if (M.size() != NumElts && M.size() != NumElts*2)
5959     return false;
5960 
5961   for (unsigned i = 0; i < M.size(); i += NumElts) {
5962     WhichResult = M[i] == 0 ? 0 : 1;
5963     unsigned Idx = WhichResult * NumElts / 2;
5964     for (unsigned j = 0; j < NumElts; j += 2) {
5965       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5966           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5967         return false;
5968       Idx += 1;
5969     }
5970   }
5971 
5972   if (M.size() == NumElts*2)
5973     WhichResult = 0;
5974 
5975   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5976   if (VT.is64BitVector() && EltSz == 32)
5977     return false;
5978 
5979   return true;
5980 }
5981 
5982 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5983 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5984 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5985                                            unsigned &WhichResult,
5986                                            bool &isV_UNDEF) {
5987   isV_UNDEF = false;
5988   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5989     return ARMISD::VTRN;
5990   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5991     return ARMISD::VUZP;
5992   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5993     return ARMISD::VZIP;
5994 
5995   isV_UNDEF = true;
5996   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5997     return ARMISD::VTRN;
5998   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5999     return ARMISD::VUZP;
6000   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6001     return ARMISD::VZIP;
6002 
6003   return 0;
6004 }
6005 
6006 /// \return true if this is a reverse operation on an vector.
6007 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6008   unsigned NumElts = VT.getVectorNumElements();
6009   // Make sure the mask has the right size.
6010   if (NumElts != M.size())
6011       return false;
6012 
6013   // Look for <15, ..., 3, -1, 1, 0>.
6014   for (unsigned i = 0; i != NumElts; ++i)
6015     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6016       return false;
6017 
6018   return true;
6019 }
6020 
6021 // If N is an integer constant that can be moved into a register in one
6022 // instruction, return an SDValue of such a constant (will become a MOV
6023 // instruction).  Otherwise return null.
6024 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6025                                      const ARMSubtarget *ST, const SDLoc &dl) {
6026   uint64_t Val;
6027   if (!isa<ConstantSDNode>(N))
6028     return SDValue();
6029   Val = cast<ConstantSDNode>(N)->getZExtValue();
6030 
6031   if (ST->isThumb1Only()) {
6032     if (Val <= 255 || ~Val <= 255)
6033       return DAG.getConstant(Val, dl, MVT::i32);
6034   } else {
6035     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6036       return DAG.getConstant(Val, dl, MVT::i32);
6037   }
6038   return SDValue();
6039 }
6040 
6041 // If this is a case we can't handle, return null and let the default
6042 // expansion code take care of it.
6043 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6044                                              const ARMSubtarget *ST) const {
6045   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6046   SDLoc dl(Op);
6047   EVT VT = Op.getValueType();
6048 
6049   APInt SplatBits, SplatUndef;
6050   unsigned SplatBitSize;
6051   bool HasAnyUndefs;
6052   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6053     if (SplatUndef.isAllOnesValue())
6054       return DAG.getUNDEF(VT);
6055 
6056     if (SplatBitSize <= 64) {
6057       // Check if an immediate VMOV works.
6058       EVT VmovVT;
6059       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6060                                       SplatUndef.getZExtValue(), SplatBitSize,
6061                                       DAG, dl, VmovVT, VT.is128BitVector(),
6062                                       VMOVModImm);
6063       if (Val.getNode()) {
6064         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6065         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6066       }
6067 
6068       // Try an immediate VMVN.
6069       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6070       Val = isNEONModifiedImm(NegatedImm,
6071                                       SplatUndef.getZExtValue(), SplatBitSize,
6072                                       DAG, dl, VmovVT, VT.is128BitVector(),
6073                                       VMVNModImm);
6074       if (Val.getNode()) {
6075         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6076         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6077       }
6078 
6079       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6080       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6081         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6082         if (ImmVal != -1) {
6083           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6084           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6085         }
6086       }
6087     }
6088   }
6089 
6090   // Scan through the operands to see if only one value is used.
6091   //
6092   // As an optimisation, even if more than one value is used it may be more
6093   // profitable to splat with one value then change some lanes.
6094   //
6095   // Heuristically we decide to do this if the vector has a "dominant" value,
6096   // defined as splatted to more than half of the lanes.
6097   unsigned NumElts = VT.getVectorNumElements();
6098   bool isOnlyLowElement = true;
6099   bool usesOnlyOneValue = true;
6100   bool hasDominantValue = false;
6101   bool isConstant = true;
6102 
6103   // Map of the number of times a particular SDValue appears in the
6104   // element list.
6105   DenseMap<SDValue, unsigned> ValueCounts;
6106   SDValue Value;
6107   for (unsigned i = 0; i < NumElts; ++i) {
6108     SDValue V = Op.getOperand(i);
6109     if (V.isUndef())
6110       continue;
6111     if (i > 0)
6112       isOnlyLowElement = false;
6113     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6114       isConstant = false;
6115 
6116     ValueCounts.insert(std::make_pair(V, 0));
6117     unsigned &Count = ValueCounts[V];
6118 
6119     // Is this value dominant? (takes up more than half of the lanes)
6120     if (++Count > (NumElts / 2)) {
6121       hasDominantValue = true;
6122       Value = V;
6123     }
6124   }
6125   if (ValueCounts.size() != 1)
6126     usesOnlyOneValue = false;
6127   if (!Value.getNode() && !ValueCounts.empty())
6128     Value = ValueCounts.begin()->first;
6129 
6130   if (ValueCounts.empty())
6131     return DAG.getUNDEF(VT);
6132 
6133   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6134   // Keep going if we are hitting this case.
6135   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6136     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6137 
6138   unsigned EltSize = VT.getScalarSizeInBits();
6139 
6140   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6141   // i32 and try again.
6142   if (hasDominantValue && EltSize <= 32) {
6143     if (!isConstant) {
6144       SDValue N;
6145 
6146       // If we are VDUPing a value that comes directly from a vector, that will
6147       // cause an unnecessary move to and from a GPR, where instead we could
6148       // just use VDUPLANE. We can only do this if the lane being extracted
6149       // is at a constant index, as the VDUP from lane instructions only have
6150       // constant-index forms.
6151       ConstantSDNode *constIndex;
6152       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6153           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6154         // We need to create a new undef vector to use for the VDUPLANE if the
6155         // size of the vector from which we get the value is different than the
6156         // size of the vector that we need to create. We will insert the element
6157         // such that the register coalescer will remove unnecessary copies.
6158         if (VT != Value->getOperand(0).getValueType()) {
6159           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6160                              VT.getVectorNumElements();
6161           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6162                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6163                         Value, DAG.getConstant(index, dl, MVT::i32)),
6164                            DAG.getConstant(index, dl, MVT::i32));
6165         } else
6166           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6167                         Value->getOperand(0), Value->getOperand(1));
6168       } else
6169         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6170 
6171       if (!usesOnlyOneValue) {
6172         // The dominant value was splatted as 'N', but we now have to insert
6173         // all differing elements.
6174         for (unsigned I = 0; I < NumElts; ++I) {
6175           if (Op.getOperand(I) == Value)
6176             continue;
6177           SmallVector<SDValue, 3> Ops;
6178           Ops.push_back(N);
6179           Ops.push_back(Op.getOperand(I));
6180           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6181           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6182         }
6183       }
6184       return N;
6185     }
6186     if (VT.getVectorElementType().isFloatingPoint()) {
6187       SmallVector<SDValue, 8> Ops;
6188       for (unsigned i = 0; i < NumElts; ++i)
6189         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6190                                   Op.getOperand(i)));
6191       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6192       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6193       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6194       if (Val.getNode())
6195         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6196     }
6197     if (usesOnlyOneValue) {
6198       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6199       if (isConstant && Val.getNode())
6200         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6201     }
6202   }
6203 
6204   // If all elements are constants and the case above didn't get hit, fall back
6205   // to the default expansion, which will generate a load from the constant
6206   // pool.
6207   if (isConstant)
6208     return SDValue();
6209 
6210   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6211   if (NumElts >= 4) {
6212     SDValue shuffle = ReconstructShuffle(Op, DAG);
6213     if (shuffle != SDValue())
6214       return shuffle;
6215   }
6216 
6217   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6218     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6219     // into two 64-bit vectors; we might discover a better way to lower it.
6220     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6221     EVT ExtVT = VT.getVectorElementType();
6222     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6223     SDValue Lower =
6224         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6225     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6226       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6227     SDValue Upper = DAG.getBuildVector(
6228         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6229     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6230       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6231     if (Lower && Upper)
6232       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6233   }
6234 
6235   // Vectors with 32- or 64-bit elements can be built by directly assigning
6236   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6237   // will be legalized.
6238   if (EltSize >= 32) {
6239     // Do the expansion with floating-point types, since that is what the VFP
6240     // registers are defined to use, and since i64 is not legal.
6241     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6242     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6243     SmallVector<SDValue, 8> Ops;
6244     for (unsigned i = 0; i < NumElts; ++i)
6245       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6246     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6247     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6248   }
6249 
6250   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6251   // know the default expansion would otherwise fall back on something even
6252   // worse. For a vector with one or two non-undef values, that's
6253   // scalar_to_vector for the elements followed by a shuffle (provided the
6254   // shuffle is valid for the target) and materialization element by element
6255   // on the stack followed by a load for everything else.
6256   if (!isConstant && !usesOnlyOneValue) {
6257     SDValue Vec = DAG.getUNDEF(VT);
6258     for (unsigned i = 0 ; i < NumElts; ++i) {
6259       SDValue V = Op.getOperand(i);
6260       if (V.isUndef())
6261         continue;
6262       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6263       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6264     }
6265     return Vec;
6266   }
6267 
6268   return SDValue();
6269 }
6270 
6271 // Gather data to see if the operation can be modelled as a
6272 // shuffle in combination with VEXTs.
6273 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6274                                               SelectionDAG &DAG) const {
6275   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6276   SDLoc dl(Op);
6277   EVT VT = Op.getValueType();
6278   unsigned NumElts = VT.getVectorNumElements();
6279 
6280   struct ShuffleSourceInfo {
6281     SDValue Vec;
6282     unsigned MinElt = std::numeric_limits<unsigned>::max();
6283     unsigned MaxElt = 0;
6284 
6285     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6286     // be compatible with the shuffle we intend to construct. As a result
6287     // ShuffleVec will be some sliding window into the original Vec.
6288     SDValue ShuffleVec;
6289 
6290     // Code should guarantee that element i in Vec starts at element "WindowBase
6291     // + i * WindowScale in ShuffleVec".
6292     int WindowBase = 0;
6293     int WindowScale = 1;
6294 
6295     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6296 
6297     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6298   };
6299 
6300   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6301   // node.
6302   SmallVector<ShuffleSourceInfo, 2> Sources;
6303   for (unsigned i = 0; i < NumElts; ++i) {
6304     SDValue V = Op.getOperand(i);
6305     if (V.isUndef())
6306       continue;
6307     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6308       // A shuffle can only come from building a vector from various
6309       // elements of other vectors.
6310       return SDValue();
6311     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6312       // Furthermore, shuffles require a constant mask, whereas extractelts
6313       // accept variable indices.
6314       return SDValue();
6315     }
6316 
6317     // Add this element source to the list if it's not already there.
6318     SDValue SourceVec = V.getOperand(0);
6319     auto Source = llvm::find(Sources, SourceVec);
6320     if (Source == Sources.end())
6321       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6322 
6323     // Update the minimum and maximum lane number seen.
6324     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6325     Source->MinElt = std::min(Source->MinElt, EltNo);
6326     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6327   }
6328 
6329   // Currently only do something sane when at most two source vectors
6330   // are involved.
6331   if (Sources.size() > 2)
6332     return SDValue();
6333 
6334   // Find out the smallest element size among result and two sources, and use
6335   // it as element size to build the shuffle_vector.
6336   EVT SmallestEltTy = VT.getVectorElementType();
6337   for (auto &Source : Sources) {
6338     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6339     if (SrcEltTy.bitsLT(SmallestEltTy))
6340       SmallestEltTy = SrcEltTy;
6341   }
6342   unsigned ResMultiplier =
6343       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6344   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6345   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6346 
6347   // If the source vector is too wide or too narrow, we may nevertheless be able
6348   // to construct a compatible shuffle either by concatenating it with UNDEF or
6349   // extracting a suitable range of elements.
6350   for (auto &Src : Sources) {
6351     EVT SrcVT = Src.ShuffleVec.getValueType();
6352 
6353     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6354       continue;
6355 
6356     // This stage of the search produces a source with the same element type as
6357     // the original, but with a total width matching the BUILD_VECTOR output.
6358     EVT EltVT = SrcVT.getVectorElementType();
6359     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6360     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6361 
6362     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6363       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6364         return SDValue();
6365       // We can pad out the smaller vector for free, so if it's part of a
6366       // shuffle...
6367       Src.ShuffleVec =
6368           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6369                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6370       continue;
6371     }
6372 
6373     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6374       return SDValue();
6375 
6376     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6377       // Span too large for a VEXT to cope
6378       return SDValue();
6379     }
6380 
6381     if (Src.MinElt >= NumSrcElts) {
6382       // The extraction can just take the second half
6383       Src.ShuffleVec =
6384           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6385                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6386       Src.WindowBase = -NumSrcElts;
6387     } else if (Src.MaxElt < NumSrcElts) {
6388       // The extraction can just take the first half
6389       Src.ShuffleVec =
6390           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6391                       DAG.getConstant(0, dl, MVT::i32));
6392     } else {
6393       // An actual VEXT is needed
6394       SDValue VEXTSrc1 =
6395           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6396                       DAG.getConstant(0, dl, MVT::i32));
6397       SDValue VEXTSrc2 =
6398           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6399                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6400 
6401       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6402                                    VEXTSrc2,
6403                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6404       Src.WindowBase = -Src.MinElt;
6405     }
6406   }
6407 
6408   // Another possible incompatibility occurs from the vector element types. We
6409   // can fix this by bitcasting the source vectors to the same type we intend
6410   // for the shuffle.
6411   for (auto &Src : Sources) {
6412     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6413     if (SrcEltTy == SmallestEltTy)
6414       continue;
6415     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6416     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6417     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6418     Src.WindowBase *= Src.WindowScale;
6419   }
6420 
6421   // Final sanity check before we try to actually produce a shuffle.
6422   DEBUG(
6423     for (auto Src : Sources)
6424       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6425   );
6426 
6427   // The stars all align, our next step is to produce the mask for the shuffle.
6428   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6429   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6430   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6431     SDValue Entry = Op.getOperand(i);
6432     if (Entry.isUndef())
6433       continue;
6434 
6435     auto Src = llvm::find(Sources, Entry.getOperand(0));
6436     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6437 
6438     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6439     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6440     // segment.
6441     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6442     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6443                                VT.getScalarSizeInBits());
6444     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6445 
6446     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6447     // starting at the appropriate offset.
6448     int *LaneMask = &Mask[i * ResMultiplier];
6449 
6450     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6451     ExtractBase += NumElts * (Src - Sources.begin());
6452     for (int j = 0; j < LanesDefined; ++j)
6453       LaneMask[j] = ExtractBase + j;
6454   }
6455 
6456   // Final check before we try to produce nonsense...
6457   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6458     return SDValue();
6459 
6460   // We can't handle more than two sources. This should have already
6461   // been checked before this point.
6462   assert(Sources.size() <= 2 && "Too many sources!");
6463 
6464   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6465   for (unsigned i = 0; i < Sources.size(); ++i)
6466     ShuffleOps[i] = Sources[i].ShuffleVec;
6467 
6468   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6469                                          ShuffleOps[1], Mask);
6470   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6471 }
6472 
6473 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6474 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6475 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6476 /// are assumed to be legal.
6477 bool
6478 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6479                                       EVT VT) const {
6480   if (VT.getVectorNumElements() == 4 &&
6481       (VT.is128BitVector() || VT.is64BitVector())) {
6482     unsigned PFIndexes[4];
6483     for (unsigned i = 0; i != 4; ++i) {
6484       if (M[i] < 0)
6485         PFIndexes[i] = 8;
6486       else
6487         PFIndexes[i] = M[i];
6488     }
6489 
6490     // Compute the index in the perfect shuffle table.
6491     unsigned PFTableIndex =
6492       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6493     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6494     unsigned Cost = (PFEntry >> 30);
6495 
6496     if (Cost <= 4)
6497       return true;
6498   }
6499 
6500   bool ReverseVEXT, isV_UNDEF;
6501   unsigned Imm, WhichResult;
6502 
6503   unsigned EltSize = VT.getScalarSizeInBits();
6504   return (EltSize >= 32 ||
6505           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6506           isVREVMask(M, VT, 64) ||
6507           isVREVMask(M, VT, 32) ||
6508           isVREVMask(M, VT, 16) ||
6509           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6510           isVTBLMask(M, VT) ||
6511           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6512           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6513 }
6514 
6515 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6516 /// the specified operations to build the shuffle.
6517 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6518                                       SDValue RHS, SelectionDAG &DAG,
6519                                       const SDLoc &dl) {
6520   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6521   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6522   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6523 
6524   enum {
6525     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6526     OP_VREV,
6527     OP_VDUP0,
6528     OP_VDUP1,
6529     OP_VDUP2,
6530     OP_VDUP3,
6531     OP_VEXT1,
6532     OP_VEXT2,
6533     OP_VEXT3,
6534     OP_VUZPL, // VUZP, left result
6535     OP_VUZPR, // VUZP, right result
6536     OP_VZIPL, // VZIP, left result
6537     OP_VZIPR, // VZIP, right result
6538     OP_VTRNL, // VTRN, left result
6539     OP_VTRNR  // VTRN, right result
6540   };
6541 
6542   if (OpNum == OP_COPY) {
6543     if (LHSID == (1*9+2)*9+3) return LHS;
6544     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6545     return RHS;
6546   }
6547 
6548   SDValue OpLHS, OpRHS;
6549   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6550   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6551   EVT VT = OpLHS.getValueType();
6552 
6553   switch (OpNum) {
6554   default: llvm_unreachable("Unknown shuffle opcode!");
6555   case OP_VREV:
6556     // VREV divides the vector in half and swaps within the half.
6557     if (VT.getVectorElementType() == MVT::i32 ||
6558         VT.getVectorElementType() == MVT::f32)
6559       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6560     // vrev <4 x i16> -> VREV32
6561     if (VT.getVectorElementType() == MVT::i16)
6562       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6563     // vrev <4 x i8> -> VREV16
6564     assert(VT.getVectorElementType() == MVT::i8);
6565     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6566   case OP_VDUP0:
6567   case OP_VDUP1:
6568   case OP_VDUP2:
6569   case OP_VDUP3:
6570     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6571                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6572   case OP_VEXT1:
6573   case OP_VEXT2:
6574   case OP_VEXT3:
6575     return DAG.getNode(ARMISD::VEXT, dl, VT,
6576                        OpLHS, OpRHS,
6577                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6578   case OP_VUZPL:
6579   case OP_VUZPR:
6580     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6581                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6582   case OP_VZIPL:
6583   case OP_VZIPR:
6584     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6585                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6586   case OP_VTRNL:
6587   case OP_VTRNR:
6588     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6589                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6590   }
6591 }
6592 
6593 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6594                                        ArrayRef<int> ShuffleMask,
6595                                        SelectionDAG &DAG) {
6596   // Check to see if we can use the VTBL instruction.
6597   SDValue V1 = Op.getOperand(0);
6598   SDValue V2 = Op.getOperand(1);
6599   SDLoc DL(Op);
6600 
6601   SmallVector<SDValue, 8> VTBLMask;
6602   for (ArrayRef<int>::iterator
6603          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6604     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6605 
6606   if (V2.getNode()->isUndef())
6607     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6608                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6609 
6610   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6611                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6612 }
6613 
6614 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6615                                                       SelectionDAG &DAG) {
6616   SDLoc DL(Op);
6617   SDValue OpLHS = Op.getOperand(0);
6618   EVT VT = OpLHS.getValueType();
6619 
6620   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6621          "Expect an v8i16/v16i8 type");
6622   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6623   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6624   // extract the first 8 bytes into the top double word and the last 8 bytes
6625   // into the bottom double word. The v8i16 case is similar.
6626   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6627   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6628                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6629 }
6630 
6631 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6632   SDValue V1 = Op.getOperand(0);
6633   SDValue V2 = Op.getOperand(1);
6634   SDLoc dl(Op);
6635   EVT VT = Op.getValueType();
6636   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6637 
6638   // Convert shuffles that are directly supported on NEON to target-specific
6639   // DAG nodes, instead of keeping them as shuffles and matching them again
6640   // during code selection.  This is more efficient and avoids the possibility
6641   // of inconsistencies between legalization and selection.
6642   // FIXME: floating-point vectors should be canonicalized to integer vectors
6643   // of the same time so that they get CSEd properly.
6644   ArrayRef<int> ShuffleMask = SVN->getMask();
6645 
6646   unsigned EltSize = VT.getScalarSizeInBits();
6647   if (EltSize <= 32) {
6648     if (SVN->isSplat()) {
6649       int Lane = SVN->getSplatIndex();
6650       // If this is undef splat, generate it via "just" vdup, if possible.
6651       if (Lane == -1) Lane = 0;
6652 
6653       // Test if V1 is a SCALAR_TO_VECTOR.
6654       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6655         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6656       }
6657       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6658       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6659       // reaches it).
6660       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6661           !isa<ConstantSDNode>(V1.getOperand(0))) {
6662         bool IsScalarToVector = true;
6663         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6664           if (!V1.getOperand(i).isUndef()) {
6665             IsScalarToVector = false;
6666             break;
6667           }
6668         if (IsScalarToVector)
6669           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6670       }
6671       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6672                          DAG.getConstant(Lane, dl, MVT::i32));
6673     }
6674 
6675     bool ReverseVEXT;
6676     unsigned Imm;
6677     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6678       if (ReverseVEXT)
6679         std::swap(V1, V2);
6680       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6681                          DAG.getConstant(Imm, dl, MVT::i32));
6682     }
6683 
6684     if (isVREVMask(ShuffleMask, VT, 64))
6685       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6686     if (isVREVMask(ShuffleMask, VT, 32))
6687       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6688     if (isVREVMask(ShuffleMask, VT, 16))
6689       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6690 
6691     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6692       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6693                          DAG.getConstant(Imm, dl, MVT::i32));
6694     }
6695 
6696     // Check for Neon shuffles that modify both input vectors in place.
6697     // If both results are used, i.e., if there are two shuffles with the same
6698     // source operands and with masks corresponding to both results of one of
6699     // these operations, DAG memoization will ensure that a single node is
6700     // used for both shuffles.
6701     unsigned WhichResult;
6702     bool isV_UNDEF;
6703     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6704             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6705       if (isV_UNDEF)
6706         V2 = V1;
6707       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6708           .getValue(WhichResult);
6709     }
6710 
6711     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6712     // shuffles that produce a result larger than their operands with:
6713     //   shuffle(concat(v1, undef), concat(v2, undef))
6714     // ->
6715     //   shuffle(concat(v1, v2), undef)
6716     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6717     //
6718     // This is useful in the general case, but there are special cases where
6719     // native shuffles produce larger results: the two-result ops.
6720     //
6721     // Look through the concat when lowering them:
6722     //   shuffle(concat(v1, v2), undef)
6723     // ->
6724     //   concat(VZIP(v1, v2):0, :1)
6725     //
6726     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6727       SDValue SubV1 = V1->getOperand(0);
6728       SDValue SubV2 = V1->getOperand(1);
6729       EVT SubVT = SubV1.getValueType();
6730 
6731       // We expect these to have been canonicalized to -1.
6732       assert(llvm::all_of(ShuffleMask, [&](int i) {
6733         return i < (int)VT.getVectorNumElements();
6734       }) && "Unexpected shuffle index into UNDEF operand!");
6735 
6736       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6737               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6738         if (isV_UNDEF)
6739           SubV2 = SubV1;
6740         assert((WhichResult == 0) &&
6741                "In-place shuffle of concat can only have one result!");
6742         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6743                                   SubV1, SubV2);
6744         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6745                            Res.getValue(1));
6746       }
6747     }
6748   }
6749 
6750   // If the shuffle is not directly supported and it has 4 elements, use
6751   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6752   unsigned NumElts = VT.getVectorNumElements();
6753   if (NumElts == 4) {
6754     unsigned PFIndexes[4];
6755     for (unsigned i = 0; i != 4; ++i) {
6756       if (ShuffleMask[i] < 0)
6757         PFIndexes[i] = 8;
6758       else
6759         PFIndexes[i] = ShuffleMask[i];
6760     }
6761 
6762     // Compute the index in the perfect shuffle table.
6763     unsigned PFTableIndex =
6764       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6765     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6766     unsigned Cost = (PFEntry >> 30);
6767 
6768     if (Cost <= 4)
6769       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6770   }
6771 
6772   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6773   if (EltSize >= 32) {
6774     // Do the expansion with floating-point types, since that is what the VFP
6775     // registers are defined to use, and since i64 is not legal.
6776     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6777     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6778     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6779     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6780     SmallVector<SDValue, 8> Ops;
6781     for (unsigned i = 0; i < NumElts; ++i) {
6782       if (ShuffleMask[i] < 0)
6783         Ops.push_back(DAG.getUNDEF(EltVT));
6784       else
6785         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6786                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6787                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6788                                                   dl, MVT::i32)));
6789     }
6790     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6791     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6792   }
6793 
6794   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6795     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6796 
6797   if (VT == MVT::v8i8)
6798     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6799       return NewOp;
6800 
6801   return SDValue();
6802 }
6803 
6804 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6805   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6806   SDValue Lane = Op.getOperand(2);
6807   if (!isa<ConstantSDNode>(Lane))
6808     return SDValue();
6809 
6810   return Op;
6811 }
6812 
6813 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6814   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6815   SDValue Lane = Op.getOperand(1);
6816   if (!isa<ConstantSDNode>(Lane))
6817     return SDValue();
6818 
6819   SDValue Vec = Op.getOperand(0);
6820   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6821     SDLoc dl(Op);
6822     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6823   }
6824 
6825   return Op;
6826 }
6827 
6828 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6829   // The only time a CONCAT_VECTORS operation can have legal types is when
6830   // two 64-bit vectors are concatenated to a 128-bit vector.
6831   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6832          "unexpected CONCAT_VECTORS");
6833   SDLoc dl(Op);
6834   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6835   SDValue Op0 = Op.getOperand(0);
6836   SDValue Op1 = Op.getOperand(1);
6837   if (!Op0.isUndef())
6838     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6839                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6840                       DAG.getIntPtrConstant(0, dl));
6841   if (!Op1.isUndef())
6842     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6843                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6844                       DAG.getIntPtrConstant(1, dl));
6845   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6846 }
6847 
6848 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6849 /// element has been zero/sign-extended, depending on the isSigned parameter,
6850 /// from an integer type half its size.
6851 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6852                                    bool isSigned) {
6853   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6854   EVT VT = N->getValueType(0);
6855   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6856     SDNode *BVN = N->getOperand(0).getNode();
6857     if (BVN->getValueType(0) != MVT::v4i32 ||
6858         BVN->getOpcode() != ISD::BUILD_VECTOR)
6859       return false;
6860     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6861     unsigned HiElt = 1 - LoElt;
6862     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6863     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6864     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6865     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6866     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6867       return false;
6868     if (isSigned) {
6869       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6870           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6871         return true;
6872     } else {
6873       if (Hi0->isNullValue() && Hi1->isNullValue())
6874         return true;
6875     }
6876     return false;
6877   }
6878 
6879   if (N->getOpcode() != ISD::BUILD_VECTOR)
6880     return false;
6881 
6882   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6883     SDNode *Elt = N->getOperand(i).getNode();
6884     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6885       unsigned EltSize = VT.getScalarSizeInBits();
6886       unsigned HalfSize = EltSize / 2;
6887       if (isSigned) {
6888         if (!isIntN(HalfSize, C->getSExtValue()))
6889           return false;
6890       } else {
6891         if (!isUIntN(HalfSize, C->getZExtValue()))
6892           return false;
6893       }
6894       continue;
6895     }
6896     return false;
6897   }
6898 
6899   return true;
6900 }
6901 
6902 /// isSignExtended - Check if a node is a vector value that is sign-extended
6903 /// or a constant BUILD_VECTOR with sign-extended elements.
6904 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6905   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6906     return true;
6907   if (isExtendedBUILD_VECTOR(N, DAG, true))
6908     return true;
6909   return false;
6910 }
6911 
6912 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6913 /// or a constant BUILD_VECTOR with zero-extended elements.
6914 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6915   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6916     return true;
6917   if (isExtendedBUILD_VECTOR(N, DAG, false))
6918     return true;
6919   return false;
6920 }
6921 
6922 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6923   if (OrigVT.getSizeInBits() >= 64)
6924     return OrigVT;
6925 
6926   assert(OrigVT.isSimple() && "Expecting a simple value type");
6927 
6928   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6929   switch (OrigSimpleTy) {
6930   default: llvm_unreachable("Unexpected Vector Type");
6931   case MVT::v2i8:
6932   case MVT::v2i16:
6933      return MVT::v2i32;
6934   case MVT::v4i8:
6935     return  MVT::v4i16;
6936   }
6937 }
6938 
6939 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6940 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6941 /// We insert the required extension here to get the vector to fill a D register.
6942 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6943                                             const EVT &OrigTy,
6944                                             const EVT &ExtTy,
6945                                             unsigned ExtOpcode) {
6946   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6947   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6948   // 64-bits we need to insert a new extension so that it will be 64-bits.
6949   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6950   if (OrigTy.getSizeInBits() >= 64)
6951     return N;
6952 
6953   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6954   EVT NewVT = getExtensionTo64Bits(OrigTy);
6955 
6956   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6957 }
6958 
6959 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6960 /// does not do any sign/zero extension. If the original vector is less
6961 /// than 64 bits, an appropriate extension will be added after the load to
6962 /// reach a total size of 64 bits. We have to add the extension separately
6963 /// because ARM does not have a sign/zero extending load for vectors.
6964 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6965   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6966 
6967   // The load already has the right type.
6968   if (ExtendedTy == LD->getMemoryVT())
6969     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6970                        LD->getBasePtr(), LD->getPointerInfo(),
6971                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6972 
6973   // We need to create a zextload/sextload. We cannot just create a load
6974   // followed by a zext/zext node because LowerMUL is also run during normal
6975   // operation legalization where we can't create illegal types.
6976   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6977                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6978                         LD->getMemoryVT(), LD->getAlignment(),
6979                         LD->getMemOperand()->getFlags());
6980 }
6981 
6982 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6983 /// extending load, or BUILD_VECTOR with extended elements, return the
6984 /// unextended value. The unextended vector should be 64 bits so that it can
6985 /// be used as an operand to a VMULL instruction. If the original vector size
6986 /// before extension is less than 64 bits we add a an extension to resize
6987 /// the vector to 64 bits.
6988 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6989   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6990     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6991                                         N->getOperand(0)->getValueType(0),
6992                                         N->getValueType(0),
6993                                         N->getOpcode());
6994 
6995   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6996     return SkipLoadExtensionForVMULL(LD, DAG);
6997 
6998   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6999   // have been legalized as a BITCAST from v4i32.
7000   if (N->getOpcode() == ISD::BITCAST) {
7001     SDNode *BVN = N->getOperand(0).getNode();
7002     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7003            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7004     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7005     return DAG.getBuildVector(
7006         MVT::v2i32, SDLoc(N),
7007         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7008   }
7009   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7010   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7011   EVT VT = N->getValueType(0);
7012   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7013   unsigned NumElts = VT.getVectorNumElements();
7014   MVT TruncVT = MVT::getIntegerVT(EltSize);
7015   SmallVector<SDValue, 8> Ops;
7016   SDLoc dl(N);
7017   for (unsigned i = 0; i != NumElts; ++i) {
7018     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7019     const APInt &CInt = C->getAPIntValue();
7020     // Element types smaller than 32 bits are not legal, so use i32 elements.
7021     // The values are implicitly truncated so sext vs. zext doesn't matter.
7022     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7023   }
7024   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7025 }
7026 
7027 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7028   unsigned Opcode = N->getOpcode();
7029   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7030     SDNode *N0 = N->getOperand(0).getNode();
7031     SDNode *N1 = N->getOperand(1).getNode();
7032     return N0->hasOneUse() && N1->hasOneUse() &&
7033       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7034   }
7035   return false;
7036 }
7037 
7038 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7039   unsigned Opcode = N->getOpcode();
7040   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7041     SDNode *N0 = N->getOperand(0).getNode();
7042     SDNode *N1 = N->getOperand(1).getNode();
7043     return N0->hasOneUse() && N1->hasOneUse() &&
7044       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7045   }
7046   return false;
7047 }
7048 
7049 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7050   // Multiplications are only custom-lowered for 128-bit vectors so that
7051   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7052   EVT VT = Op.getValueType();
7053   assert(VT.is128BitVector() && VT.isInteger() &&
7054          "unexpected type for custom-lowering ISD::MUL");
7055   SDNode *N0 = Op.getOperand(0).getNode();
7056   SDNode *N1 = Op.getOperand(1).getNode();
7057   unsigned NewOpc = 0;
7058   bool isMLA = false;
7059   bool isN0SExt = isSignExtended(N0, DAG);
7060   bool isN1SExt = isSignExtended(N1, DAG);
7061   if (isN0SExt && isN1SExt)
7062     NewOpc = ARMISD::VMULLs;
7063   else {
7064     bool isN0ZExt = isZeroExtended(N0, DAG);
7065     bool isN1ZExt = isZeroExtended(N1, DAG);
7066     if (isN0ZExt && isN1ZExt)
7067       NewOpc = ARMISD::VMULLu;
7068     else if (isN1SExt || isN1ZExt) {
7069       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7070       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7071       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7072         NewOpc = ARMISD::VMULLs;
7073         isMLA = true;
7074       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7075         NewOpc = ARMISD::VMULLu;
7076         isMLA = true;
7077       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7078         std::swap(N0, N1);
7079         NewOpc = ARMISD::VMULLu;
7080         isMLA = true;
7081       }
7082     }
7083 
7084     if (!NewOpc) {
7085       if (VT == MVT::v2i64)
7086         // Fall through to expand this.  It is not legal.
7087         return SDValue();
7088       else
7089         // Other vector multiplications are legal.
7090         return Op;
7091     }
7092   }
7093 
7094   // Legalize to a VMULL instruction.
7095   SDLoc DL(Op);
7096   SDValue Op0;
7097   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7098   if (!isMLA) {
7099     Op0 = SkipExtensionForVMULL(N0, DAG);
7100     assert(Op0.getValueType().is64BitVector() &&
7101            Op1.getValueType().is64BitVector() &&
7102            "unexpected types for extended operands to VMULL");
7103     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7104   }
7105 
7106   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7107   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7108   //   vmull q0, d4, d6
7109   //   vmlal q0, d5, d6
7110   // is faster than
7111   //   vaddl q0, d4, d5
7112   //   vmovl q1, d6
7113   //   vmul  q0, q0, q1
7114   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7115   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7116   EVT Op1VT = Op1.getValueType();
7117   return DAG.getNode(N0->getOpcode(), DL, VT,
7118                      DAG.getNode(NewOpc, DL, VT,
7119                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7120                      DAG.getNode(NewOpc, DL, VT,
7121                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7122 }
7123 
7124 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7125                               SelectionDAG &DAG) {
7126   // TODO: Should this propagate fast-math-flags?
7127 
7128   // Convert to float
7129   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7130   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7131   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7132   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7133   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7134   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7135   // Get reciprocal estimate.
7136   // float4 recip = vrecpeq_f32(yf);
7137   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7138                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7139                    Y);
7140   // Because char has a smaller range than uchar, we can actually get away
7141   // without any newton steps.  This requires that we use a weird bias
7142   // of 0xb000, however (again, this has been exhaustively tested).
7143   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7144   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7145   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7146   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7147   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7148   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7149   // Convert back to short.
7150   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7151   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7152   return X;
7153 }
7154 
7155 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7156                                SelectionDAG &DAG) {
7157   // TODO: Should this propagate fast-math-flags?
7158 
7159   SDValue N2;
7160   // Convert to float.
7161   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7162   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7163   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7164   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7165   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7166   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7167 
7168   // Use reciprocal estimate and one refinement step.
7169   // float4 recip = vrecpeq_f32(yf);
7170   // recip *= vrecpsq_f32(yf, recip);
7171   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7172                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7173                    N1);
7174   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7175                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7176                    N1, N2);
7177   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7178   // Because short has a smaller range than ushort, we can actually get away
7179   // with only a single newton step.  This requires that we use a weird bias
7180   // of 89, however (again, this has been exhaustively tested).
7181   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7182   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7183   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7184   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7185   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7186   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7187   // Convert back to integer and return.
7188   // return vmovn_s32(vcvt_s32_f32(result));
7189   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7190   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7191   return N0;
7192 }
7193 
7194 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7195   EVT VT = Op.getValueType();
7196   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7197          "unexpected type for custom-lowering ISD::SDIV");
7198 
7199   SDLoc dl(Op);
7200   SDValue N0 = Op.getOperand(0);
7201   SDValue N1 = Op.getOperand(1);
7202   SDValue N2, N3;
7203 
7204   if (VT == MVT::v8i8) {
7205     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7206     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7207 
7208     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7209                      DAG.getIntPtrConstant(4, dl));
7210     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7211                      DAG.getIntPtrConstant(4, dl));
7212     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7213                      DAG.getIntPtrConstant(0, dl));
7214     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7215                      DAG.getIntPtrConstant(0, dl));
7216 
7217     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7218     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7219 
7220     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7221     N0 = LowerCONCAT_VECTORS(N0, DAG);
7222 
7223     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7224     return N0;
7225   }
7226   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7227 }
7228 
7229 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7230   // TODO: Should this propagate fast-math-flags?
7231   EVT VT = Op.getValueType();
7232   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7233          "unexpected type for custom-lowering ISD::UDIV");
7234 
7235   SDLoc dl(Op);
7236   SDValue N0 = Op.getOperand(0);
7237   SDValue N1 = Op.getOperand(1);
7238   SDValue N2, N3;
7239 
7240   if (VT == MVT::v8i8) {
7241     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7242     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7243 
7244     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7245                      DAG.getIntPtrConstant(4, dl));
7246     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7247                      DAG.getIntPtrConstant(4, dl));
7248     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7249                      DAG.getIntPtrConstant(0, dl));
7250     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7251                      DAG.getIntPtrConstant(0, dl));
7252 
7253     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7254     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7255 
7256     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7257     N0 = LowerCONCAT_VECTORS(N0, DAG);
7258 
7259     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7260                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7261                                      MVT::i32),
7262                      N0);
7263     return N0;
7264   }
7265 
7266   // v4i16 sdiv ... Convert to float.
7267   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7268   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7269   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7270   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7271   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7272   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7273 
7274   // Use reciprocal estimate and two refinement steps.
7275   // float4 recip = vrecpeq_f32(yf);
7276   // recip *= vrecpsq_f32(yf, recip);
7277   // recip *= vrecpsq_f32(yf, recip);
7278   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7279                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7280                    BN1);
7281   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7282                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7283                    BN1, N2);
7284   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7285   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7286                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7287                    BN1, N2);
7288   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7289   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7290   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7291   // and that it will never cause us to return an answer too large).
7292   // float4 result = as_float4(as_int4(xf*recip) + 2);
7293   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7294   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7295   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7296   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7297   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7298   // Convert back to integer and return.
7299   // return vmovn_u32(vcvt_s32_f32(result));
7300   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7301   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7302   return N0;
7303 }
7304 
7305 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7306   EVT VT = Op.getNode()->getValueType(0);
7307   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7308 
7309   unsigned Opc;
7310   bool ExtraOp = false;
7311   switch (Op.getOpcode()) {
7312   default: llvm_unreachable("Invalid code");
7313   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7314   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7315   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7316   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7317   }
7318 
7319   if (!ExtraOp)
7320     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7321                        Op.getOperand(1));
7322   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7323                      Op.getOperand(1), Op.getOperand(2));
7324 }
7325 
7326 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7327   assert(Subtarget->isTargetDarwin());
7328 
7329   // For iOS, we want to call an alternative entry point: __sincos_stret,
7330   // return values are passed via sret.
7331   SDLoc dl(Op);
7332   SDValue Arg = Op.getOperand(0);
7333   EVT ArgVT = Arg.getValueType();
7334   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7335   auto PtrVT = getPointerTy(DAG.getDataLayout());
7336 
7337   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7339 
7340   // Pair of floats / doubles used to pass the result.
7341   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
7342   auto &DL = DAG.getDataLayout();
7343 
7344   ArgListTy Args;
7345   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7346   SDValue SRet;
7347   if (ShouldUseSRet) {
7348     // Create stack object for sret.
7349     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7350     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7351     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7352     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7353 
7354     ArgListEntry Entry;
7355     Entry.Node = SRet;
7356     Entry.Ty = RetTy->getPointerTo();
7357     Entry.IsSExt = false;
7358     Entry.IsZExt = false;
7359     Entry.IsSRet = true;
7360     Args.push_back(Entry);
7361     RetTy = Type::getVoidTy(*DAG.getContext());
7362   }
7363 
7364   ArgListEntry Entry;
7365   Entry.Node = Arg;
7366   Entry.Ty = ArgTy;
7367   Entry.IsSExt = false;
7368   Entry.IsZExt = false;
7369   Args.push_back(Entry);
7370 
7371   const char *LibcallName =
7372       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7373   RTLIB::Libcall LC =
7374       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7375   CallingConv::ID CC = getLibcallCallingConv(LC);
7376   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7377 
7378   TargetLowering::CallLoweringInfo CLI(DAG);
7379   CLI.setDebugLoc(dl)
7380       .setChain(DAG.getEntryNode())
7381       .setCallee(CC, RetTy, Callee, std::move(Args))
7382       .setDiscardResult(ShouldUseSRet);
7383   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7384 
7385   if (!ShouldUseSRet)
7386     return CallResult.first;
7387 
7388   SDValue LoadSin =
7389       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7390 
7391   // Address of cos field.
7392   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7393                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7394   SDValue LoadCos =
7395       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7396 
7397   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7398   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7399                      LoadSin.getValue(0), LoadCos.getValue(0));
7400 }
7401 
7402 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7403                                                   bool Signed,
7404                                                   SDValue &Chain) const {
7405   EVT VT = Op.getValueType();
7406   assert((VT == MVT::i32 || VT == MVT::i64) &&
7407          "unexpected type for custom lowering DIV");
7408   SDLoc dl(Op);
7409 
7410   const auto &DL = DAG.getDataLayout();
7411   const auto &TLI = DAG.getTargetLoweringInfo();
7412 
7413   const char *Name = nullptr;
7414   if (Signed)
7415     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7416   else
7417     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7418 
7419   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7420 
7421   ARMTargetLowering::ArgListTy Args;
7422 
7423   for (auto AI : {1, 0}) {
7424     ArgListEntry Arg;
7425     Arg.Node = Op.getOperand(AI);
7426     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7427     Args.push_back(Arg);
7428   }
7429 
7430   CallLoweringInfo CLI(DAG);
7431   CLI.setDebugLoc(dl)
7432     .setChain(Chain)
7433     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7434                ES, std::move(Args));
7435 
7436   return LowerCallTo(CLI).first;
7437 }
7438 
7439 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7440                                             bool Signed) const {
7441   assert(Op.getValueType() == MVT::i32 &&
7442          "unexpected type for custom lowering DIV");
7443   SDLoc dl(Op);
7444 
7445   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7446                                DAG.getEntryNode(), Op.getOperand(1));
7447 
7448   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7449 }
7450 
7451 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7452   SDLoc DL(N);
7453   SDValue Op = N->getOperand(1);
7454   if (N->getValueType(0) == MVT::i32)
7455     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7456   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7457                            DAG.getConstant(0, DL, MVT::i32));
7458   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7459                            DAG.getConstant(1, DL, MVT::i32));
7460   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7461                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7462 }
7463 
7464 void ARMTargetLowering::ExpandDIV_Windows(
7465     SDValue Op, SelectionDAG &DAG, bool Signed,
7466     SmallVectorImpl<SDValue> &Results) const {
7467   const auto &DL = DAG.getDataLayout();
7468   const auto &TLI = DAG.getTargetLoweringInfo();
7469 
7470   assert(Op.getValueType() == MVT::i64 &&
7471          "unexpected type for custom lowering DIV");
7472   SDLoc dl(Op);
7473 
7474   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7475 
7476   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7477 
7478   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7479   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7480                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7481   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7482 
7483   Results.push_back(Lower);
7484   Results.push_back(Upper);
7485 }
7486 
7487 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7488   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7489     // Acquire/Release load/store is not legal for targets without a dmb or
7490     // equivalent available.
7491     return SDValue();
7492 
7493   // Monotonic load/store is legal for all targets.
7494   return Op;
7495 }
7496 
7497 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7498                                     SmallVectorImpl<SDValue> &Results,
7499                                     SelectionDAG &DAG,
7500                                     const ARMSubtarget *Subtarget) {
7501   SDLoc DL(N);
7502   // Under Power Management extensions, the cycle-count is:
7503   //    mrc p15, #0, <Rt>, c9, c13, #0
7504   SDValue Ops[] = { N->getOperand(0), // Chain
7505                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7506                     DAG.getConstant(15, DL, MVT::i32),
7507                     DAG.getConstant(0, DL, MVT::i32),
7508                     DAG.getConstant(9, DL, MVT::i32),
7509                     DAG.getConstant(13, DL, MVT::i32),
7510                     DAG.getConstant(0, DL, MVT::i32)
7511   };
7512 
7513   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7514                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7515   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7516                                 DAG.getConstant(0, DL, MVT::i32)));
7517   Results.push_back(Cycles32.getValue(1));
7518 }
7519 
7520 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7521   SDLoc dl(V.getNode());
7522   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7523   SDValue VHi = DAG.getAnyExtOrTrunc(
7524       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7525       dl, MVT::i32);
7526   SDValue RegClass =
7527       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7528   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7529   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7530   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7531   return SDValue(
7532       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7533 }
7534 
7535 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7536                                        SmallVectorImpl<SDValue> & Results,
7537                                        SelectionDAG &DAG) {
7538   assert(N->getValueType(0) == MVT::i64 &&
7539          "AtomicCmpSwap on types less than 64 should be legal");
7540   SDValue Ops[] = {N->getOperand(1),
7541                    createGPRPairNode(DAG, N->getOperand(2)),
7542                    createGPRPairNode(DAG, N->getOperand(3)),
7543                    N->getOperand(0)};
7544   SDNode *CmpSwap = DAG.getMachineNode(
7545       ARM::CMP_SWAP_64, SDLoc(N),
7546       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7547 
7548   MachineFunction &MF = DAG.getMachineFunction();
7549   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7550   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7551   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7552 
7553   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7554                                                SDValue(CmpSwap, 0)));
7555   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7556                                                SDValue(CmpSwap, 0)));
7557   Results.push_back(SDValue(CmpSwap, 2));
7558 }
7559 
7560 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7561                           SelectionDAG &DAG) {
7562   const auto &TLI = DAG.getTargetLoweringInfo();
7563 
7564   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7565          "Custom lowering is MSVCRT specific!");
7566 
7567   SDLoc dl(Op);
7568   SDValue Val = Op.getOperand(0);
7569   MVT Ty = Val->getSimpleValueType(0);
7570   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7571   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7572                                          TLI.getPointerTy(DAG.getDataLayout()));
7573 
7574   TargetLowering::ArgListTy Args;
7575   TargetLowering::ArgListEntry Entry;
7576 
7577   Entry.Node = Val;
7578   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7579   Entry.IsZExt = true;
7580   Args.push_back(Entry);
7581 
7582   Entry.Node = Exponent;
7583   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7584   Entry.IsZExt = true;
7585   Args.push_back(Entry);
7586 
7587   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7588 
7589   // In the in-chain to the call is the entry node  If we are emitting a
7590   // tailcall, the chain will be mutated if the node has a non-entry input
7591   // chain.
7592   SDValue InChain = DAG.getEntryNode();
7593   SDValue TCChain = InChain;
7594 
7595   const auto *F = DAG.getMachineFunction().getFunction();
7596   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7597               F->getReturnType() == LCRTy;
7598   if (IsTC)
7599     InChain = TCChain;
7600 
7601   TargetLowering::CallLoweringInfo CLI(DAG);
7602   CLI.setDebugLoc(dl)
7603       .setChain(InChain)
7604       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7605       .setTailCall(IsTC);
7606   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7607 
7608   // Return the chain (the DAG root) if it is a tail call
7609   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7610 }
7611 
7612 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7613   switch (Op.getOpcode()) {
7614   default: llvm_unreachable("Don't know how to custom lower this!");
7615   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7616   case ISD::ConstantPool:
7617     if (Subtarget->genExecuteOnly())
7618       llvm_unreachable("execute-only should not generate constant pools");
7619     return LowerConstantPool(Op, DAG);
7620   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7621   case ISD::GlobalAddress:
7622     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7623     default: llvm_unreachable("unknown object format");
7624     case Triple::COFF:
7625       return LowerGlobalAddressWindows(Op, DAG);
7626     case Triple::ELF:
7627       return LowerGlobalAddressELF(Op, DAG);
7628     case Triple::MachO:
7629       return LowerGlobalAddressDarwin(Op, DAG);
7630     }
7631   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7632   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7633   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7634   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7635   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7636   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7637   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7638   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7639   case ISD::SINT_TO_FP:
7640   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7641   case ISD::FP_TO_SINT:
7642   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7643   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7644   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7645   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7646   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7647   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7648   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7649   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7650                                                                Subtarget);
7651   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7652   case ISD::SHL:
7653   case ISD::SRL:
7654   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7655   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7656   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7657   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7658   case ISD::SRL_PARTS:
7659   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7660   case ISD::CTTZ:
7661   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7662   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7663   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7664   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7665   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7666   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7667   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7668   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7669   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7670   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7671   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7672   case ISD::MUL:           return LowerMUL(Op, DAG);
7673   case ISD::SDIV:
7674     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7675       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7676     return LowerSDIV(Op, DAG);
7677   case ISD::UDIV:
7678     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7679       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7680     return LowerUDIV(Op, DAG);
7681   case ISD::ADDC:
7682   case ISD::ADDE:
7683   case ISD::SUBC:
7684   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7685   case ISD::SADDO:
7686   case ISD::UADDO:
7687   case ISD::SSUBO:
7688   case ISD::USUBO:
7689     return LowerXALUO(Op, DAG);
7690   case ISD::ATOMIC_LOAD:
7691   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7692   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7693   case ISD::SDIVREM:
7694   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7695   case ISD::DYNAMIC_STACKALLOC:
7696     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7697       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7698     llvm_unreachable("Don't know how to custom lower this!");
7699   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7700   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7701   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7702   case ARMISD::WIN__DBZCHK: return SDValue();
7703   }
7704 }
7705 
7706 /// ReplaceNodeResults - Replace the results of node with an illegal result
7707 /// type with new values built out of custom code.
7708 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7709                                            SmallVectorImpl<SDValue> &Results,
7710                                            SelectionDAG &DAG) const {
7711   SDValue Res;
7712   switch (N->getOpcode()) {
7713   default:
7714     llvm_unreachable("Don't know how to custom expand this!");
7715   case ISD::READ_REGISTER:
7716     ExpandREAD_REGISTER(N, Results, DAG);
7717     break;
7718   case ISD::BITCAST:
7719     Res = ExpandBITCAST(N, DAG);
7720     break;
7721   case ISD::SRL:
7722   case ISD::SRA:
7723     Res = Expand64BitShift(N, DAG, Subtarget);
7724     break;
7725   case ISD::SREM:
7726   case ISD::UREM:
7727     Res = LowerREM(N, DAG);
7728     break;
7729   case ISD::SDIVREM:
7730   case ISD::UDIVREM:
7731     Res = LowerDivRem(SDValue(N, 0), DAG);
7732     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7733     Results.push_back(Res.getValue(0));
7734     Results.push_back(Res.getValue(1));
7735     return;
7736   case ISD::READCYCLECOUNTER:
7737     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7738     return;
7739   case ISD::UDIV:
7740   case ISD::SDIV:
7741     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7742     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7743                              Results);
7744   case ISD::ATOMIC_CMP_SWAP:
7745     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7746     return;
7747   }
7748   if (Res.getNode())
7749     Results.push_back(Res);
7750 }
7751 
7752 //===----------------------------------------------------------------------===//
7753 //                           ARM Scheduler Hooks
7754 //===----------------------------------------------------------------------===//
7755 
7756 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7757 /// registers the function context.
7758 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7759                                                MachineBasicBlock *MBB,
7760                                                MachineBasicBlock *DispatchBB,
7761                                                int FI) const {
7762   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7763          "ROPI/RWPI not currently supported with SjLj");
7764   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7765   DebugLoc dl = MI.getDebugLoc();
7766   MachineFunction *MF = MBB->getParent();
7767   MachineRegisterInfo *MRI = &MF->getRegInfo();
7768   MachineConstantPool *MCP = MF->getConstantPool();
7769   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7770   const Function *F = MF->getFunction();
7771 
7772   bool isThumb = Subtarget->isThumb();
7773   bool isThumb2 = Subtarget->isThumb2();
7774 
7775   unsigned PCLabelId = AFI->createPICLabelUId();
7776   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7777   ARMConstantPoolValue *CPV =
7778     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7779   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7780 
7781   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7782                                            : &ARM::GPRRegClass;
7783 
7784   // Grab constant pool and fixed stack memory operands.
7785   MachineMemOperand *CPMMO =
7786       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7787                                MachineMemOperand::MOLoad, 4, 4);
7788 
7789   MachineMemOperand *FIMMOSt =
7790       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7791                                MachineMemOperand::MOStore, 4, 4);
7792 
7793   // Load the address of the dispatch MBB into the jump buffer.
7794   if (isThumb2) {
7795     // Incoming value: jbuf
7796     //   ldr.n  r5, LCPI1_1
7797     //   orr    r5, r5, #1
7798     //   add    r5, pc
7799     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7800     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7801     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7802         .addConstantPoolIndex(CPI)
7803         .addMemOperand(CPMMO)
7804         .add(predOps(ARMCC::AL));
7805     // Set the low bit because of thumb mode.
7806     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7807     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7808         .addReg(NewVReg1, RegState::Kill)
7809         .addImm(0x01)
7810         .add(predOps(ARMCC::AL))
7811         .add(condCodeOp());
7812     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7813     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7814       .addReg(NewVReg2, RegState::Kill)
7815       .addImm(PCLabelId);
7816     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7817         .addReg(NewVReg3, RegState::Kill)
7818         .addFrameIndex(FI)
7819         .addImm(36) // &jbuf[1] :: pc
7820         .addMemOperand(FIMMOSt)
7821         .add(predOps(ARMCC::AL));
7822   } else if (isThumb) {
7823     // Incoming value: jbuf
7824     //   ldr.n  r1, LCPI1_4
7825     //   add    r1, pc
7826     //   mov    r2, #1
7827     //   orrs   r1, r2
7828     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7829     //   str    r1, [r2]
7830     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7831     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7832         .addConstantPoolIndex(CPI)
7833         .addMemOperand(CPMMO)
7834         .add(predOps(ARMCC::AL));
7835     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7836     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7837       .addReg(NewVReg1, RegState::Kill)
7838       .addImm(PCLabelId);
7839     // Set the low bit because of thumb mode.
7840     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7841     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7842         .addReg(ARM::CPSR, RegState::Define)
7843         .addImm(1)
7844         .add(predOps(ARMCC::AL));
7845     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7846     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7847         .addReg(ARM::CPSR, RegState::Define)
7848         .addReg(NewVReg2, RegState::Kill)
7849         .addReg(NewVReg3, RegState::Kill)
7850         .add(predOps(ARMCC::AL));
7851     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7852     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7853             .addFrameIndex(FI)
7854             .addImm(36); // &jbuf[1] :: pc
7855     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7856         .addReg(NewVReg4, RegState::Kill)
7857         .addReg(NewVReg5, RegState::Kill)
7858         .addImm(0)
7859         .addMemOperand(FIMMOSt)
7860         .add(predOps(ARMCC::AL));
7861   } else {
7862     // Incoming value: jbuf
7863     //   ldr  r1, LCPI1_1
7864     //   add  r1, pc, r1
7865     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7866     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7867     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7868         .addConstantPoolIndex(CPI)
7869         .addImm(0)
7870         .addMemOperand(CPMMO)
7871         .add(predOps(ARMCC::AL));
7872     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7873     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7874         .addReg(NewVReg1, RegState::Kill)
7875         .addImm(PCLabelId)
7876         .add(predOps(ARMCC::AL));
7877     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7878         .addReg(NewVReg2, RegState::Kill)
7879         .addFrameIndex(FI)
7880         .addImm(36) // &jbuf[1] :: pc
7881         .addMemOperand(FIMMOSt)
7882         .add(predOps(ARMCC::AL));
7883   }
7884 }
7885 
7886 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7887                                               MachineBasicBlock *MBB) const {
7888   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7889   DebugLoc dl = MI.getDebugLoc();
7890   MachineFunction *MF = MBB->getParent();
7891   MachineRegisterInfo *MRI = &MF->getRegInfo();
7892   MachineFrameInfo &MFI = MF->getFrameInfo();
7893   int FI = MFI.getFunctionContextIndex();
7894 
7895   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7896                                                         : &ARM::GPRnopcRegClass;
7897 
7898   // Get a mapping of the call site numbers to all of the landing pads they're
7899   // associated with.
7900   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
7901   unsigned MaxCSNum = 0;
7902   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7903        ++BB) {
7904     if (!BB->isEHPad()) continue;
7905 
7906     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7907     // pad.
7908     for (MachineBasicBlock::iterator
7909            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7910       if (!II->isEHLabel()) continue;
7911 
7912       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7913       if (!MF->hasCallSiteLandingPad(Sym)) continue;
7914 
7915       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
7916       for (SmallVectorImpl<unsigned>::iterator
7917              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7918            CSI != CSE; ++CSI) {
7919         CallSiteNumToLPad[*CSI].push_back(&*BB);
7920         MaxCSNum = std::max(MaxCSNum, *CSI);
7921       }
7922       break;
7923     }
7924   }
7925 
7926   // Get an ordered list of the machine basic blocks for the jump table.
7927   std::vector<MachineBasicBlock*> LPadList;
7928   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7929   LPadList.reserve(CallSiteNumToLPad.size());
7930   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7931     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7932     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7933            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7934       LPadList.push_back(*II);
7935       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7936     }
7937   }
7938 
7939   assert(!LPadList.empty() &&
7940          "No landing pad destinations for the dispatch jump table!");
7941 
7942   // Create the jump table and associated information.
7943   MachineJumpTableInfo *JTI =
7944     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7945   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7946 
7947   // Create the MBBs for the dispatch code.
7948 
7949   // Shove the dispatch's address into the return slot in the function context.
7950   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7951   DispatchBB->setIsEHPad();
7952 
7953   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7954   unsigned trap_opcode;
7955   if (Subtarget->isThumb())
7956     trap_opcode = ARM::tTRAP;
7957   else
7958     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7959 
7960   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7961   DispatchBB->addSuccessor(TrapBB);
7962 
7963   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7964   DispatchBB->addSuccessor(DispContBB);
7965 
7966   // Insert and MBBs.
7967   MF->insert(MF->end(), DispatchBB);
7968   MF->insert(MF->end(), DispContBB);
7969   MF->insert(MF->end(), TrapBB);
7970 
7971   // Insert code into the entry block that creates and registers the function
7972   // context.
7973   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7974 
7975   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7976       MachinePointerInfo::getFixedStack(*MF, FI),
7977       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7978 
7979   MachineInstrBuilder MIB;
7980   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7981 
7982   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7983   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7984 
7985   // Add a register mask with no preserved registers.  This results in all
7986   // registers being marked as clobbered. This can't work if the dispatch block
7987   // is in a Thumb1 function and is linked with ARM code which uses the FP
7988   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
7989   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
7990 
7991   bool IsPositionIndependent = isPositionIndependent();
7992   unsigned NumLPads = LPadList.size();
7993   if (Subtarget->isThumb2()) {
7994     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7995     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7996         .addFrameIndex(FI)
7997         .addImm(4)
7998         .addMemOperand(FIMMOLd)
7999         .add(predOps(ARMCC::AL));
8000 
8001     if (NumLPads < 256) {
8002       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8003           .addReg(NewVReg1)
8004           .addImm(LPadList.size())
8005           .add(predOps(ARMCC::AL));
8006     } else {
8007       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8008       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8009           .addImm(NumLPads & 0xFFFF)
8010           .add(predOps(ARMCC::AL));
8011 
8012       unsigned VReg2 = VReg1;
8013       if ((NumLPads & 0xFFFF0000) != 0) {
8014         VReg2 = MRI->createVirtualRegister(TRC);
8015         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8016             .addReg(VReg1)
8017             .addImm(NumLPads >> 16)
8018             .add(predOps(ARMCC::AL));
8019       }
8020 
8021       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8022           .addReg(NewVReg1)
8023           .addReg(VReg2)
8024           .add(predOps(ARMCC::AL));
8025     }
8026 
8027     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8028       .addMBB(TrapBB)
8029       .addImm(ARMCC::HI)
8030       .addReg(ARM::CPSR);
8031 
8032     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8033     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8034         .addJumpTableIndex(MJTI)
8035         .add(predOps(ARMCC::AL));
8036 
8037     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8038     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8039         .addReg(NewVReg3, RegState::Kill)
8040         .addReg(NewVReg1)
8041         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8042         .add(predOps(ARMCC::AL))
8043         .add(condCodeOp());
8044 
8045     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8046       .addReg(NewVReg4, RegState::Kill)
8047       .addReg(NewVReg1)
8048       .addJumpTableIndex(MJTI);
8049   } else if (Subtarget->isThumb()) {
8050     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8051     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8052         .addFrameIndex(FI)
8053         .addImm(1)
8054         .addMemOperand(FIMMOLd)
8055         .add(predOps(ARMCC::AL));
8056 
8057     if (NumLPads < 256) {
8058       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8059           .addReg(NewVReg1)
8060           .addImm(NumLPads)
8061           .add(predOps(ARMCC::AL));
8062     } else {
8063       MachineConstantPool *ConstantPool = MF->getConstantPool();
8064       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8065       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8066 
8067       // MachineConstantPool wants an explicit alignment.
8068       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8069       if (Align == 0)
8070         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8071       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8072 
8073       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8074       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8075           .addReg(VReg1, RegState::Define)
8076           .addConstantPoolIndex(Idx)
8077           .add(predOps(ARMCC::AL));
8078       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8079           .addReg(NewVReg1)
8080           .addReg(VReg1)
8081           .add(predOps(ARMCC::AL));
8082     }
8083 
8084     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8085       .addMBB(TrapBB)
8086       .addImm(ARMCC::HI)
8087       .addReg(ARM::CPSR);
8088 
8089     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8090     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8091         .addReg(ARM::CPSR, RegState::Define)
8092         .addReg(NewVReg1)
8093         .addImm(2)
8094         .add(predOps(ARMCC::AL));
8095 
8096     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8097     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8098         .addJumpTableIndex(MJTI)
8099         .add(predOps(ARMCC::AL));
8100 
8101     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8102     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8103         .addReg(ARM::CPSR, RegState::Define)
8104         .addReg(NewVReg2, RegState::Kill)
8105         .addReg(NewVReg3)
8106         .add(predOps(ARMCC::AL));
8107 
8108     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8109         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8110 
8111     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8112     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8113         .addReg(NewVReg4, RegState::Kill)
8114         .addImm(0)
8115         .addMemOperand(JTMMOLd)
8116         .add(predOps(ARMCC::AL));
8117 
8118     unsigned NewVReg6 = NewVReg5;
8119     if (IsPositionIndependent) {
8120       NewVReg6 = MRI->createVirtualRegister(TRC);
8121       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8122           .addReg(ARM::CPSR, RegState::Define)
8123           .addReg(NewVReg5, RegState::Kill)
8124           .addReg(NewVReg3)
8125           .add(predOps(ARMCC::AL));
8126     }
8127 
8128     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8129       .addReg(NewVReg6, RegState::Kill)
8130       .addJumpTableIndex(MJTI);
8131   } else {
8132     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8133     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8134         .addFrameIndex(FI)
8135         .addImm(4)
8136         .addMemOperand(FIMMOLd)
8137         .add(predOps(ARMCC::AL));
8138 
8139     if (NumLPads < 256) {
8140       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8141           .addReg(NewVReg1)
8142           .addImm(NumLPads)
8143           .add(predOps(ARMCC::AL));
8144     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8145       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8146       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8147           .addImm(NumLPads & 0xFFFF)
8148           .add(predOps(ARMCC::AL));
8149 
8150       unsigned VReg2 = VReg1;
8151       if ((NumLPads & 0xFFFF0000) != 0) {
8152         VReg2 = MRI->createVirtualRegister(TRC);
8153         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8154             .addReg(VReg1)
8155             .addImm(NumLPads >> 16)
8156             .add(predOps(ARMCC::AL));
8157       }
8158 
8159       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8160           .addReg(NewVReg1)
8161           .addReg(VReg2)
8162           .add(predOps(ARMCC::AL));
8163     } else {
8164       MachineConstantPool *ConstantPool = MF->getConstantPool();
8165       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8166       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8167 
8168       // MachineConstantPool wants an explicit alignment.
8169       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8170       if (Align == 0)
8171         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8172       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8173 
8174       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8175       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8176           .addReg(VReg1, RegState::Define)
8177           .addConstantPoolIndex(Idx)
8178           .addImm(0)
8179           .add(predOps(ARMCC::AL));
8180       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8181           .addReg(NewVReg1)
8182           .addReg(VReg1, RegState::Kill)
8183           .add(predOps(ARMCC::AL));
8184     }
8185 
8186     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8187       .addMBB(TrapBB)
8188       .addImm(ARMCC::HI)
8189       .addReg(ARM::CPSR);
8190 
8191     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8192     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8193         .addReg(NewVReg1)
8194         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8195         .add(predOps(ARMCC::AL))
8196         .add(condCodeOp());
8197     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8198     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8199         .addJumpTableIndex(MJTI)
8200         .add(predOps(ARMCC::AL));
8201 
8202     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8203         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8204     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8205     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8206         .addReg(NewVReg3, RegState::Kill)
8207         .addReg(NewVReg4)
8208         .addImm(0)
8209         .addMemOperand(JTMMOLd)
8210         .add(predOps(ARMCC::AL));
8211 
8212     if (IsPositionIndependent) {
8213       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8214         .addReg(NewVReg5, RegState::Kill)
8215         .addReg(NewVReg4)
8216         .addJumpTableIndex(MJTI);
8217     } else {
8218       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8219         .addReg(NewVReg5, RegState::Kill)
8220         .addJumpTableIndex(MJTI);
8221     }
8222   }
8223 
8224   // Add the jump table entries as successors to the MBB.
8225   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8226   for (std::vector<MachineBasicBlock*>::iterator
8227          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8228     MachineBasicBlock *CurMBB = *I;
8229     if (SeenMBBs.insert(CurMBB).second)
8230       DispContBB->addSuccessor(CurMBB);
8231   }
8232 
8233   // N.B. the order the invoke BBs are processed in doesn't matter here.
8234   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8235   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8236   for (MachineBasicBlock *BB : InvokeBBs) {
8237 
8238     // Remove the landing pad successor from the invoke block and replace it
8239     // with the new dispatch block.
8240     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8241                                                   BB->succ_end());
8242     while (!Successors.empty()) {
8243       MachineBasicBlock *SMBB = Successors.pop_back_val();
8244       if (SMBB->isEHPad()) {
8245         BB->removeSuccessor(SMBB);
8246         MBBLPads.push_back(SMBB);
8247       }
8248     }
8249 
8250     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8251     BB->normalizeSuccProbs();
8252 
8253     // Find the invoke call and mark all of the callee-saved registers as
8254     // 'implicit defined' so that they're spilled. This prevents code from
8255     // moving instructions to before the EH block, where they will never be
8256     // executed.
8257     for (MachineBasicBlock::reverse_iterator
8258            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8259       if (!II->isCall()) continue;
8260 
8261       DenseMap<unsigned, bool> DefRegs;
8262       for (MachineInstr::mop_iterator
8263              OI = II->operands_begin(), OE = II->operands_end();
8264            OI != OE; ++OI) {
8265         if (!OI->isReg()) continue;
8266         DefRegs[OI->getReg()] = true;
8267       }
8268 
8269       MachineInstrBuilder MIB(*MF, &*II);
8270 
8271       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8272         unsigned Reg = SavedRegs[i];
8273         if (Subtarget->isThumb2() &&
8274             !ARM::tGPRRegClass.contains(Reg) &&
8275             !ARM::hGPRRegClass.contains(Reg))
8276           continue;
8277         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8278           continue;
8279         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8280           continue;
8281         if (!DefRegs[Reg])
8282           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8283       }
8284 
8285       break;
8286     }
8287   }
8288 
8289   // Mark all former landing pads as non-landing pads. The dispatch is the only
8290   // landing pad now.
8291   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8292          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8293     (*I)->setIsEHPad(false);
8294 
8295   // The instruction is gone now.
8296   MI.eraseFromParent();
8297 }
8298 
8299 static
8300 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8301   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8302        E = MBB->succ_end(); I != E; ++I)
8303     if (*I != Succ)
8304       return *I;
8305   llvm_unreachable("Expecting a BB with two successors!");
8306 }
8307 
8308 /// Return the load opcode for a given load size. If load size >= 8,
8309 /// neon opcode will be returned.
8310 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8311   if (LdSize >= 8)
8312     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8313                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8314   if (IsThumb1)
8315     return LdSize == 4 ? ARM::tLDRi
8316                        : LdSize == 2 ? ARM::tLDRHi
8317                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8318   if (IsThumb2)
8319     return LdSize == 4 ? ARM::t2LDR_POST
8320                        : LdSize == 2 ? ARM::t2LDRH_POST
8321                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8322   return LdSize == 4 ? ARM::LDR_POST_IMM
8323                      : LdSize == 2 ? ARM::LDRH_POST
8324                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8325 }
8326 
8327 /// Return the store opcode for a given store size. If store size >= 8,
8328 /// neon opcode will be returned.
8329 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8330   if (StSize >= 8)
8331     return StSize == 16 ? ARM::VST1q32wb_fixed
8332                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8333   if (IsThumb1)
8334     return StSize == 4 ? ARM::tSTRi
8335                        : StSize == 2 ? ARM::tSTRHi
8336                                      : StSize == 1 ? ARM::tSTRBi : 0;
8337   if (IsThumb2)
8338     return StSize == 4 ? ARM::t2STR_POST
8339                        : StSize == 2 ? ARM::t2STRH_POST
8340                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8341   return StSize == 4 ? ARM::STR_POST_IMM
8342                      : StSize == 2 ? ARM::STRH_POST
8343                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8344 }
8345 
8346 /// Emit a post-increment load operation with given size. The instructions
8347 /// will be added to BB at Pos.
8348 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8349                        const TargetInstrInfo *TII, const DebugLoc &dl,
8350                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8351                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8352   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8353   assert(LdOpc != 0 && "Should have a load opcode");
8354   if (LdSize >= 8) {
8355     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8356         .addReg(AddrOut, RegState::Define)
8357         .addReg(AddrIn)
8358         .addImm(0)
8359         .add(predOps(ARMCC::AL));
8360   } else if (IsThumb1) {
8361     // load + update AddrIn
8362     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8363         .addReg(AddrIn)
8364         .addImm(0)
8365         .add(predOps(ARMCC::AL));
8366     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8367         .add(t1CondCodeOp())
8368         .addReg(AddrIn)
8369         .addImm(LdSize)
8370         .add(predOps(ARMCC::AL));
8371   } else if (IsThumb2) {
8372     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8373         .addReg(AddrOut, RegState::Define)
8374         .addReg(AddrIn)
8375         .addImm(LdSize)
8376         .add(predOps(ARMCC::AL));
8377   } else { // arm
8378     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8379         .addReg(AddrOut, RegState::Define)
8380         .addReg(AddrIn)
8381         .addReg(0)
8382         .addImm(LdSize)
8383         .add(predOps(ARMCC::AL));
8384   }
8385 }
8386 
8387 /// Emit a post-increment store operation with given size. The instructions
8388 /// will be added to BB at Pos.
8389 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8390                        const TargetInstrInfo *TII, const DebugLoc &dl,
8391                        unsigned StSize, unsigned Data, unsigned AddrIn,
8392                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8393   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8394   assert(StOpc != 0 && "Should have a store opcode");
8395   if (StSize >= 8) {
8396     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8397         .addReg(AddrIn)
8398         .addImm(0)
8399         .addReg(Data)
8400         .add(predOps(ARMCC::AL));
8401   } else if (IsThumb1) {
8402     // store + update AddrIn
8403     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8404         .addReg(Data)
8405         .addReg(AddrIn)
8406         .addImm(0)
8407         .add(predOps(ARMCC::AL));
8408     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8409         .add(t1CondCodeOp())
8410         .addReg(AddrIn)
8411         .addImm(StSize)
8412         .add(predOps(ARMCC::AL));
8413   } else if (IsThumb2) {
8414     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8415         .addReg(Data)
8416         .addReg(AddrIn)
8417         .addImm(StSize)
8418         .add(predOps(ARMCC::AL));
8419   } else { // arm
8420     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8421         .addReg(Data)
8422         .addReg(AddrIn)
8423         .addReg(0)
8424         .addImm(StSize)
8425         .add(predOps(ARMCC::AL));
8426   }
8427 }
8428 
8429 MachineBasicBlock *
8430 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8431                                    MachineBasicBlock *BB) const {
8432   // This pseudo instruction has 3 operands: dst, src, size
8433   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8434   // Otherwise, we will generate unrolled scalar copies.
8435   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8436   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8437   MachineFunction::iterator It = ++BB->getIterator();
8438 
8439   unsigned dest = MI.getOperand(0).getReg();
8440   unsigned src = MI.getOperand(1).getReg();
8441   unsigned SizeVal = MI.getOperand(2).getImm();
8442   unsigned Align = MI.getOperand(3).getImm();
8443   DebugLoc dl = MI.getDebugLoc();
8444 
8445   MachineFunction *MF = BB->getParent();
8446   MachineRegisterInfo &MRI = MF->getRegInfo();
8447   unsigned UnitSize = 0;
8448   const TargetRegisterClass *TRC = nullptr;
8449   const TargetRegisterClass *VecTRC = nullptr;
8450 
8451   bool IsThumb1 = Subtarget->isThumb1Only();
8452   bool IsThumb2 = Subtarget->isThumb2();
8453   bool IsThumb = Subtarget->isThumb();
8454 
8455   if (Align & 1) {
8456     UnitSize = 1;
8457   } else if (Align & 2) {
8458     UnitSize = 2;
8459   } else {
8460     // Check whether we can use NEON instructions.
8461     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8462         Subtarget->hasNEON()) {
8463       if ((Align % 16 == 0) && SizeVal >= 16)
8464         UnitSize = 16;
8465       else if ((Align % 8 == 0) && SizeVal >= 8)
8466         UnitSize = 8;
8467     }
8468     // Can't use NEON instructions.
8469     if (UnitSize == 0)
8470       UnitSize = 4;
8471   }
8472 
8473   // Select the correct opcode and register class for unit size load/store
8474   bool IsNeon = UnitSize >= 8;
8475   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8476   if (IsNeon)
8477     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8478                             : UnitSize == 8 ? &ARM::DPRRegClass
8479                                             : nullptr;
8480 
8481   unsigned BytesLeft = SizeVal % UnitSize;
8482   unsigned LoopSize = SizeVal - BytesLeft;
8483 
8484   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8485     // Use LDR and STR to copy.
8486     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8487     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8488     unsigned srcIn = src;
8489     unsigned destIn = dest;
8490     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8491       unsigned srcOut = MRI.createVirtualRegister(TRC);
8492       unsigned destOut = MRI.createVirtualRegister(TRC);
8493       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8494       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8495                  IsThumb1, IsThumb2);
8496       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8497                  IsThumb1, IsThumb2);
8498       srcIn = srcOut;
8499       destIn = destOut;
8500     }
8501 
8502     // Handle the leftover bytes with LDRB and STRB.
8503     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8504     // [destOut] = STRB_POST(scratch, destIn, 1)
8505     for (unsigned i = 0; i < BytesLeft; i++) {
8506       unsigned srcOut = MRI.createVirtualRegister(TRC);
8507       unsigned destOut = MRI.createVirtualRegister(TRC);
8508       unsigned scratch = MRI.createVirtualRegister(TRC);
8509       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8510                  IsThumb1, IsThumb2);
8511       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8512                  IsThumb1, IsThumb2);
8513       srcIn = srcOut;
8514       destIn = destOut;
8515     }
8516     MI.eraseFromParent(); // The instruction is gone now.
8517     return BB;
8518   }
8519 
8520   // Expand the pseudo op to a loop.
8521   // thisMBB:
8522   //   ...
8523   //   movw varEnd, # --> with thumb2
8524   //   movt varEnd, #
8525   //   ldrcp varEnd, idx --> without thumb2
8526   //   fallthrough --> loopMBB
8527   // loopMBB:
8528   //   PHI varPhi, varEnd, varLoop
8529   //   PHI srcPhi, src, srcLoop
8530   //   PHI destPhi, dst, destLoop
8531   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8532   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8533   //   subs varLoop, varPhi, #UnitSize
8534   //   bne loopMBB
8535   //   fallthrough --> exitMBB
8536   // exitMBB:
8537   //   epilogue to handle left-over bytes
8538   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8539   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8540   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8541   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8542   MF->insert(It, loopMBB);
8543   MF->insert(It, exitMBB);
8544 
8545   // Transfer the remainder of BB and its successor edges to exitMBB.
8546   exitMBB->splice(exitMBB->begin(), BB,
8547                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8548   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8549 
8550   // Load an immediate to varEnd.
8551   unsigned varEnd = MRI.createVirtualRegister(TRC);
8552   if (Subtarget->useMovt(*MF)) {
8553     unsigned Vtmp = varEnd;
8554     if ((LoopSize & 0xFFFF0000) != 0)
8555       Vtmp = MRI.createVirtualRegister(TRC);
8556     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8557         .addImm(LoopSize & 0xFFFF)
8558         .add(predOps(ARMCC::AL));
8559 
8560     if ((LoopSize & 0xFFFF0000) != 0)
8561       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8562           .addReg(Vtmp)
8563           .addImm(LoopSize >> 16)
8564           .add(predOps(ARMCC::AL));
8565   } else {
8566     MachineConstantPool *ConstantPool = MF->getConstantPool();
8567     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8568     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8569 
8570     // MachineConstantPool wants an explicit alignment.
8571     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8572     if (Align == 0)
8573       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8574     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8575 
8576     if (IsThumb)
8577       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8578           .addReg(varEnd, RegState::Define)
8579           .addConstantPoolIndex(Idx)
8580           .add(predOps(ARMCC::AL));
8581     else
8582       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8583           .addReg(varEnd, RegState::Define)
8584           .addConstantPoolIndex(Idx)
8585           .addImm(0)
8586           .add(predOps(ARMCC::AL));
8587   }
8588   BB->addSuccessor(loopMBB);
8589 
8590   // Generate the loop body:
8591   //   varPhi = PHI(varLoop, varEnd)
8592   //   srcPhi = PHI(srcLoop, src)
8593   //   destPhi = PHI(destLoop, dst)
8594   MachineBasicBlock *entryBB = BB;
8595   BB = loopMBB;
8596   unsigned varLoop = MRI.createVirtualRegister(TRC);
8597   unsigned varPhi = MRI.createVirtualRegister(TRC);
8598   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8599   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8600   unsigned destLoop = MRI.createVirtualRegister(TRC);
8601   unsigned destPhi = MRI.createVirtualRegister(TRC);
8602 
8603   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8604     .addReg(varLoop).addMBB(loopMBB)
8605     .addReg(varEnd).addMBB(entryBB);
8606   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8607     .addReg(srcLoop).addMBB(loopMBB)
8608     .addReg(src).addMBB(entryBB);
8609   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8610     .addReg(destLoop).addMBB(loopMBB)
8611     .addReg(dest).addMBB(entryBB);
8612 
8613   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8614   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8615   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8616   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8617              IsThumb1, IsThumb2);
8618   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8619              IsThumb1, IsThumb2);
8620 
8621   // Decrement loop variable by UnitSize.
8622   if (IsThumb1) {
8623     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8624         .add(t1CondCodeOp())
8625         .addReg(varPhi)
8626         .addImm(UnitSize)
8627         .add(predOps(ARMCC::AL));
8628   } else {
8629     MachineInstrBuilder MIB =
8630         BuildMI(*BB, BB->end(), dl,
8631                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8632     MIB.addReg(varPhi)
8633         .addImm(UnitSize)
8634         .add(predOps(ARMCC::AL))
8635         .add(condCodeOp());
8636     MIB->getOperand(5).setReg(ARM::CPSR);
8637     MIB->getOperand(5).setIsDef(true);
8638   }
8639   BuildMI(*BB, BB->end(), dl,
8640           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8641       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8642 
8643   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8644   BB->addSuccessor(loopMBB);
8645   BB->addSuccessor(exitMBB);
8646 
8647   // Add epilogue to handle BytesLeft.
8648   BB = exitMBB;
8649   auto StartOfExit = exitMBB->begin();
8650 
8651   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8652   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8653   unsigned srcIn = srcLoop;
8654   unsigned destIn = destLoop;
8655   for (unsigned i = 0; i < BytesLeft; i++) {
8656     unsigned srcOut = MRI.createVirtualRegister(TRC);
8657     unsigned destOut = MRI.createVirtualRegister(TRC);
8658     unsigned scratch = MRI.createVirtualRegister(TRC);
8659     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8660                IsThumb1, IsThumb2);
8661     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8662                IsThumb1, IsThumb2);
8663     srcIn = srcOut;
8664     destIn = destOut;
8665   }
8666 
8667   MI.eraseFromParent(); // The instruction is gone now.
8668   return BB;
8669 }
8670 
8671 MachineBasicBlock *
8672 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8673                                        MachineBasicBlock *MBB) const {
8674   const TargetMachine &TM = getTargetMachine();
8675   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8676   DebugLoc DL = MI.getDebugLoc();
8677 
8678   assert(Subtarget->isTargetWindows() &&
8679          "__chkstk is only supported on Windows");
8680   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8681 
8682   // __chkstk takes the number of words to allocate on the stack in R4, and
8683   // returns the stack adjustment in number of bytes in R4.  This will not
8684   // clober any other registers (other than the obvious lr).
8685   //
8686   // Although, technically, IP should be considered a register which may be
8687   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8688   // thumb-2 environment, so there is no interworking required.  As a result, we
8689   // do not expect a veneer to be emitted by the linker, clobbering IP.
8690   //
8691   // Each module receives its own copy of __chkstk, so no import thunk is
8692   // required, again, ensuring that IP is not clobbered.
8693   //
8694   // Finally, although some linkers may theoretically provide a trampoline for
8695   // out of range calls (which is quite common due to a 32M range limitation of
8696   // branches for Thumb), we can generate the long-call version via
8697   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8698   // IP.
8699 
8700   switch (TM.getCodeModel()) {
8701   case CodeModel::Small:
8702   case CodeModel::Medium:
8703   case CodeModel::Default:
8704   case CodeModel::Kernel:
8705     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8706         .add(predOps(ARMCC::AL))
8707         .addExternalSymbol("__chkstk")
8708         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8709         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8710         .addReg(ARM::R12,
8711                 RegState::Implicit | RegState::Define | RegState::Dead);
8712     break;
8713   case CodeModel::Large:
8714   case CodeModel::JITDefault: {
8715     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8716     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8717 
8718     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8719       .addExternalSymbol("__chkstk");
8720     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8721         .add(predOps(ARMCC::AL))
8722         .addReg(Reg, RegState::Kill)
8723         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8724         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8725         .addReg(ARM::R12,
8726                 RegState::Implicit | RegState::Define | RegState::Dead);
8727     break;
8728   }
8729   }
8730 
8731   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8732       .addReg(ARM::SP, RegState::Kill)
8733       .addReg(ARM::R4, RegState::Kill)
8734       .setMIFlags(MachineInstr::FrameSetup)
8735       .add(predOps(ARMCC::AL))
8736       .add(condCodeOp());
8737 
8738   MI.eraseFromParent();
8739   return MBB;
8740 }
8741 
8742 MachineBasicBlock *
8743 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8744                                        MachineBasicBlock *MBB) const {
8745   DebugLoc DL = MI.getDebugLoc();
8746   MachineFunction *MF = MBB->getParent();
8747   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8748 
8749   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8750   MF->insert(++MBB->getIterator(), ContBB);
8751   ContBB->splice(ContBB->begin(), MBB,
8752                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8753   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8754   MBB->addSuccessor(ContBB);
8755 
8756   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8757   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8758   MF->push_back(TrapBB);
8759   MBB->addSuccessor(TrapBB);
8760 
8761   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8762       .addReg(MI.getOperand(0).getReg())
8763       .addImm(0)
8764       .add(predOps(ARMCC::AL));
8765   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8766       .addMBB(TrapBB)
8767       .addImm(ARMCC::EQ)
8768       .addReg(ARM::CPSR);
8769 
8770   MI.eraseFromParent();
8771   return ContBB;
8772 }
8773 
8774 MachineBasicBlock *
8775 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8776                                                MachineBasicBlock *BB) const {
8777   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8778   DebugLoc dl = MI.getDebugLoc();
8779   bool isThumb2 = Subtarget->isThumb2();
8780   switch (MI.getOpcode()) {
8781   default: {
8782     MI.print(errs());
8783     llvm_unreachable("Unexpected instr type to insert");
8784   }
8785 
8786   // Thumb1 post-indexed loads are really just single-register LDMs.
8787   case ARM::tLDR_postidx: {
8788     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8789         .add(MI.getOperand(1))  // Rn_wb
8790         .add(MI.getOperand(2))  // Rn
8791         .add(MI.getOperand(3))  // PredImm
8792         .add(MI.getOperand(4))  // PredReg
8793         .add(MI.getOperand(0)); // Rt
8794     MI.eraseFromParent();
8795     return BB;
8796   }
8797 
8798   // The Thumb2 pre-indexed stores have the same MI operands, they just
8799   // define them differently in the .td files from the isel patterns, so
8800   // they need pseudos.
8801   case ARM::t2STR_preidx:
8802     MI.setDesc(TII->get(ARM::t2STR_PRE));
8803     return BB;
8804   case ARM::t2STRB_preidx:
8805     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8806     return BB;
8807   case ARM::t2STRH_preidx:
8808     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8809     return BB;
8810 
8811   case ARM::STRi_preidx:
8812   case ARM::STRBi_preidx: {
8813     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8814                                                          : ARM::STRB_PRE_IMM;
8815     // Decode the offset.
8816     unsigned Offset = MI.getOperand(4).getImm();
8817     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8818     Offset = ARM_AM::getAM2Offset(Offset);
8819     if (isSub)
8820       Offset = -Offset;
8821 
8822     MachineMemOperand *MMO = *MI.memoperands_begin();
8823     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8824         .add(MI.getOperand(0)) // Rn_wb
8825         .add(MI.getOperand(1)) // Rt
8826         .add(MI.getOperand(2)) // Rn
8827         .addImm(Offset)        // offset (skip GPR==zero_reg)
8828         .add(MI.getOperand(5)) // pred
8829         .add(MI.getOperand(6))
8830         .addMemOperand(MMO);
8831     MI.eraseFromParent();
8832     return BB;
8833   }
8834   case ARM::STRr_preidx:
8835   case ARM::STRBr_preidx:
8836   case ARM::STRH_preidx: {
8837     unsigned NewOpc;
8838     switch (MI.getOpcode()) {
8839     default: llvm_unreachable("unexpected opcode!");
8840     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8841     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8842     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8843     }
8844     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8845     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8846       MIB.add(MI.getOperand(i));
8847     MI.eraseFromParent();
8848     return BB;
8849   }
8850 
8851   case ARM::tMOVCCr_pseudo: {
8852     // To "insert" a SELECT_CC instruction, we actually have to insert the
8853     // diamond control-flow pattern.  The incoming instruction knows the
8854     // destination vreg to set, the condition code register to branch on, the
8855     // true/false values to select between, and a branch opcode to use.
8856     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8857     MachineFunction::iterator It = ++BB->getIterator();
8858 
8859     //  thisMBB:
8860     //  ...
8861     //   TrueVal = ...
8862     //   cmpTY ccX, r1, r2
8863     //   bCC copy1MBB
8864     //   fallthrough --> copy0MBB
8865     MachineBasicBlock *thisMBB  = BB;
8866     MachineFunction *F = BB->getParent();
8867     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8868     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8869     F->insert(It, copy0MBB);
8870     F->insert(It, sinkMBB);
8871 
8872     // Transfer the remainder of BB and its successor edges to sinkMBB.
8873     sinkMBB->splice(sinkMBB->begin(), BB,
8874                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8875     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8876 
8877     BB->addSuccessor(copy0MBB);
8878     BB->addSuccessor(sinkMBB);
8879 
8880     BuildMI(BB, dl, TII->get(ARM::tBcc))
8881         .addMBB(sinkMBB)
8882         .addImm(MI.getOperand(3).getImm())
8883         .addReg(MI.getOperand(4).getReg());
8884 
8885     //  copy0MBB:
8886     //   %FalseValue = ...
8887     //   # fallthrough to sinkMBB
8888     BB = copy0MBB;
8889 
8890     // Update machine-CFG edges
8891     BB->addSuccessor(sinkMBB);
8892 
8893     //  sinkMBB:
8894     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8895     //  ...
8896     BB = sinkMBB;
8897     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8898         .addReg(MI.getOperand(1).getReg())
8899         .addMBB(copy0MBB)
8900         .addReg(MI.getOperand(2).getReg())
8901         .addMBB(thisMBB);
8902 
8903     MI.eraseFromParent(); // The pseudo instruction is gone now.
8904     return BB;
8905   }
8906 
8907   case ARM::BCCi64:
8908   case ARM::BCCZi64: {
8909     // If there is an unconditional branch to the other successor, remove it.
8910     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8911 
8912     // Compare both parts that make up the double comparison separately for
8913     // equality.
8914     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8915 
8916     unsigned LHS1 = MI.getOperand(1).getReg();
8917     unsigned LHS2 = MI.getOperand(2).getReg();
8918     if (RHSisZero) {
8919       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8920           .addReg(LHS1)
8921           .addImm(0)
8922           .add(predOps(ARMCC::AL));
8923       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8924         .addReg(LHS2).addImm(0)
8925         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8926     } else {
8927       unsigned RHS1 = MI.getOperand(3).getReg();
8928       unsigned RHS2 = MI.getOperand(4).getReg();
8929       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8930           .addReg(LHS1)
8931           .addReg(RHS1)
8932           .add(predOps(ARMCC::AL));
8933       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8934         .addReg(LHS2).addReg(RHS2)
8935         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8936     }
8937 
8938     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8939     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8940     if (MI.getOperand(0).getImm() == ARMCC::NE)
8941       std::swap(destMBB, exitMBB);
8942 
8943     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8944       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8945     if (isThumb2)
8946       BuildMI(BB, dl, TII->get(ARM::t2B))
8947           .addMBB(exitMBB)
8948           .add(predOps(ARMCC::AL));
8949     else
8950       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8951 
8952     MI.eraseFromParent(); // The pseudo instruction is gone now.
8953     return BB;
8954   }
8955 
8956   case ARM::Int_eh_sjlj_setjmp:
8957   case ARM::Int_eh_sjlj_setjmp_nofp:
8958   case ARM::tInt_eh_sjlj_setjmp:
8959   case ARM::t2Int_eh_sjlj_setjmp:
8960   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8961     return BB;
8962 
8963   case ARM::Int_eh_sjlj_setup_dispatch:
8964     EmitSjLjDispatchBlock(MI, BB);
8965     return BB;
8966 
8967   case ARM::ABS:
8968   case ARM::t2ABS: {
8969     // To insert an ABS instruction, we have to insert the
8970     // diamond control-flow pattern.  The incoming instruction knows the
8971     // source vreg to test against 0, the destination vreg to set,
8972     // the condition code register to branch on, the
8973     // true/false values to select between, and a branch opcode to use.
8974     // It transforms
8975     //     V1 = ABS V0
8976     // into
8977     //     V2 = MOVS V0
8978     //     BCC                      (branch to SinkBB if V0 >= 0)
8979     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8980     //     SinkBB: V1 = PHI(V2, V3)
8981     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8982     MachineFunction::iterator BBI = ++BB->getIterator();
8983     MachineFunction *Fn = BB->getParent();
8984     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8985     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8986     Fn->insert(BBI, RSBBB);
8987     Fn->insert(BBI, SinkBB);
8988 
8989     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8990     unsigned int ABSDstReg = MI.getOperand(0).getReg();
8991     bool ABSSrcKIll = MI.getOperand(1).isKill();
8992     bool isThumb2 = Subtarget->isThumb2();
8993     MachineRegisterInfo &MRI = Fn->getRegInfo();
8994     // In Thumb mode S must not be specified if source register is the SP or
8995     // PC and if destination register is the SP, so restrict register class
8996     unsigned NewRsbDstReg =
8997       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8998 
8999     // Transfer the remainder of BB and its successor edges to sinkMBB.
9000     SinkBB->splice(SinkBB->begin(), BB,
9001                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9002     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9003 
9004     BB->addSuccessor(RSBBB);
9005     BB->addSuccessor(SinkBB);
9006 
9007     // fall through to SinkMBB
9008     RSBBB->addSuccessor(SinkBB);
9009 
9010     // insert a cmp at the end of BB
9011     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9012         .addReg(ABSSrcReg)
9013         .addImm(0)
9014         .add(predOps(ARMCC::AL));
9015 
9016     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9017     BuildMI(BB, dl,
9018       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9019       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9020 
9021     // insert rsbri in RSBBB
9022     // Note: BCC and rsbri will be converted into predicated rsbmi
9023     // by if-conversion pass
9024     BuildMI(*RSBBB, RSBBB->begin(), dl,
9025             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9026         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9027         .addImm(0)
9028         .add(predOps(ARMCC::AL))
9029         .add(condCodeOp());
9030 
9031     // insert PHI in SinkBB,
9032     // reuse ABSDstReg to not change uses of ABS instruction
9033     BuildMI(*SinkBB, SinkBB->begin(), dl,
9034       TII->get(ARM::PHI), ABSDstReg)
9035       .addReg(NewRsbDstReg).addMBB(RSBBB)
9036       .addReg(ABSSrcReg).addMBB(BB);
9037 
9038     // remove ABS instruction
9039     MI.eraseFromParent();
9040 
9041     // return last added BB
9042     return SinkBB;
9043   }
9044   case ARM::COPY_STRUCT_BYVAL_I32:
9045     ++NumLoopByVals;
9046     return EmitStructByval(MI, BB);
9047   case ARM::WIN__CHKSTK:
9048     return EmitLowered__chkstk(MI, BB);
9049   case ARM::WIN__DBZCHK:
9050     return EmitLowered__dbzchk(MI, BB);
9051   }
9052 }
9053 
9054 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9055 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9056 /// instead of as a custom inserter because we need the use list from the SDNode.
9057 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9058                                     MachineInstr &MI, const SDNode *Node) {
9059   bool isThumb1 = Subtarget->isThumb1Only();
9060 
9061   DebugLoc DL = MI.getDebugLoc();
9062   MachineFunction *MF = MI.getParent()->getParent();
9063   MachineRegisterInfo &MRI = MF->getRegInfo();
9064   MachineInstrBuilder MIB(*MF, MI);
9065 
9066   // If the new dst/src is unused mark it as dead.
9067   if (!Node->hasAnyUseOfValue(0)) {
9068     MI.getOperand(0).setIsDead(true);
9069   }
9070   if (!Node->hasAnyUseOfValue(1)) {
9071     MI.getOperand(1).setIsDead(true);
9072   }
9073 
9074   // The MEMCPY both defines and kills the scratch registers.
9075   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9076     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9077                                                          : &ARM::GPRRegClass);
9078     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9079   }
9080 }
9081 
9082 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9083                                                       SDNode *Node) const {
9084   if (MI.getOpcode() == ARM::MEMCPY) {
9085     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9086     return;
9087   }
9088 
9089   const MCInstrDesc *MCID = &MI.getDesc();
9090   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9091   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9092   // operand is still set to noreg. If needed, set the optional operand's
9093   // register to CPSR, and remove the redundant implicit def.
9094   //
9095   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9096 
9097   // Rename pseudo opcodes.
9098   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9099   if (NewOpc) {
9100     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9101     MCID = &TII->get(NewOpc);
9102 
9103     assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 &&
9104            "converted opcode should be the same except for cc_out");
9105 
9106     MI.setDesc(*MCID);
9107 
9108     // Add the optional cc_out operand
9109     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9110   }
9111   unsigned ccOutIdx = MCID->getNumOperands() - 1;
9112 
9113   // Any ARM instruction that sets the 's' bit should specify an optional
9114   // "cc_out" operand in the last operand position.
9115   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9116     assert(!NewOpc && "Optional cc_out operand required");
9117     return;
9118   }
9119   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9120   // since we already have an optional CPSR def.
9121   bool definesCPSR = false;
9122   bool deadCPSR = false;
9123   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9124        ++i) {
9125     const MachineOperand &MO = MI.getOperand(i);
9126     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9127       definesCPSR = true;
9128       if (MO.isDead())
9129         deadCPSR = true;
9130       MI.RemoveOperand(i);
9131       break;
9132     }
9133   }
9134   if (!definesCPSR) {
9135     assert(!NewOpc && "Optional cc_out operand required");
9136     return;
9137   }
9138   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9139   if (deadCPSR) {
9140     assert(!MI.getOperand(ccOutIdx).getReg() &&
9141            "expect uninitialized optional cc_out operand");
9142     return;
9143   }
9144 
9145   // If this instruction was defined with an optional CPSR def and its dag node
9146   // had a live implicit CPSR def, then activate the optional CPSR def.
9147   MachineOperand &MO = MI.getOperand(ccOutIdx);
9148   MO.setReg(ARM::CPSR);
9149   MO.setIsDef(true);
9150 }
9151 
9152 //===----------------------------------------------------------------------===//
9153 //                           ARM Optimization Hooks
9154 //===----------------------------------------------------------------------===//
9155 
9156 // Helper function that checks if N is a null or all ones constant.
9157 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9158   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9159 }
9160 
9161 // Return true if N is conditionally 0 or all ones.
9162 // Detects these expressions where cc is an i1 value:
9163 //
9164 //   (select cc 0, y)   [AllOnes=0]
9165 //   (select cc y, 0)   [AllOnes=0]
9166 //   (zext cc)          [AllOnes=0]
9167 //   (sext cc)          [AllOnes=0/1]
9168 //   (select cc -1, y)  [AllOnes=1]
9169 //   (select cc y, -1)  [AllOnes=1]
9170 //
9171 // Invert is set when N is the null/all ones constant when CC is false.
9172 // OtherOp is set to the alternative value of N.
9173 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9174                                        SDValue &CC, bool &Invert,
9175                                        SDValue &OtherOp,
9176                                        SelectionDAG &DAG) {
9177   switch (N->getOpcode()) {
9178   default: return false;
9179   case ISD::SELECT: {
9180     CC = N->getOperand(0);
9181     SDValue N1 = N->getOperand(1);
9182     SDValue N2 = N->getOperand(2);
9183     if (isZeroOrAllOnes(N1, AllOnes)) {
9184       Invert = false;
9185       OtherOp = N2;
9186       return true;
9187     }
9188     if (isZeroOrAllOnes(N2, AllOnes)) {
9189       Invert = true;
9190       OtherOp = N1;
9191       return true;
9192     }
9193     return false;
9194   }
9195   case ISD::ZERO_EXTEND:
9196     // (zext cc) can never be the all ones value.
9197     if (AllOnes)
9198       return false;
9199     LLVM_FALLTHROUGH;
9200   case ISD::SIGN_EXTEND: {
9201     SDLoc dl(N);
9202     EVT VT = N->getValueType(0);
9203     CC = N->getOperand(0);
9204     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9205       return false;
9206     Invert = !AllOnes;
9207     if (AllOnes)
9208       // When looking for an AllOnes constant, N is an sext, and the 'other'
9209       // value is 0.
9210       OtherOp = DAG.getConstant(0, dl, VT);
9211     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9212       // When looking for a 0 constant, N can be zext or sext.
9213       OtherOp = DAG.getConstant(1, dl, VT);
9214     else
9215       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9216                                 VT);
9217     return true;
9218   }
9219   }
9220 }
9221 
9222 // Combine a constant select operand into its use:
9223 //
9224 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9225 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9226 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9227 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9228 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9229 //
9230 // The transform is rejected if the select doesn't have a constant operand that
9231 // is null, or all ones when AllOnes is set.
9232 //
9233 // Also recognize sext/zext from i1:
9234 //
9235 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9236 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9237 //
9238 // These transformations eventually create predicated instructions.
9239 //
9240 // @param N       The node to transform.
9241 // @param Slct    The N operand that is a select.
9242 // @param OtherOp The other N operand (x above).
9243 // @param DCI     Context.
9244 // @param AllOnes Require the select constant to be all ones instead of null.
9245 // @returns The new node, or SDValue() on failure.
9246 static
9247 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9248                             TargetLowering::DAGCombinerInfo &DCI,
9249                             bool AllOnes = false) {
9250   SelectionDAG &DAG = DCI.DAG;
9251   EVT VT = N->getValueType(0);
9252   SDValue NonConstantVal;
9253   SDValue CCOp;
9254   bool SwapSelectOps;
9255   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9256                                   NonConstantVal, DAG))
9257     return SDValue();
9258 
9259   // Slct is now know to be the desired identity constant when CC is true.
9260   SDValue TrueVal = OtherOp;
9261   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9262                                  OtherOp, NonConstantVal);
9263   // Unless SwapSelectOps says CC should be false.
9264   if (SwapSelectOps)
9265     std::swap(TrueVal, FalseVal);
9266 
9267   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9268                      CCOp, TrueVal, FalseVal);
9269 }
9270 
9271 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9272 static
9273 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9274                                        TargetLowering::DAGCombinerInfo &DCI) {
9275   SDValue N0 = N->getOperand(0);
9276   SDValue N1 = N->getOperand(1);
9277   if (N0.getNode()->hasOneUse())
9278     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9279       return Result;
9280   if (N1.getNode()->hasOneUse())
9281     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9282       return Result;
9283   return SDValue();
9284 }
9285 
9286 static bool IsVUZPShuffleNode(SDNode *N) {
9287   // VUZP shuffle node.
9288   if (N->getOpcode() == ARMISD::VUZP)
9289     return true;
9290 
9291   // "VUZP" on i32 is an alias for VTRN.
9292   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9293     return true;
9294 
9295   return false;
9296 }
9297 
9298 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9299                                  TargetLowering::DAGCombinerInfo &DCI,
9300                                  const ARMSubtarget *Subtarget) {
9301   // Look for ADD(VUZP.0, VUZP.1).
9302   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9303       N0 == N1)
9304    return SDValue();
9305 
9306   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9307   if (!N->getValueType(0).is64BitVector())
9308     return SDValue();
9309 
9310   // Generate vpadd.
9311   SelectionDAG &DAG = DCI.DAG;
9312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9313   SDLoc dl(N);
9314   SDNode *Unzip = N0.getNode();
9315   EVT VT = N->getValueType(0);
9316 
9317   SmallVector<SDValue, 8> Ops;
9318   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9319                                 TLI.getPointerTy(DAG.getDataLayout())));
9320   Ops.push_back(Unzip->getOperand(0));
9321   Ops.push_back(Unzip->getOperand(1));
9322 
9323   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9324 }
9325 
9326 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9327                                       TargetLowering::DAGCombinerInfo &DCI,
9328                                       const ARMSubtarget *Subtarget) {
9329   // Check for two extended operands.
9330   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9331         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9332       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9333         N1.getOpcode() == ISD::ZERO_EXTEND))
9334     return SDValue();
9335 
9336   SDValue N00 = N0.getOperand(0);
9337   SDValue N10 = N1.getOperand(0);
9338 
9339   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9340   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9341       N00 == N10)
9342     return SDValue();
9343 
9344   // We only recognize Q register paddl here; this can't be reached until
9345   // after type legalization.
9346   if (!N00.getValueType().is64BitVector() ||
9347       !N0.getValueType().is128BitVector())
9348     return SDValue();
9349 
9350   // Generate vpaddl.
9351   SelectionDAG &DAG = DCI.DAG;
9352   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9353   SDLoc dl(N);
9354   EVT VT = N->getValueType(0);
9355 
9356   SmallVector<SDValue, 8> Ops;
9357   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9358   unsigned Opcode;
9359   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9360     Opcode = Intrinsic::arm_neon_vpaddls;
9361   else
9362     Opcode = Intrinsic::arm_neon_vpaddlu;
9363   Ops.push_back(DAG.getConstant(Opcode, dl,
9364                                 TLI.getPointerTy(DAG.getDataLayout())));
9365   EVT ElemTy = N00.getValueType().getVectorElementType();
9366   unsigned NumElts = VT.getVectorNumElements();
9367   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9368   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9369                                N00.getOperand(0), N00.getOperand(1));
9370   Ops.push_back(Concat);
9371 
9372   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9373 }
9374 
9375 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9376 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9377 // much easier to match.
9378 static SDValue
9379 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9380                                TargetLowering::DAGCombinerInfo &DCI,
9381                                const ARMSubtarget *Subtarget) {
9382   // Only perform optimization if after legalize, and if NEON is available. We
9383   // also expected both operands to be BUILD_VECTORs.
9384   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9385       || N0.getOpcode() != ISD::BUILD_VECTOR
9386       || N1.getOpcode() != ISD::BUILD_VECTOR)
9387     return SDValue();
9388 
9389   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9390   EVT VT = N->getValueType(0);
9391   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9392     return SDValue();
9393 
9394   // Check that the vector operands are of the right form.
9395   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9396   // operands, where N is the size of the formed vector.
9397   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9398   // index such that we have a pair wise add pattern.
9399 
9400   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9401   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9402     return SDValue();
9403   SDValue Vec = N0->getOperand(0)->getOperand(0);
9404   SDNode *V = Vec.getNode();
9405   unsigned nextIndex = 0;
9406 
9407   // For each operands to the ADD which are BUILD_VECTORs,
9408   // check to see if each of their operands are an EXTRACT_VECTOR with
9409   // the same vector and appropriate index.
9410   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9411     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9412         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9413 
9414       SDValue ExtVec0 = N0->getOperand(i);
9415       SDValue ExtVec1 = N1->getOperand(i);
9416 
9417       // First operand is the vector, verify its the same.
9418       if (V != ExtVec0->getOperand(0).getNode() ||
9419           V != ExtVec1->getOperand(0).getNode())
9420         return SDValue();
9421 
9422       // Second is the constant, verify its correct.
9423       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9424       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9425 
9426       // For the constant, we want to see all the even or all the odd.
9427       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9428           || C1->getZExtValue() != nextIndex+1)
9429         return SDValue();
9430 
9431       // Increment index.
9432       nextIndex+=2;
9433     } else
9434       return SDValue();
9435   }
9436 
9437   // Don't generate vpaddl+vmovn; we'll match it to vpadd later.
9438   if (Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9439     return SDValue();
9440 
9441   // Create VPADDL node.
9442   SelectionDAG &DAG = DCI.DAG;
9443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9444 
9445   SDLoc dl(N);
9446 
9447   // Build operand list.
9448   SmallVector<SDValue, 8> Ops;
9449   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9450                                 TLI.getPointerTy(DAG.getDataLayout())));
9451 
9452   // Input is the vector.
9453   Ops.push_back(Vec);
9454 
9455   // Get widened type and narrowed type.
9456   MVT widenType;
9457   unsigned numElem = VT.getVectorNumElements();
9458 
9459   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9460   switch (inputLaneType.getSimpleVT().SimpleTy) {
9461     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9462     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9463     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9464     default:
9465       llvm_unreachable("Invalid vector element type for padd optimization.");
9466   }
9467 
9468   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9469   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9470   return DAG.getNode(ExtOp, dl, VT, tmp);
9471 }
9472 
9473 static SDValue findMUL_LOHI(SDValue V) {
9474   if (V->getOpcode() == ISD::UMUL_LOHI ||
9475       V->getOpcode() == ISD::SMUL_LOHI)
9476     return V;
9477   return SDValue();
9478 }
9479 
9480 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9481                                         TargetLowering::DAGCombinerInfo &DCI,
9482                                         const ARMSubtarget *Subtarget) {
9483 
9484   if (Subtarget->isThumb()) {
9485     if (!Subtarget->hasDSP())
9486       return SDValue();
9487   } else if (!Subtarget->hasV5TEOps())
9488     return SDValue();
9489 
9490   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9491   // accumulates the product into a 64-bit value. The 16-bit values will
9492   // be sign extended somehow or SRA'd into 32-bit values
9493   // (addc (adde (mul 16bit, 16bit), lo), hi)
9494   SDValue Mul = AddcNode->getOperand(0);
9495   SDValue Hi = AddcNode->getOperand(1);
9496   if (Mul.getOpcode() != ISD::MUL) {
9497     Hi = AddcNode->getOperand(0);
9498     Mul = AddcNode->getOperand(1);
9499     if (Mul.getOpcode() != ISD::MUL)
9500       return SDValue();
9501   }
9502 
9503   SDValue SRA = AddeNode->getOperand(0);
9504   SDValue Lo = AddeNode->getOperand(1);
9505   if (SRA.getOpcode() != ISD::SRA) {
9506     SRA = AddeNode->getOperand(1);
9507     Lo = AddeNode->getOperand(0);
9508     if (SRA.getOpcode() != ISD::SRA)
9509       return SDValue();
9510   }
9511   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9512     if (Const->getZExtValue() != 31)
9513       return SDValue();
9514   } else
9515     return SDValue();
9516 
9517   if (SRA.getOperand(0) != Mul)
9518     return SDValue();
9519 
9520   SelectionDAG &DAG = DCI.DAG;
9521   SDLoc dl(AddcNode);
9522   unsigned Opcode = 0;
9523   SDValue Op0;
9524   SDValue Op1;
9525 
9526   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9527     Opcode = ARMISD::SMLALBB;
9528     Op0 = Mul.getOperand(0);
9529     Op1 = Mul.getOperand(1);
9530   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9531     Opcode = ARMISD::SMLALBT;
9532     Op0 = Mul.getOperand(0);
9533     Op1 = Mul.getOperand(1).getOperand(0);
9534   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9535     Opcode = ARMISD::SMLALTB;
9536     Op0 = Mul.getOperand(0).getOperand(0);
9537     Op1 = Mul.getOperand(1);
9538   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9539     Opcode = ARMISD::SMLALTT;
9540     Op0 = Mul->getOperand(0).getOperand(0);
9541     Op1 = Mul->getOperand(1).getOperand(0);
9542   }
9543 
9544   if (!Op0 || !Op1)
9545     return SDValue();
9546 
9547   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9548                               Op0, Op1, Lo, Hi);
9549   // Replace the ADDs' nodes uses by the MLA node's values.
9550   SDValue HiMLALResult(SMLAL.getNode(), 1);
9551   SDValue LoMLALResult(SMLAL.getNode(), 0);
9552 
9553   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9554   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9555 
9556   // Return original node to notify the driver to stop replacing.
9557   SDValue resNode(AddcNode, 0);
9558   return resNode;
9559 }
9560 
9561 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9562                                      TargetLowering::DAGCombinerInfo &DCI,
9563                                      const ARMSubtarget *Subtarget) {
9564   // Look for multiply add opportunities.
9565   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9566   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9567   // a glue link from the first add to the second add.
9568   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9569   // a S/UMLAL instruction.
9570   //                  UMUL_LOHI
9571   //                 / :lo    \ :hi
9572   //                /          \          [no multiline comment]
9573   //    loAdd ->  ADDE         |
9574   //                 \ :glue  /
9575   //                  \      /
9576   //                    ADDC   <- hiAdd
9577   //
9578   assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9579 
9580   assert(AddeNode->getNumOperands() == 3 &&
9581          AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9582          "ADDE node has the wrong inputs");
9583 
9584   // Check that we have a glued ADDC node.
9585   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9586   if (AddcNode->getOpcode() != ARMISD::ADDC)
9587     return SDValue();
9588 
9589   SDValue AddcOp0 = AddcNode->getOperand(0);
9590   SDValue AddcOp1 = AddcNode->getOperand(1);
9591 
9592   // Check if the two operands are from the same mul_lohi node.
9593   if (AddcOp0.getNode() == AddcOp1.getNode())
9594     return SDValue();
9595 
9596   assert(AddcNode->getNumValues() == 2 &&
9597          AddcNode->getValueType(0) == MVT::i32 &&
9598          "Expect ADDC with two result values. First: i32");
9599 
9600   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9601   // maybe a SMLAL which multiplies two 16-bit values.
9602   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9603       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9604       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9605       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9606     return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9607 
9608   // Check for the triangle shape.
9609   SDValue AddeOp0 = AddeNode->getOperand(0);
9610   SDValue AddeOp1 = AddeNode->getOperand(1);
9611 
9612   // Make sure that the ADDE operands are not coming from the same node.
9613   if (AddeOp0.getNode() == AddeOp1.getNode())
9614     return SDValue();
9615 
9616   // Find the MUL_LOHI node walking up ADDE's operands.
9617   bool IsLeftOperandMUL = false;
9618   SDValue MULOp = findMUL_LOHI(AddeOp0);
9619   if (MULOp == SDValue())
9620    MULOp = findMUL_LOHI(AddeOp1);
9621   else
9622     IsLeftOperandMUL = true;
9623   if (MULOp == SDValue())
9624     return SDValue();
9625 
9626   // Figure out the right opcode.
9627   unsigned Opc = MULOp->getOpcode();
9628   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9629 
9630   // Figure out the high and low input values to the MLAL node.
9631   SDValue* HiAdd = nullptr;
9632   SDValue* LoMul = nullptr;
9633   SDValue* LowAdd = nullptr;
9634 
9635   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9636   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9637     return SDValue();
9638 
9639   if (IsLeftOperandMUL)
9640     HiAdd = &AddeOp1;
9641   else
9642     HiAdd = &AddeOp0;
9643 
9644 
9645   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9646   // whose low result is fed to the ADDC we are checking.
9647 
9648   if (AddcOp0 == MULOp.getValue(0)) {
9649     LoMul = &AddcOp0;
9650     LowAdd = &AddcOp1;
9651   }
9652   if (AddcOp1 == MULOp.getValue(0)) {
9653     LoMul = &AddcOp1;
9654     LowAdd = &AddcOp0;
9655   }
9656 
9657   if (!LoMul)
9658     return SDValue();
9659 
9660   // Create the merged node.
9661   SelectionDAG &DAG = DCI.DAG;
9662 
9663   // Build operand list.
9664   SmallVector<SDValue, 8> Ops;
9665   Ops.push_back(LoMul->getOperand(0));
9666   Ops.push_back(LoMul->getOperand(1));
9667   Ops.push_back(*LowAdd);
9668   Ops.push_back(*HiAdd);
9669 
9670   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9671                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9672 
9673   // Replace the ADDs' nodes uses by the MLA node's values.
9674   SDValue HiMLALResult(MLALNode.getNode(), 1);
9675   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9676 
9677   SDValue LoMLALResult(MLALNode.getNode(), 0);
9678   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9679 
9680   // Return original node to notify the driver to stop replacing.
9681   return SDValue(AddeNode, 0);
9682 }
9683 
9684 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9685                                       TargetLowering::DAGCombinerInfo &DCI,
9686                                       const ARMSubtarget *Subtarget) {
9687   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9688   // While trying to combine for the other MLAL nodes, first search for the
9689   // chance to use UMAAL. Check if Addc uses a node which has already
9690   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9691   // as the addend, and it's handled in PerformUMLALCombine.
9692 
9693   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9694     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9695 
9696   // Check that we have a glued ADDC node.
9697   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9698   if (AddcNode->getOpcode() != ARMISD::ADDC)
9699     return SDValue();
9700 
9701   // Find the converted UMAAL or quit if it doesn't exist.
9702   SDNode *UmlalNode = nullptr;
9703   SDValue AddHi;
9704   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9705     UmlalNode = AddcNode->getOperand(0).getNode();
9706     AddHi = AddcNode->getOperand(1);
9707   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9708     UmlalNode = AddcNode->getOperand(1).getNode();
9709     AddHi = AddcNode->getOperand(0);
9710   } else {
9711     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9712   }
9713 
9714   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9715   // the ADDC as well as Zero.
9716   if (!isNullConstant(UmlalNode->getOperand(3)))
9717     return SDValue();
9718 
9719   if ((isNullConstant(AddeNode->getOperand(0)) &&
9720        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9721       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9722        isNullConstant(AddeNode->getOperand(1)))) {
9723 
9724     SelectionDAG &DAG = DCI.DAG;
9725     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9726                       UmlalNode->getOperand(2), AddHi };
9727     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9728                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9729 
9730     // Replace the ADDs' nodes uses by the UMAAL node's values.
9731     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9732     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9733 
9734     // Return original node to notify the driver to stop replacing.
9735     return SDValue(AddeNode, 0);
9736   }
9737   return SDValue();
9738 }
9739 
9740 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9741                                    const ARMSubtarget *Subtarget) {
9742   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9743     return SDValue();
9744 
9745   // Check that we have a pair of ADDC and ADDE as operands.
9746   // Both addends of the ADDE must be zero.
9747   SDNode* AddcNode = N->getOperand(2).getNode();
9748   SDNode* AddeNode = N->getOperand(3).getNode();
9749   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9750       (AddeNode->getOpcode() == ARMISD::ADDE) &&
9751       isNullConstant(AddeNode->getOperand(0)) &&
9752       isNullConstant(AddeNode->getOperand(1)) &&
9753       (AddeNode->getOperand(2).getNode() == AddcNode))
9754     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9755                        DAG.getVTList(MVT::i32, MVT::i32),
9756                        {N->getOperand(0), N->getOperand(1),
9757                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
9758   else
9759     return SDValue();
9760 }
9761 
9762 /// PerformADDECombine - Target-specific dag combine transform from
9763 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
9764 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9765 static SDValue PerformADDECombine(SDNode *N,
9766                                   TargetLowering::DAGCombinerInfo &DCI,
9767                                   const ARMSubtarget *Subtarget) {
9768   // Only ARM and Thumb2 support UMLAL/SMLAL.
9769   if (Subtarget->isThumb1Only())
9770     return SDValue();
9771 
9772   // Only perform the checks after legalize when the pattern is available.
9773   if (DCI.isBeforeLegalize()) return SDValue();
9774 
9775   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9776 }
9777 
9778 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9779 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9780 /// called with the default operands, and if that fails, with commuted
9781 /// operands.
9782 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9783                                           TargetLowering::DAGCombinerInfo &DCI,
9784                                           const ARMSubtarget *Subtarget){
9785   // Attempt to create vpadd for this add.
9786   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
9787     return Result;
9788 
9789   // Attempt to create vpaddl for this add.
9790   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
9791     return Result;
9792   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
9793                                                       Subtarget))
9794     return Result;
9795 
9796   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9797   if (N0.getNode()->hasOneUse())
9798     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9799       return Result;
9800   return SDValue();
9801 }
9802 
9803 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9804 ///
9805 static SDValue PerformADDCombine(SDNode *N,
9806                                  TargetLowering::DAGCombinerInfo &DCI,
9807                                  const ARMSubtarget *Subtarget) {
9808   SDValue N0 = N->getOperand(0);
9809   SDValue N1 = N->getOperand(1);
9810 
9811   // First try with the default operand order.
9812   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9813     return Result;
9814 
9815   // If that didn't work, try again with the operands commuted.
9816   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9817 }
9818 
9819 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9820 ///
9821 static SDValue PerformSUBCombine(SDNode *N,
9822                                  TargetLowering::DAGCombinerInfo &DCI) {
9823   SDValue N0 = N->getOperand(0);
9824   SDValue N1 = N->getOperand(1);
9825 
9826   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9827   if (N1.getNode()->hasOneUse())
9828     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9829       return Result;
9830 
9831   return SDValue();
9832 }
9833 
9834 /// PerformVMULCombine
9835 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9836 /// special multiplier accumulator forwarding.
9837 ///   vmul d3, d0, d2
9838 ///   vmla d3, d1, d2
9839 /// is faster than
9840 ///   vadd d3, d0, d1
9841 ///   vmul d3, d3, d2
9842 //  However, for (A + B) * (A + B),
9843 //    vadd d2, d0, d1
9844 //    vmul d3, d0, d2
9845 //    vmla d3, d1, d2
9846 //  is slower than
9847 //    vadd d2, d0, d1
9848 //    vmul d3, d2, d2
9849 static SDValue PerformVMULCombine(SDNode *N,
9850                                   TargetLowering::DAGCombinerInfo &DCI,
9851                                   const ARMSubtarget *Subtarget) {
9852   if (!Subtarget->hasVMLxForwarding())
9853     return SDValue();
9854 
9855   SelectionDAG &DAG = DCI.DAG;
9856   SDValue N0 = N->getOperand(0);
9857   SDValue N1 = N->getOperand(1);
9858   unsigned Opcode = N0.getOpcode();
9859   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9860       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9861     Opcode = N1.getOpcode();
9862     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9863         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9864       return SDValue();
9865     std::swap(N0, N1);
9866   }
9867 
9868   if (N0 == N1)
9869     return SDValue();
9870 
9871   EVT VT = N->getValueType(0);
9872   SDLoc DL(N);
9873   SDValue N00 = N0->getOperand(0);
9874   SDValue N01 = N0->getOperand(1);
9875   return DAG.getNode(Opcode, DL, VT,
9876                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9877                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9878 }
9879 
9880 static SDValue PerformMULCombine(SDNode *N,
9881                                  TargetLowering::DAGCombinerInfo &DCI,
9882                                  const ARMSubtarget *Subtarget) {
9883   SelectionDAG &DAG = DCI.DAG;
9884 
9885   if (Subtarget->isThumb1Only())
9886     return SDValue();
9887 
9888   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9889     return SDValue();
9890 
9891   EVT VT = N->getValueType(0);
9892   if (VT.is64BitVector() || VT.is128BitVector())
9893     return PerformVMULCombine(N, DCI, Subtarget);
9894   if (VT != MVT::i32)
9895     return SDValue();
9896 
9897   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9898   if (!C)
9899     return SDValue();
9900 
9901   int64_t MulAmt = C->getSExtValue();
9902   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9903 
9904   ShiftAmt = ShiftAmt & (32 - 1);
9905   SDValue V = N->getOperand(0);
9906   SDLoc DL(N);
9907 
9908   SDValue Res;
9909   MulAmt >>= ShiftAmt;
9910 
9911   if (MulAmt >= 0) {
9912     if (isPowerOf2_32(MulAmt - 1)) {
9913       // (mul x, 2^N + 1) => (add (shl x, N), x)
9914       Res = DAG.getNode(ISD::ADD, DL, VT,
9915                         V,
9916                         DAG.getNode(ISD::SHL, DL, VT,
9917                                     V,
9918                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
9919                                                     MVT::i32)));
9920     } else if (isPowerOf2_32(MulAmt + 1)) {
9921       // (mul x, 2^N - 1) => (sub (shl x, N), x)
9922       Res = DAG.getNode(ISD::SUB, DL, VT,
9923                         DAG.getNode(ISD::SHL, DL, VT,
9924                                     V,
9925                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
9926                                                     MVT::i32)),
9927                         V);
9928     } else
9929       return SDValue();
9930   } else {
9931     uint64_t MulAmtAbs = -MulAmt;
9932     if (isPowerOf2_32(MulAmtAbs + 1)) {
9933       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9934       Res = DAG.getNode(ISD::SUB, DL, VT,
9935                         V,
9936                         DAG.getNode(ISD::SHL, DL, VT,
9937                                     V,
9938                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
9939                                                     MVT::i32)));
9940     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
9941       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9942       Res = DAG.getNode(ISD::ADD, DL, VT,
9943                         V,
9944                         DAG.getNode(ISD::SHL, DL, VT,
9945                                     V,
9946                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
9947                                                     MVT::i32)));
9948       Res = DAG.getNode(ISD::SUB, DL, VT,
9949                         DAG.getConstant(0, DL, MVT::i32), Res);
9950 
9951     } else
9952       return SDValue();
9953   }
9954 
9955   if (ShiftAmt != 0)
9956     Res = DAG.getNode(ISD::SHL, DL, VT,
9957                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
9958 
9959   // Do not add new nodes to DAG combiner worklist.
9960   DCI.CombineTo(N, Res, false);
9961   return SDValue();
9962 }
9963 
9964 static SDValue PerformANDCombine(SDNode *N,
9965                                  TargetLowering::DAGCombinerInfo &DCI,
9966                                  const ARMSubtarget *Subtarget) {
9967   // Attempt to use immediate-form VBIC
9968   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9969   SDLoc dl(N);
9970   EVT VT = N->getValueType(0);
9971   SelectionDAG &DAG = DCI.DAG;
9972 
9973   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9974     return SDValue();
9975 
9976   APInt SplatBits, SplatUndef;
9977   unsigned SplatBitSize;
9978   bool HasAnyUndefs;
9979   if (BVN &&
9980       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9981     if (SplatBitSize <= 64) {
9982       EVT VbicVT;
9983       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
9984                                       SplatUndef.getZExtValue(), SplatBitSize,
9985                                       DAG, dl, VbicVT, VT.is128BitVector(),
9986                                       OtherModImm);
9987       if (Val.getNode()) {
9988         SDValue Input =
9989           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
9990         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
9991         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
9992       }
9993     }
9994   }
9995 
9996   if (!Subtarget->isThumb1Only()) {
9997     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
9998     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
9999       return Result;
10000   }
10001 
10002   return SDValue();
10003 }
10004 
10005 // Try combining OR nodes to SMULWB, SMULWT.
10006 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10007                                          TargetLowering::DAGCombinerInfo &DCI,
10008                                          const ARMSubtarget *Subtarget) {
10009   if (!Subtarget->hasV6Ops() ||
10010       (Subtarget->isThumb() &&
10011        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10012     return SDValue();
10013 
10014   SDValue SRL = OR->getOperand(0);
10015   SDValue SHL = OR->getOperand(1);
10016 
10017   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10018     SRL = OR->getOperand(1);
10019     SHL = OR->getOperand(0);
10020   }
10021   if (!isSRL16(SRL) || !isSHL16(SHL))
10022     return SDValue();
10023 
10024   // The first operands to the shifts need to be the two results from the
10025   // same smul_lohi node.
10026   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10027        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10028     return SDValue();
10029 
10030   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10031   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10032       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10033     return SDValue();
10034 
10035   // Now we have:
10036   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10037   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10038   // For SMUWB the 16-bit value will signed extended somehow.
10039   // For SMULWT only the SRA is required.
10040   // Check both sides of SMUL_LOHI
10041   SDValue OpS16 = SMULLOHI->getOperand(0);
10042   SDValue OpS32 = SMULLOHI->getOperand(1);
10043 
10044   SelectionDAG &DAG = DCI.DAG;
10045   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10046     OpS16 = OpS32;
10047     OpS32 = SMULLOHI->getOperand(0);
10048   }
10049 
10050   SDLoc dl(OR);
10051   unsigned Opcode = 0;
10052   if (isS16(OpS16, DAG))
10053     Opcode = ARMISD::SMULWB;
10054   else if (isSRA16(OpS16)) {
10055     Opcode = ARMISD::SMULWT;
10056     OpS16 = OpS16->getOperand(0);
10057   }
10058   else
10059     return SDValue();
10060 
10061   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10062   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10063   return SDValue(OR, 0);
10064 }
10065 
10066 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10067 static SDValue PerformORCombine(SDNode *N,
10068                                 TargetLowering::DAGCombinerInfo &DCI,
10069                                 const ARMSubtarget *Subtarget) {
10070   // Attempt to use immediate-form VORR
10071   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10072   SDLoc dl(N);
10073   EVT VT = N->getValueType(0);
10074   SelectionDAG &DAG = DCI.DAG;
10075 
10076   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10077     return SDValue();
10078 
10079   APInt SplatBits, SplatUndef;
10080   unsigned SplatBitSize;
10081   bool HasAnyUndefs;
10082   if (BVN && Subtarget->hasNEON() &&
10083       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10084     if (SplatBitSize <= 64) {
10085       EVT VorrVT;
10086       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10087                                       SplatUndef.getZExtValue(), SplatBitSize,
10088                                       DAG, dl, VorrVT, VT.is128BitVector(),
10089                                       OtherModImm);
10090       if (Val.getNode()) {
10091         SDValue Input =
10092           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10093         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10094         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10095       }
10096     }
10097   }
10098 
10099   if (!Subtarget->isThumb1Only()) {
10100     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10101     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10102       return Result;
10103     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10104       return Result;
10105   }
10106 
10107   // The code below optimizes (or (and X, Y), Z).
10108   // The AND operand needs to have a single user to make these optimizations
10109   // profitable.
10110   SDValue N0 = N->getOperand(0);
10111   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10112     return SDValue();
10113   SDValue N1 = N->getOperand(1);
10114 
10115   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10116   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10117       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10118     APInt SplatUndef;
10119     unsigned SplatBitSize;
10120     bool HasAnyUndefs;
10121 
10122     APInt SplatBits0, SplatBits1;
10123     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10124     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10125     // Ensure that the second operand of both ands are constants
10126     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10127                                       HasAnyUndefs) && !HasAnyUndefs) {
10128         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10129                                           HasAnyUndefs) && !HasAnyUndefs) {
10130             // Ensure that the bit width of the constants are the same and that
10131             // the splat arguments are logical inverses as per the pattern we
10132             // are trying to simplify.
10133             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10134                 SplatBits0 == ~SplatBits1) {
10135                 // Canonicalize the vector type to make instruction selection
10136                 // simpler.
10137                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10138                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10139                                              N0->getOperand(1),
10140                                              N0->getOperand(0),
10141                                              N1->getOperand(0));
10142                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10143             }
10144         }
10145     }
10146   }
10147 
10148   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10149   // reasonable.
10150 
10151   // BFI is only available on V6T2+
10152   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10153     return SDValue();
10154 
10155   SDLoc DL(N);
10156   // 1) or (and A, mask), val => ARMbfi A, val, mask
10157   //      iff (val & mask) == val
10158   //
10159   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10160   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10161   //          && mask == ~mask2
10162   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10163   //          && ~mask == mask2
10164   //  (i.e., copy a bitfield value into another bitfield of the same width)
10165 
10166   if (VT != MVT::i32)
10167     return SDValue();
10168 
10169   SDValue N00 = N0.getOperand(0);
10170 
10171   // The value and the mask need to be constants so we can verify this is
10172   // actually a bitfield set. If the mask is 0xffff, we can do better
10173   // via a movt instruction, so don't use BFI in that case.
10174   SDValue MaskOp = N0.getOperand(1);
10175   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10176   if (!MaskC)
10177     return SDValue();
10178   unsigned Mask = MaskC->getZExtValue();
10179   if (Mask == 0xffff)
10180     return SDValue();
10181   SDValue Res;
10182   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10183   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10184   if (N1C) {
10185     unsigned Val = N1C->getZExtValue();
10186     if ((Val & ~Mask) != Val)
10187       return SDValue();
10188 
10189     if (ARM::isBitFieldInvertedMask(Mask)) {
10190       Val >>= countTrailingZeros(~Mask);
10191 
10192       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10193                         DAG.getConstant(Val, DL, MVT::i32),
10194                         DAG.getConstant(Mask, DL, MVT::i32));
10195 
10196       // Do not add new nodes to DAG combiner worklist.
10197       DCI.CombineTo(N, Res, false);
10198       return SDValue();
10199     }
10200   } else if (N1.getOpcode() == ISD::AND) {
10201     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10202     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10203     if (!N11C)
10204       return SDValue();
10205     unsigned Mask2 = N11C->getZExtValue();
10206 
10207     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10208     // as is to match.
10209     if (ARM::isBitFieldInvertedMask(Mask) &&
10210         (Mask == ~Mask2)) {
10211       // The pack halfword instruction works better for masks that fit it,
10212       // so use that when it's available.
10213       if (Subtarget->hasDSP() &&
10214           (Mask == 0xffff || Mask == 0xffff0000))
10215         return SDValue();
10216       // 2a
10217       unsigned amt = countTrailingZeros(Mask2);
10218       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10219                         DAG.getConstant(amt, DL, MVT::i32));
10220       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10221                         DAG.getConstant(Mask, DL, MVT::i32));
10222       // Do not add new nodes to DAG combiner worklist.
10223       DCI.CombineTo(N, Res, false);
10224       return SDValue();
10225     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10226                (~Mask == Mask2)) {
10227       // The pack halfword instruction works better for masks that fit it,
10228       // so use that when it's available.
10229       if (Subtarget->hasDSP() &&
10230           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10231         return SDValue();
10232       // 2b
10233       unsigned lsb = countTrailingZeros(Mask);
10234       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10235                         DAG.getConstant(lsb, DL, MVT::i32));
10236       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10237                         DAG.getConstant(Mask2, DL, MVT::i32));
10238       // Do not add new nodes to DAG combiner worklist.
10239       DCI.CombineTo(N, Res, false);
10240       return SDValue();
10241     }
10242   }
10243 
10244   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10245       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10246       ARM::isBitFieldInvertedMask(~Mask)) {
10247     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10248     // where lsb(mask) == #shamt and masked bits of B are known zero.
10249     SDValue ShAmt = N00.getOperand(1);
10250     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10251     unsigned LSB = countTrailingZeros(Mask);
10252     if (ShAmtC != LSB)
10253       return SDValue();
10254 
10255     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10256                       DAG.getConstant(~Mask, DL, MVT::i32));
10257 
10258     // Do not add new nodes to DAG combiner worklist.
10259     DCI.CombineTo(N, Res, false);
10260   }
10261 
10262   return SDValue();
10263 }
10264 
10265 static SDValue PerformXORCombine(SDNode *N,
10266                                  TargetLowering::DAGCombinerInfo &DCI,
10267                                  const ARMSubtarget *Subtarget) {
10268   EVT VT = N->getValueType(0);
10269   SelectionDAG &DAG = DCI.DAG;
10270 
10271   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10272     return SDValue();
10273 
10274   if (!Subtarget->isThumb1Only()) {
10275     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10276     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10277       return Result;
10278   }
10279 
10280   return SDValue();
10281 }
10282 
10283 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10284 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10285 // their position in "to" (Rd).
10286 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10287   assert(N->getOpcode() == ARMISD::BFI);
10288 
10289   SDValue From = N->getOperand(1);
10290   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10291   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10292 
10293   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10294   // #C in the base of the SHR.
10295   if (From->getOpcode() == ISD::SRL &&
10296       isa<ConstantSDNode>(From->getOperand(1))) {
10297     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10298     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10299     FromMask <<= Shift.getLimitedValue(31);
10300     From = From->getOperand(0);
10301   }
10302 
10303   return From;
10304 }
10305 
10306 // If A and B contain one contiguous set of bits, does A | B == A . B?
10307 //
10308 // Neither A nor B must be zero.
10309 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10310   unsigned LastActiveBitInA =  A.countTrailingZeros();
10311   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10312   return LastActiveBitInA - 1 == FirstActiveBitInB;
10313 }
10314 
10315 static SDValue FindBFIToCombineWith(SDNode *N) {
10316   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10317   // if one exists.
10318   APInt ToMask, FromMask;
10319   SDValue From = ParseBFI(N, ToMask, FromMask);
10320   SDValue To = N->getOperand(0);
10321 
10322   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10323   // aren't compatible, but not if they set the same bit in their destination as
10324   // we do (or that of any BFI we're going to combine with).
10325   SDValue V = To;
10326   APInt CombinedToMask = ToMask;
10327   while (V.getOpcode() == ARMISD::BFI) {
10328     APInt NewToMask, NewFromMask;
10329     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10330     if (NewFrom != From) {
10331       // This BFI has a different base. Keep going.
10332       CombinedToMask |= NewToMask;
10333       V = V.getOperand(0);
10334       continue;
10335     }
10336 
10337     // Do the written bits conflict with any we've seen so far?
10338     if ((NewToMask & CombinedToMask).getBoolValue())
10339       // Conflicting bits - bail out because going further is unsafe.
10340       return SDValue();
10341 
10342     // Are the new bits contiguous when combined with the old bits?
10343     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10344         BitsProperlyConcatenate(FromMask, NewFromMask))
10345       return V;
10346     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10347         BitsProperlyConcatenate(NewFromMask, FromMask))
10348       return V;
10349 
10350     // We've seen a write to some bits, so track it.
10351     CombinedToMask |= NewToMask;
10352     // Keep going...
10353     V = V.getOperand(0);
10354   }
10355 
10356   return SDValue();
10357 }
10358 
10359 static SDValue PerformBFICombine(SDNode *N,
10360                                  TargetLowering::DAGCombinerInfo &DCI) {
10361   SDValue N1 = N->getOperand(1);
10362   if (N1.getOpcode() == ISD::AND) {
10363     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10364     // the bits being cleared by the AND are not demanded by the BFI.
10365     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10366     if (!N11C)
10367       return SDValue();
10368     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10369     unsigned LSB = countTrailingZeros(~InvMask);
10370     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10371     assert(Width <
10372                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10373            "undefined behavior");
10374     unsigned Mask = (1u << Width) - 1;
10375     unsigned Mask2 = N11C->getZExtValue();
10376     if ((Mask & (~Mask2)) == 0)
10377       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10378                              N->getOperand(0), N1.getOperand(0),
10379                              N->getOperand(2));
10380   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10381     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10382     // Keep track of any consecutive bits set that all come from the same base
10383     // value. We can combine these together into a single BFI.
10384     SDValue CombineBFI = FindBFIToCombineWith(N);
10385     if (CombineBFI == SDValue())
10386       return SDValue();
10387 
10388     // We've found a BFI.
10389     APInt ToMask1, FromMask1;
10390     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10391 
10392     APInt ToMask2, FromMask2;
10393     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10394     assert(From1 == From2);
10395     (void)From2;
10396 
10397     // First, unlink CombineBFI.
10398     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10399     // Then create a new BFI, combining the two together.
10400     APInt NewFromMask = FromMask1 | FromMask2;
10401     APInt NewToMask = ToMask1 | ToMask2;
10402 
10403     EVT VT = N->getValueType(0);
10404     SDLoc dl(N);
10405 
10406     if (NewFromMask[0] == 0)
10407       From1 = DCI.DAG.getNode(
10408         ISD::SRL, dl, VT, From1,
10409         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10410     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10411                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10412   }
10413   return SDValue();
10414 }
10415 
10416 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10417 /// ARMISD::VMOVRRD.
10418 static SDValue PerformVMOVRRDCombine(SDNode *N,
10419                                      TargetLowering::DAGCombinerInfo &DCI,
10420                                      const ARMSubtarget *Subtarget) {
10421   // vmovrrd(vmovdrr x, y) -> x,y
10422   SDValue InDouble = N->getOperand(0);
10423   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10424     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10425 
10426   // vmovrrd(load f64) -> (load i32), (load i32)
10427   SDNode *InNode = InDouble.getNode();
10428   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10429       InNode->getValueType(0) == MVT::f64 &&
10430       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10431       !cast<LoadSDNode>(InNode)->isVolatile()) {
10432     // TODO: Should this be done for non-FrameIndex operands?
10433     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10434 
10435     SelectionDAG &DAG = DCI.DAG;
10436     SDLoc DL(LD);
10437     SDValue BasePtr = LD->getBasePtr();
10438     SDValue NewLD1 =
10439         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10440                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10441 
10442     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10443                                     DAG.getConstant(4, DL, MVT::i32));
10444     SDValue NewLD2 = DAG.getLoad(
10445         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10446         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10447 
10448     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10449     if (DCI.DAG.getDataLayout().isBigEndian())
10450       std::swap (NewLD1, NewLD2);
10451     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10452     return Result;
10453   }
10454 
10455   return SDValue();
10456 }
10457 
10458 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10459 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10460 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10461   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10462   SDValue Op0 = N->getOperand(0);
10463   SDValue Op1 = N->getOperand(1);
10464   if (Op0.getOpcode() == ISD::BITCAST)
10465     Op0 = Op0.getOperand(0);
10466   if (Op1.getOpcode() == ISD::BITCAST)
10467     Op1 = Op1.getOperand(0);
10468   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10469       Op0.getNode() == Op1.getNode() &&
10470       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10471     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10472                        N->getValueType(0), Op0.getOperand(0));
10473   return SDValue();
10474 }
10475 
10476 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10477 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10478 /// i64 vector to have f64 elements, since the value can then be loaded
10479 /// directly into a VFP register.
10480 static bool hasNormalLoadOperand(SDNode *N) {
10481   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10482   for (unsigned i = 0; i < NumElts; ++i) {
10483     SDNode *Elt = N->getOperand(i).getNode();
10484     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10485       return true;
10486   }
10487   return false;
10488 }
10489 
10490 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10491 /// ISD::BUILD_VECTOR.
10492 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10493                                           TargetLowering::DAGCombinerInfo &DCI,
10494                                           const ARMSubtarget *Subtarget) {
10495   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10496   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10497   // into a pair of GPRs, which is fine when the value is used as a scalar,
10498   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10499   SelectionDAG &DAG = DCI.DAG;
10500   if (N->getNumOperands() == 2)
10501     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10502       return RV;
10503 
10504   // Load i64 elements as f64 values so that type legalization does not split
10505   // them up into i32 values.
10506   EVT VT = N->getValueType(0);
10507   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10508     return SDValue();
10509   SDLoc dl(N);
10510   SmallVector<SDValue, 8> Ops;
10511   unsigned NumElts = VT.getVectorNumElements();
10512   for (unsigned i = 0; i < NumElts; ++i) {
10513     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10514     Ops.push_back(V);
10515     // Make the DAGCombiner fold the bitcast.
10516     DCI.AddToWorklist(V.getNode());
10517   }
10518   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10519   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10520   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10521 }
10522 
10523 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10524 static SDValue
10525 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10526   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10527   // At that time, we may have inserted bitcasts from integer to float.
10528   // If these bitcasts have survived DAGCombine, change the lowering of this
10529   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10530   // force to use floating point types.
10531 
10532   // Make sure we can change the type of the vector.
10533   // This is possible iff:
10534   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10535   //    1.1. Vector is used only once.
10536   //    1.2. Use is a bit convert to an integer type.
10537   // 2. The size of its operands are 32-bits (64-bits are not legal).
10538   EVT VT = N->getValueType(0);
10539   EVT EltVT = VT.getVectorElementType();
10540 
10541   // Check 1.1. and 2.
10542   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10543     return SDValue();
10544 
10545   // By construction, the input type must be float.
10546   assert(EltVT == MVT::f32 && "Unexpected type!");
10547 
10548   // Check 1.2.
10549   SDNode *Use = *N->use_begin();
10550   if (Use->getOpcode() != ISD::BITCAST ||
10551       Use->getValueType(0).isFloatingPoint())
10552     return SDValue();
10553 
10554   // Check profitability.
10555   // Model is, if more than half of the relevant operands are bitcast from
10556   // i32, turn the build_vector into a sequence of insert_vector_elt.
10557   // Relevant operands are everything that is not statically
10558   // (i.e., at compile time) bitcasted.
10559   unsigned NumOfBitCastedElts = 0;
10560   unsigned NumElts = VT.getVectorNumElements();
10561   unsigned NumOfRelevantElts = NumElts;
10562   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10563     SDValue Elt = N->getOperand(Idx);
10564     if (Elt->getOpcode() == ISD::BITCAST) {
10565       // Assume only bit cast to i32 will go away.
10566       if (Elt->getOperand(0).getValueType() == MVT::i32)
10567         ++NumOfBitCastedElts;
10568     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10569       // Constants are statically casted, thus do not count them as
10570       // relevant operands.
10571       --NumOfRelevantElts;
10572   }
10573 
10574   // Check if more than half of the elements require a non-free bitcast.
10575   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10576     return SDValue();
10577 
10578   SelectionDAG &DAG = DCI.DAG;
10579   // Create the new vector type.
10580   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10581   // Check if the type is legal.
10582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10583   if (!TLI.isTypeLegal(VecVT))
10584     return SDValue();
10585 
10586   // Combine:
10587   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10588   // => BITCAST INSERT_VECTOR_ELT
10589   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10590   //                      (BITCAST EN), N.
10591   SDValue Vec = DAG.getUNDEF(VecVT);
10592   SDLoc dl(N);
10593   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10594     SDValue V = N->getOperand(Idx);
10595     if (V.isUndef())
10596       continue;
10597     if (V.getOpcode() == ISD::BITCAST &&
10598         V->getOperand(0).getValueType() == MVT::i32)
10599       // Fold obvious case.
10600       V = V.getOperand(0);
10601     else {
10602       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10603       // Make the DAGCombiner fold the bitcasts.
10604       DCI.AddToWorklist(V.getNode());
10605     }
10606     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10607     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10608   }
10609   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10610   // Make the DAGCombiner fold the bitcasts.
10611   DCI.AddToWorklist(Vec.getNode());
10612   return Vec;
10613 }
10614 
10615 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10616 /// ISD::INSERT_VECTOR_ELT.
10617 static SDValue PerformInsertEltCombine(SDNode *N,
10618                                        TargetLowering::DAGCombinerInfo &DCI) {
10619   // Bitcast an i64 load inserted into a vector to f64.
10620   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10621   EVT VT = N->getValueType(0);
10622   SDNode *Elt = N->getOperand(1).getNode();
10623   if (VT.getVectorElementType() != MVT::i64 ||
10624       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10625     return SDValue();
10626 
10627   SelectionDAG &DAG = DCI.DAG;
10628   SDLoc dl(N);
10629   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10630                                  VT.getVectorNumElements());
10631   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10632   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10633   // Make the DAGCombiner fold the bitcasts.
10634   DCI.AddToWorklist(Vec.getNode());
10635   DCI.AddToWorklist(V.getNode());
10636   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10637                                Vec, V, N->getOperand(2));
10638   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10639 }
10640 
10641 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10642 /// ISD::VECTOR_SHUFFLE.
10643 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10644   // The LLVM shufflevector instruction does not require the shuffle mask
10645   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10646   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10647   // operands do not match the mask length, they are extended by concatenating
10648   // them with undef vectors.  That is probably the right thing for other
10649   // targets, but for NEON it is better to concatenate two double-register
10650   // size vector operands into a single quad-register size vector.  Do that
10651   // transformation here:
10652   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10653   //   shuffle(concat(v1, v2), undef)
10654   SDValue Op0 = N->getOperand(0);
10655   SDValue Op1 = N->getOperand(1);
10656   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10657       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10658       Op0.getNumOperands() != 2 ||
10659       Op1.getNumOperands() != 2)
10660     return SDValue();
10661   SDValue Concat0Op1 = Op0.getOperand(1);
10662   SDValue Concat1Op1 = Op1.getOperand(1);
10663   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10664     return SDValue();
10665   // Skip the transformation if any of the types are illegal.
10666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10667   EVT VT = N->getValueType(0);
10668   if (!TLI.isTypeLegal(VT) ||
10669       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10670       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10671     return SDValue();
10672 
10673   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10674                                   Op0.getOperand(0), Op1.getOperand(0));
10675   // Translate the shuffle mask.
10676   SmallVector<int, 16> NewMask;
10677   unsigned NumElts = VT.getVectorNumElements();
10678   unsigned HalfElts = NumElts/2;
10679   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10680   for (unsigned n = 0; n < NumElts; ++n) {
10681     int MaskElt = SVN->getMaskElt(n);
10682     int NewElt = -1;
10683     if (MaskElt < (int)HalfElts)
10684       NewElt = MaskElt;
10685     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10686       NewElt = HalfElts + MaskElt - NumElts;
10687     NewMask.push_back(NewElt);
10688   }
10689   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10690                               DAG.getUNDEF(VT), NewMask);
10691 }
10692 
10693 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10694 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10695 /// base address updates.
10696 /// For generic load/stores, the memory type is assumed to be a vector.
10697 /// The caller is assumed to have checked legality.
10698 static SDValue CombineBaseUpdate(SDNode *N,
10699                                  TargetLowering::DAGCombinerInfo &DCI) {
10700   SelectionDAG &DAG = DCI.DAG;
10701   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10702                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10703   const bool isStore = N->getOpcode() == ISD::STORE;
10704   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10705   SDValue Addr = N->getOperand(AddrOpIdx);
10706   MemSDNode *MemN = cast<MemSDNode>(N);
10707   SDLoc dl(N);
10708 
10709   // Search for a use of the address operand that is an increment.
10710   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10711          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10712     SDNode *User = *UI;
10713     if (User->getOpcode() != ISD::ADD ||
10714         UI.getUse().getResNo() != Addr.getResNo())
10715       continue;
10716 
10717     // Check that the add is independent of the load/store.  Otherwise, folding
10718     // it would create a cycle.
10719     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10720       continue;
10721 
10722     // Find the new opcode for the updating load/store.
10723     bool isLoadOp = true;
10724     bool isLaneOp = false;
10725     unsigned NewOpc = 0;
10726     unsigned NumVecs = 0;
10727     if (isIntrinsic) {
10728       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10729       switch (IntNo) {
10730       default: llvm_unreachable("unexpected intrinsic for Neon base update");
10731       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
10732         NumVecs = 1; break;
10733       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
10734         NumVecs = 2; break;
10735       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
10736         NumVecs = 3; break;
10737       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
10738         NumVecs = 4; break;
10739       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10740         NumVecs = 2; isLaneOp = true; break;
10741       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10742         NumVecs = 3; isLaneOp = true; break;
10743       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10744         NumVecs = 4; isLaneOp = true; break;
10745       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
10746         NumVecs = 1; isLoadOp = false; break;
10747       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
10748         NumVecs = 2; isLoadOp = false; break;
10749       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
10750         NumVecs = 3; isLoadOp = false; break;
10751       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
10752         NumVecs = 4; isLoadOp = false; break;
10753       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10754         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10755       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10756         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10757       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10758         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10759       }
10760     } else {
10761       isLaneOp = true;
10762       switch (N->getOpcode()) {
10763       default: llvm_unreachable("unexpected opcode for Neon base update");
10764       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
10765       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10766       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10767       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10768       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
10769         NumVecs = 1; isLaneOp = false; break;
10770       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
10771         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10772       }
10773     }
10774 
10775     // Find the size of memory referenced by the load/store.
10776     EVT VecTy;
10777     if (isLoadOp) {
10778       VecTy = N->getValueType(0);
10779     } else if (isIntrinsic) {
10780       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10781     } else {
10782       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10783       VecTy = N->getOperand(1).getValueType();
10784     }
10785 
10786     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10787     if (isLaneOp)
10788       NumBytes /= VecTy.getVectorNumElements();
10789 
10790     // If the increment is a constant, it must match the memory ref size.
10791     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10792     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10793       uint64_t IncVal = CInc->getZExtValue();
10794       if (IncVal != NumBytes)
10795         continue;
10796     } else if (NumBytes >= 3 * 16) {
10797       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10798       // separate instructions that make it harder to use a non-constant update.
10799       continue;
10800     }
10801 
10802     // OK, we found an ADD we can fold into the base update.
10803     // Now, create a _UPD node, taking care of not breaking alignment.
10804 
10805     EVT AlignedVecTy = VecTy;
10806     unsigned Alignment = MemN->getAlignment();
10807 
10808     // If this is a less-than-standard-aligned load/store, change the type to
10809     // match the standard alignment.
10810     // The alignment is overlooked when selecting _UPD variants; and it's
10811     // easier to introduce bitcasts here than fix that.
10812     // There are 3 ways to get to this base-update combine:
10813     // - intrinsics: they are assumed to be properly aligned (to the standard
10814     //   alignment of the memory type), so we don't need to do anything.
10815     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10816     //   intrinsics, so, likewise, there's nothing to do.
10817     // - generic load/store instructions: the alignment is specified as an
10818     //   explicit operand, rather than implicitly as the standard alignment
10819     //   of the memory type (like the intrisics).  We need to change the
10820     //   memory type to match the explicit alignment.  That way, we don't
10821     //   generate non-standard-aligned ARMISD::VLDx nodes.
10822     if (isa<LSBaseSDNode>(N)) {
10823       if (Alignment == 0)
10824         Alignment = 1;
10825       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10826         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10827         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10828         assert(!isLaneOp && "Unexpected generic load/store lane.");
10829         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10830         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10831       }
10832       // Don't set an explicit alignment on regular load/stores that we want
10833       // to transform to VLD/VST 1_UPD nodes.
10834       // This matches the behavior of regular load/stores, which only get an
10835       // explicit alignment if the MMO alignment is larger than the standard
10836       // alignment of the memory type.
10837       // Intrinsics, however, always get an explicit alignment, set to the
10838       // alignment of the MMO.
10839       Alignment = 1;
10840     }
10841 
10842     // Create the new updating load/store node.
10843     // First, create an SDVTList for the new updating node's results.
10844     EVT Tys[6];
10845     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10846     unsigned n;
10847     for (n = 0; n < NumResultVecs; ++n)
10848       Tys[n] = AlignedVecTy;
10849     Tys[n++] = MVT::i32;
10850     Tys[n] = MVT::Other;
10851     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10852 
10853     // Then, gather the new node's operands.
10854     SmallVector<SDValue, 8> Ops;
10855     Ops.push_back(N->getOperand(0)); // incoming chain
10856     Ops.push_back(N->getOperand(AddrOpIdx));
10857     Ops.push_back(Inc);
10858 
10859     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10860       // Try to match the intrinsic's signature
10861       Ops.push_back(StN->getValue());
10862     } else {
10863       // Loads (and of course intrinsics) match the intrinsics' signature,
10864       // so just add all but the alignment operand.
10865       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10866         Ops.push_back(N->getOperand(i));
10867     }
10868 
10869     // For all node types, the alignment operand is always the last one.
10870     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10871 
10872     // If this is a non-standard-aligned STORE, the penultimate operand is the
10873     // stored value.  Bitcast it to the aligned type.
10874     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10875       SDValue &StVal = Ops[Ops.size()-2];
10876       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10877     }
10878 
10879     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
10880     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
10881                                            MemN->getMemOperand());
10882 
10883     // Update the uses.
10884     SmallVector<SDValue, 5> NewResults;
10885     for (unsigned i = 0; i < NumResultVecs; ++i)
10886       NewResults.push_back(SDValue(UpdN.getNode(), i));
10887 
10888     // If this is an non-standard-aligned LOAD, the first result is the loaded
10889     // value.  Bitcast it to the expected result type.
10890     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10891       SDValue &LdVal = NewResults[0];
10892       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10893     }
10894 
10895     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10896     DCI.CombineTo(N, NewResults);
10897     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10898 
10899     break;
10900   }
10901   return SDValue();
10902 }
10903 
10904 static SDValue PerformVLDCombine(SDNode *N,
10905                                  TargetLowering::DAGCombinerInfo &DCI) {
10906   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10907     return SDValue();
10908 
10909   return CombineBaseUpdate(N, DCI);
10910 }
10911 
10912 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10913 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10914 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
10915 /// return true.
10916 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10917   SelectionDAG &DAG = DCI.DAG;
10918   EVT VT = N->getValueType(0);
10919   // vldN-dup instructions only support 64-bit vectors for N > 1.
10920   if (!VT.is64BitVector())
10921     return false;
10922 
10923   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
10924   SDNode *VLD = N->getOperand(0).getNode();
10925   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
10926     return false;
10927   unsigned NumVecs = 0;
10928   unsigned NewOpc = 0;
10929   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
10930   if (IntNo == Intrinsic::arm_neon_vld2lane) {
10931     NumVecs = 2;
10932     NewOpc = ARMISD::VLD2DUP;
10933   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
10934     NumVecs = 3;
10935     NewOpc = ARMISD::VLD3DUP;
10936   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
10937     NumVecs = 4;
10938     NewOpc = ARMISD::VLD4DUP;
10939   } else {
10940     return false;
10941   }
10942 
10943   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
10944   // numbers match the load.
10945   unsigned VLDLaneNo =
10946     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
10947   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10948        UI != UE; ++UI) {
10949     // Ignore uses of the chain result.
10950     if (UI.getUse().getResNo() == NumVecs)
10951       continue;
10952     SDNode *User = *UI;
10953     if (User->getOpcode() != ARMISD::VDUPLANE ||
10954         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
10955       return false;
10956   }
10957 
10958   // Create the vldN-dup node.
10959   EVT Tys[5];
10960   unsigned n;
10961   for (n = 0; n < NumVecs; ++n)
10962     Tys[n] = VT;
10963   Tys[n] = MVT::Other;
10964   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
10965   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
10966   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
10967   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
10968                                            Ops, VLDMemInt->getMemoryVT(),
10969                                            VLDMemInt->getMemOperand());
10970 
10971   // Update the uses.
10972   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10973        UI != UE; ++UI) {
10974     unsigned ResNo = UI.getUse().getResNo();
10975     // Ignore uses of the chain result.
10976     if (ResNo == NumVecs)
10977       continue;
10978     SDNode *User = *UI;
10979     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
10980   }
10981 
10982   // Now the vldN-lane intrinsic is dead except for its chain result.
10983   // Update uses of the chain.
10984   std::vector<SDValue> VLDDupResults;
10985   for (unsigned n = 0; n < NumVecs; ++n)
10986     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
10987   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
10988   DCI.CombineTo(VLD, VLDDupResults);
10989 
10990   return true;
10991 }
10992 
10993 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
10994 /// ARMISD::VDUPLANE.
10995 static SDValue PerformVDUPLANECombine(SDNode *N,
10996                                       TargetLowering::DAGCombinerInfo &DCI) {
10997   SDValue Op = N->getOperand(0);
10998 
10999   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11000   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11001   if (CombineVLDDUP(N, DCI))
11002     return SDValue(N, 0);
11003 
11004   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11005   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11006   while (Op.getOpcode() == ISD::BITCAST)
11007     Op = Op.getOperand(0);
11008   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11009     return SDValue();
11010 
11011   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11012   unsigned EltSize = Op.getScalarValueSizeInBits();
11013   // The canonical VMOV for a zero vector uses a 32-bit element size.
11014   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11015   unsigned EltBits;
11016   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11017     EltSize = 8;
11018   EVT VT = N->getValueType(0);
11019   if (EltSize > VT.getScalarSizeInBits())
11020     return SDValue();
11021 
11022   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11023 }
11024 
11025 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11026 static SDValue PerformVDUPCombine(SDNode *N,
11027                                   TargetLowering::DAGCombinerInfo &DCI) {
11028   SelectionDAG &DAG = DCI.DAG;
11029   SDValue Op = N->getOperand(0);
11030 
11031   // Match VDUP(LOAD) -> VLD1DUP.
11032   // We match this pattern here rather than waiting for isel because the
11033   // transform is only legal for unindexed loads.
11034   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11035   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11036       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11037     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11038                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11039     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11040     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11041                                              Ops, LD->getMemoryVT(),
11042                                              LD->getMemOperand());
11043     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11044     return VLDDup;
11045   }
11046 
11047   return SDValue();
11048 }
11049 
11050 static SDValue PerformLOADCombine(SDNode *N,
11051                                   TargetLowering::DAGCombinerInfo &DCI) {
11052   EVT VT = N->getValueType(0);
11053 
11054   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11055   if (ISD::isNormalLoad(N) && VT.isVector() &&
11056       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11057     return CombineBaseUpdate(N, DCI);
11058 
11059   return SDValue();
11060 }
11061 
11062 /// PerformSTORECombine - Target-specific dag combine xforms for
11063 /// ISD::STORE.
11064 static SDValue PerformSTORECombine(SDNode *N,
11065                                    TargetLowering::DAGCombinerInfo &DCI) {
11066   StoreSDNode *St = cast<StoreSDNode>(N);
11067   if (St->isVolatile())
11068     return SDValue();
11069 
11070   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11071   // pack all of the elements in one place.  Next, store to memory in fewer
11072   // chunks.
11073   SDValue StVal = St->getValue();
11074   EVT VT = StVal.getValueType();
11075   if (St->isTruncatingStore() && VT.isVector()) {
11076     SelectionDAG &DAG = DCI.DAG;
11077     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11078     EVT StVT = St->getMemoryVT();
11079     unsigned NumElems = VT.getVectorNumElements();
11080     assert(StVT != VT && "Cannot truncate to the same type");
11081     unsigned FromEltSz = VT.getScalarSizeInBits();
11082     unsigned ToEltSz = StVT.getScalarSizeInBits();
11083 
11084     // From, To sizes and ElemCount must be pow of two
11085     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11086 
11087     // We are going to use the original vector elt for storing.
11088     // Accumulated smaller vector elements must be a multiple of the store size.
11089     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11090 
11091     unsigned SizeRatio  = FromEltSz / ToEltSz;
11092     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11093 
11094     // Create a type on which we perform the shuffle.
11095     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11096                                      NumElems*SizeRatio);
11097     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11098 
11099     SDLoc DL(St);
11100     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11101     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11102     for (unsigned i = 0; i < NumElems; ++i)
11103       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11104                           ? (i + 1) * SizeRatio - 1
11105                           : i * SizeRatio;
11106 
11107     // Can't shuffle using an illegal type.
11108     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11109 
11110     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11111                                 DAG.getUNDEF(WideVec.getValueType()),
11112                                 ShuffleVec);
11113     // At this point all of the data is stored at the bottom of the
11114     // register. We now need to save it to mem.
11115 
11116     // Find the largest store unit
11117     MVT StoreType = MVT::i8;
11118     for (MVT Tp : MVT::integer_valuetypes()) {
11119       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11120         StoreType = Tp;
11121     }
11122     // Didn't find a legal store type.
11123     if (!TLI.isTypeLegal(StoreType))
11124       return SDValue();
11125 
11126     // Bitcast the original vector into a vector of store-size units
11127     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11128             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11129     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11130     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11131     SmallVector<SDValue, 8> Chains;
11132     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11133                                         TLI.getPointerTy(DAG.getDataLayout()));
11134     SDValue BasePtr = St->getBasePtr();
11135 
11136     // Perform one or more big stores into memory.
11137     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11138     for (unsigned I = 0; I < E; I++) {
11139       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11140                                    StoreType, ShuffWide,
11141                                    DAG.getIntPtrConstant(I, DL));
11142       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11143                                 St->getPointerInfo(), St->getAlignment(),
11144                                 St->getMemOperand()->getFlags());
11145       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11146                             Increment);
11147       Chains.push_back(Ch);
11148     }
11149     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11150   }
11151 
11152   if (!ISD::isNormalStore(St))
11153     return SDValue();
11154 
11155   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11156   // ARM stores of arguments in the same cache line.
11157   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11158       StVal.getNode()->hasOneUse()) {
11159     SelectionDAG  &DAG = DCI.DAG;
11160     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11161     SDLoc DL(St);
11162     SDValue BasePtr = St->getBasePtr();
11163     SDValue NewST1 = DAG.getStore(
11164         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11165         BasePtr, St->getPointerInfo(), St->getAlignment(),
11166         St->getMemOperand()->getFlags());
11167 
11168     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11169                                     DAG.getConstant(4, DL, MVT::i32));
11170     return DAG.getStore(NewST1.getValue(0), DL,
11171                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11172                         OffsetPtr, St->getPointerInfo(),
11173                         std::min(4U, St->getAlignment() / 2),
11174                         St->getMemOperand()->getFlags());
11175   }
11176 
11177   if (StVal.getValueType() == MVT::i64 &&
11178       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11179 
11180     // Bitcast an i64 store extracted from a vector to f64.
11181     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11182     SelectionDAG &DAG = DCI.DAG;
11183     SDLoc dl(StVal);
11184     SDValue IntVec = StVal.getOperand(0);
11185     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11186                                    IntVec.getValueType().getVectorNumElements());
11187     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11188     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11189                                  Vec, StVal.getOperand(1));
11190     dl = SDLoc(N);
11191     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11192     // Make the DAGCombiner fold the bitcasts.
11193     DCI.AddToWorklist(Vec.getNode());
11194     DCI.AddToWorklist(ExtElt.getNode());
11195     DCI.AddToWorklist(V.getNode());
11196     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11197                         St->getPointerInfo(), St->getAlignment(),
11198                         St->getMemOperand()->getFlags(), St->getAAInfo());
11199   }
11200 
11201   // If this is a legal vector store, try to combine it into a VST1_UPD.
11202   if (ISD::isNormalStore(N) && VT.isVector() &&
11203       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11204     return CombineBaseUpdate(N, DCI);
11205 
11206   return SDValue();
11207 }
11208 
11209 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11210 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11211 /// when the VMUL has a constant operand that is a power of 2.
11212 ///
11213 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11214 ///  vmul.f32        d16, d17, d16
11215 ///  vcvt.s32.f32    d16, d16
11216 /// becomes:
11217 ///  vcvt.s32.f32    d16, d16, #3
11218 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11219                                   const ARMSubtarget *Subtarget) {
11220   if (!Subtarget->hasNEON())
11221     return SDValue();
11222 
11223   SDValue Op = N->getOperand(0);
11224   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11225       Op.getOpcode() != ISD::FMUL)
11226     return SDValue();
11227 
11228   SDValue ConstVec = Op->getOperand(1);
11229   if (!isa<BuildVectorSDNode>(ConstVec))
11230     return SDValue();
11231 
11232   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11233   uint32_t FloatBits = FloatTy.getSizeInBits();
11234   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11235   uint32_t IntBits = IntTy.getSizeInBits();
11236   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11237   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11238     // These instructions only exist converting from f32 to i32. We can handle
11239     // smaller integers by generating an extra truncate, but larger ones would
11240     // be lossy. We also can't handle more then 4 lanes, since these intructions
11241     // only support v2i32/v4i32 types.
11242     return SDValue();
11243   }
11244 
11245   BitVector UndefElements;
11246   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11247   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11248   if (C == -1 || C == 0 || C > 32)
11249     return SDValue();
11250 
11251   SDLoc dl(N);
11252   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11253   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11254     Intrinsic::arm_neon_vcvtfp2fxu;
11255   SDValue FixConv = DAG.getNode(
11256       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11257       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11258       DAG.getConstant(C, dl, MVT::i32));
11259 
11260   if (IntBits < FloatBits)
11261     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11262 
11263   return FixConv;
11264 }
11265 
11266 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11267 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11268 /// when the VDIV has a constant operand that is a power of 2.
11269 ///
11270 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11271 ///  vcvt.f32.s32    d16, d16
11272 ///  vdiv.f32        d16, d17, d16
11273 /// becomes:
11274 ///  vcvt.f32.s32    d16, d16, #3
11275 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11276                                   const ARMSubtarget *Subtarget) {
11277   if (!Subtarget->hasNEON())
11278     return SDValue();
11279 
11280   SDValue Op = N->getOperand(0);
11281   unsigned OpOpcode = Op.getNode()->getOpcode();
11282   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11283       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11284     return SDValue();
11285 
11286   SDValue ConstVec = N->getOperand(1);
11287   if (!isa<BuildVectorSDNode>(ConstVec))
11288     return SDValue();
11289 
11290   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11291   uint32_t FloatBits = FloatTy.getSizeInBits();
11292   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11293   uint32_t IntBits = IntTy.getSizeInBits();
11294   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11295   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11296     // These instructions only exist converting from i32 to f32. We can handle
11297     // smaller integers by generating an extra extend, but larger ones would
11298     // be lossy. We also can't handle more then 4 lanes, since these intructions
11299     // only support v2i32/v4i32 types.
11300     return SDValue();
11301   }
11302 
11303   BitVector UndefElements;
11304   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11305   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11306   if (C == -1 || C == 0 || C > 32)
11307     return SDValue();
11308 
11309   SDLoc dl(N);
11310   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11311   SDValue ConvInput = Op.getOperand(0);
11312   if (IntBits < FloatBits)
11313     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11314                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11315                             ConvInput);
11316 
11317   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11318     Intrinsic::arm_neon_vcvtfxu2fp;
11319   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11320                      Op.getValueType(),
11321                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11322                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11323 }
11324 
11325 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11326 /// operand of a vector shift operation, where all the elements of the
11327 /// build_vector must have the same constant integer value.
11328 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11329   // Ignore bit_converts.
11330   while (Op.getOpcode() == ISD::BITCAST)
11331     Op = Op.getOperand(0);
11332   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11333   APInt SplatBits, SplatUndef;
11334   unsigned SplatBitSize;
11335   bool HasAnyUndefs;
11336   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11337                                       HasAnyUndefs, ElementBits) ||
11338       SplatBitSize > ElementBits)
11339     return false;
11340   Cnt = SplatBits.getSExtValue();
11341   return true;
11342 }
11343 
11344 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11345 /// operand of a vector shift left operation.  That value must be in the range:
11346 ///   0 <= Value < ElementBits for a left shift; or
11347 ///   0 <= Value <= ElementBits for a long left shift.
11348 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11349   assert(VT.isVector() && "vector shift count is not a vector type");
11350   int64_t ElementBits = VT.getScalarSizeInBits();
11351   if (! getVShiftImm(Op, ElementBits, Cnt))
11352     return false;
11353   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11354 }
11355 
11356 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11357 /// operand of a vector shift right operation.  For a shift opcode, the value
11358 /// is positive, but for an intrinsic the value count must be negative. The
11359 /// absolute value must be in the range:
11360 ///   1 <= |Value| <= ElementBits for a right shift; or
11361 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11362 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11363                          int64_t &Cnt) {
11364   assert(VT.isVector() && "vector shift count is not a vector type");
11365   int64_t ElementBits = VT.getScalarSizeInBits();
11366   if (! getVShiftImm(Op, ElementBits, Cnt))
11367     return false;
11368   if (!isIntrinsic)
11369     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11370   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11371     Cnt = -Cnt;
11372     return true;
11373   }
11374   return false;
11375 }
11376 
11377 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11378 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11379   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11380   switch (IntNo) {
11381   default:
11382     // Don't do anything for most intrinsics.
11383     break;
11384 
11385   // Vector shifts: check for immediate versions and lower them.
11386   // Note: This is done during DAG combining instead of DAG legalizing because
11387   // the build_vectors for 64-bit vector element shift counts are generally
11388   // not legal, and it is hard to see their values after they get legalized to
11389   // loads from a constant pool.
11390   case Intrinsic::arm_neon_vshifts:
11391   case Intrinsic::arm_neon_vshiftu:
11392   case Intrinsic::arm_neon_vrshifts:
11393   case Intrinsic::arm_neon_vrshiftu:
11394   case Intrinsic::arm_neon_vrshiftn:
11395   case Intrinsic::arm_neon_vqshifts:
11396   case Intrinsic::arm_neon_vqshiftu:
11397   case Intrinsic::arm_neon_vqshiftsu:
11398   case Intrinsic::arm_neon_vqshiftns:
11399   case Intrinsic::arm_neon_vqshiftnu:
11400   case Intrinsic::arm_neon_vqshiftnsu:
11401   case Intrinsic::arm_neon_vqrshiftns:
11402   case Intrinsic::arm_neon_vqrshiftnu:
11403   case Intrinsic::arm_neon_vqrshiftnsu: {
11404     EVT VT = N->getOperand(1).getValueType();
11405     int64_t Cnt;
11406     unsigned VShiftOpc = 0;
11407 
11408     switch (IntNo) {
11409     case Intrinsic::arm_neon_vshifts:
11410     case Intrinsic::arm_neon_vshiftu:
11411       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11412         VShiftOpc = ARMISD::VSHL;
11413         break;
11414       }
11415       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11416         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11417                      ARMISD::VSHRs : ARMISD::VSHRu);
11418         break;
11419       }
11420       return SDValue();
11421 
11422     case Intrinsic::arm_neon_vrshifts:
11423     case Intrinsic::arm_neon_vrshiftu:
11424       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11425         break;
11426       return SDValue();
11427 
11428     case Intrinsic::arm_neon_vqshifts:
11429     case Intrinsic::arm_neon_vqshiftu:
11430       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11431         break;
11432       return SDValue();
11433 
11434     case Intrinsic::arm_neon_vqshiftsu:
11435       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11436         break;
11437       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11438 
11439     case Intrinsic::arm_neon_vrshiftn:
11440     case Intrinsic::arm_neon_vqshiftns:
11441     case Intrinsic::arm_neon_vqshiftnu:
11442     case Intrinsic::arm_neon_vqshiftnsu:
11443     case Intrinsic::arm_neon_vqrshiftns:
11444     case Intrinsic::arm_neon_vqrshiftnu:
11445     case Intrinsic::arm_neon_vqrshiftnsu:
11446       // Narrowing shifts require an immediate right shift.
11447       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11448         break;
11449       llvm_unreachable("invalid shift count for narrowing vector shift "
11450                        "intrinsic");
11451 
11452     default:
11453       llvm_unreachable("unhandled vector shift");
11454     }
11455 
11456     switch (IntNo) {
11457     case Intrinsic::arm_neon_vshifts:
11458     case Intrinsic::arm_neon_vshiftu:
11459       // Opcode already set above.
11460       break;
11461     case Intrinsic::arm_neon_vrshifts:
11462       VShiftOpc = ARMISD::VRSHRs; break;
11463     case Intrinsic::arm_neon_vrshiftu:
11464       VShiftOpc = ARMISD::VRSHRu; break;
11465     case Intrinsic::arm_neon_vrshiftn:
11466       VShiftOpc = ARMISD::VRSHRN; break;
11467     case Intrinsic::arm_neon_vqshifts:
11468       VShiftOpc = ARMISD::VQSHLs; break;
11469     case Intrinsic::arm_neon_vqshiftu:
11470       VShiftOpc = ARMISD::VQSHLu; break;
11471     case Intrinsic::arm_neon_vqshiftsu:
11472       VShiftOpc = ARMISD::VQSHLsu; break;
11473     case Intrinsic::arm_neon_vqshiftns:
11474       VShiftOpc = ARMISD::VQSHRNs; break;
11475     case Intrinsic::arm_neon_vqshiftnu:
11476       VShiftOpc = ARMISD::VQSHRNu; break;
11477     case Intrinsic::arm_neon_vqshiftnsu:
11478       VShiftOpc = ARMISD::VQSHRNsu; break;
11479     case Intrinsic::arm_neon_vqrshiftns:
11480       VShiftOpc = ARMISD::VQRSHRNs; break;
11481     case Intrinsic::arm_neon_vqrshiftnu:
11482       VShiftOpc = ARMISD::VQRSHRNu; break;
11483     case Intrinsic::arm_neon_vqrshiftnsu:
11484       VShiftOpc = ARMISD::VQRSHRNsu; break;
11485     }
11486 
11487     SDLoc dl(N);
11488     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11489                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11490   }
11491 
11492   case Intrinsic::arm_neon_vshiftins: {
11493     EVT VT = N->getOperand(1).getValueType();
11494     int64_t Cnt;
11495     unsigned VShiftOpc = 0;
11496 
11497     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11498       VShiftOpc = ARMISD::VSLI;
11499     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11500       VShiftOpc = ARMISD::VSRI;
11501     else {
11502       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11503     }
11504 
11505     SDLoc dl(N);
11506     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11507                        N->getOperand(1), N->getOperand(2),
11508                        DAG.getConstant(Cnt, dl, MVT::i32));
11509   }
11510 
11511   case Intrinsic::arm_neon_vqrshifts:
11512   case Intrinsic::arm_neon_vqrshiftu:
11513     // No immediate versions of these to check for.
11514     break;
11515   }
11516 
11517   return SDValue();
11518 }
11519 
11520 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11521 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11522 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11523 /// vector element shift counts are generally not legal, and it is hard to see
11524 /// their values after they get legalized to loads from a constant pool.
11525 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11526                                    const ARMSubtarget *ST) {
11527   EVT VT = N->getValueType(0);
11528   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11529     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11530     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11531     SDValue N1 = N->getOperand(1);
11532     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11533       SDValue N0 = N->getOperand(0);
11534       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11535           DAG.MaskedValueIsZero(N0.getOperand(0),
11536                                 APInt::getHighBitsSet(32, 16)))
11537         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11538     }
11539   }
11540 
11541   // Nothing to be done for scalar shifts.
11542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11543   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11544     return SDValue();
11545 
11546   assert(ST->hasNEON() && "unexpected vector shift");
11547   int64_t Cnt;
11548 
11549   switch (N->getOpcode()) {
11550   default: llvm_unreachable("unexpected shift opcode");
11551 
11552   case ISD::SHL:
11553     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11554       SDLoc dl(N);
11555       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11556                          DAG.getConstant(Cnt, dl, MVT::i32));
11557     }
11558     break;
11559 
11560   case ISD::SRA:
11561   case ISD::SRL:
11562     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11563       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11564                             ARMISD::VSHRs : ARMISD::VSHRu);
11565       SDLoc dl(N);
11566       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11567                          DAG.getConstant(Cnt, dl, MVT::i32));
11568     }
11569   }
11570   return SDValue();
11571 }
11572 
11573 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11574 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11575 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11576                                     const ARMSubtarget *ST) {
11577   SDValue N0 = N->getOperand(0);
11578 
11579   // Check for sign- and zero-extensions of vector extract operations of 8-
11580   // and 16-bit vector elements.  NEON supports these directly.  They are
11581   // handled during DAG combining because type legalization will promote them
11582   // to 32-bit types and it is messy to recognize the operations after that.
11583   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11584     SDValue Vec = N0.getOperand(0);
11585     SDValue Lane = N0.getOperand(1);
11586     EVT VT = N->getValueType(0);
11587     EVT EltVT = N0.getValueType();
11588     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11589 
11590     if (VT == MVT::i32 &&
11591         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11592         TLI.isTypeLegal(Vec.getValueType()) &&
11593         isa<ConstantSDNode>(Lane)) {
11594 
11595       unsigned Opc = 0;
11596       switch (N->getOpcode()) {
11597       default: llvm_unreachable("unexpected opcode");
11598       case ISD::SIGN_EXTEND:
11599         Opc = ARMISD::VGETLANEs;
11600         break;
11601       case ISD::ZERO_EXTEND:
11602       case ISD::ANY_EXTEND:
11603         Opc = ARMISD::VGETLANEu;
11604         break;
11605       }
11606       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11607     }
11608   }
11609 
11610   return SDValue();
11611 }
11612 
11613 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
11614                              APInt &KnownOne) {
11615   if (Op.getOpcode() == ARMISD::BFI) {
11616     // Conservatively, we can recurse down the first operand
11617     // and just mask out all affected bits.
11618     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
11619 
11620     // The operand to BFI is already a mask suitable for removing the bits it
11621     // sets.
11622     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
11623     const APInt &Mask = CI->getAPIntValue();
11624     KnownZero &= Mask;
11625     KnownOne &= Mask;
11626     return;
11627   }
11628   if (Op.getOpcode() == ARMISD::CMOV) {
11629     APInt KZ2(KnownZero.getBitWidth(), 0);
11630     APInt KO2(KnownOne.getBitWidth(), 0);
11631     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
11632     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
11633 
11634     KnownZero &= KZ2;
11635     KnownOne &= KO2;
11636     return;
11637   }
11638   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
11639 }
11640 
11641 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11642   // If we have a CMOV, OR and AND combination such as:
11643   //   if (x & CN)
11644   //     y |= CM;
11645   //
11646   // And:
11647   //   * CN is a single bit;
11648   //   * All bits covered by CM are known zero in y
11649   //
11650   // Then we can convert this into a sequence of BFI instructions. This will
11651   // always be a win if CM is a single bit, will always be no worse than the
11652   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11653   // three bits (due to the extra IT instruction).
11654 
11655   SDValue Op0 = CMOV->getOperand(0);
11656   SDValue Op1 = CMOV->getOperand(1);
11657   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11658   auto CC = CCNode->getAPIntValue().getLimitedValue();
11659   SDValue CmpZ = CMOV->getOperand(4);
11660 
11661   // The compare must be against zero.
11662   if (!isNullConstant(CmpZ->getOperand(1)))
11663     return SDValue();
11664 
11665   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11666   SDValue And = CmpZ->getOperand(0);
11667   if (And->getOpcode() != ISD::AND)
11668     return SDValue();
11669   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11670   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11671     return SDValue();
11672   SDValue X = And->getOperand(0);
11673 
11674   if (CC == ARMCC::EQ) {
11675     // We're performing an "equal to zero" compare. Swap the operands so we
11676     // canonicalize on a "not equal to zero" compare.
11677     std::swap(Op0, Op1);
11678   } else {
11679     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11680   }
11681 
11682   if (Op1->getOpcode() != ISD::OR)
11683     return SDValue();
11684 
11685   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11686   if (!OrC)
11687     return SDValue();
11688   SDValue Y = Op1->getOperand(0);
11689 
11690   if (Op0 != Y)
11691     return SDValue();
11692 
11693   // Now, is it profitable to continue?
11694   APInt OrCI = OrC->getAPIntValue();
11695   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11696   if (OrCI.countPopulation() > Heuristic)
11697     return SDValue();
11698 
11699   // Lastly, can we determine that the bits defined by OrCI
11700   // are zero in Y?
11701   APInt KnownZero, KnownOne;
11702   computeKnownBits(DAG, Y, KnownZero, KnownOne);
11703   if ((OrCI & KnownZero) != OrCI)
11704     return SDValue();
11705 
11706   // OK, we can do the combine.
11707   SDValue V = Y;
11708   SDLoc dl(X);
11709   EVT VT = X.getValueType();
11710   unsigned BitInX = AndC->getAPIntValue().logBase2();
11711 
11712   if (BitInX != 0) {
11713     // We must shift X first.
11714     X = DAG.getNode(ISD::SRL, dl, VT, X,
11715                     DAG.getConstant(BitInX, dl, VT));
11716   }
11717 
11718   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11719        BitInY < NumActiveBits; ++BitInY) {
11720     if (OrCI[BitInY] == 0)
11721       continue;
11722     APInt Mask(VT.getSizeInBits(), 0);
11723     Mask.setBit(BitInY);
11724     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11725                     // Confusingly, the operand is an *inverted* mask.
11726                     DAG.getConstant(~Mask, dl, VT));
11727   }
11728 
11729   return V;
11730 }
11731 
11732 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11733 SDValue
11734 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11735   SDValue Cmp = N->getOperand(4);
11736   if (Cmp.getOpcode() != ARMISD::CMPZ)
11737     // Only looking at NE cases.
11738     return SDValue();
11739 
11740   EVT VT = N->getValueType(0);
11741   SDLoc dl(N);
11742   SDValue LHS = Cmp.getOperand(0);
11743   SDValue RHS = Cmp.getOperand(1);
11744   SDValue Chain = N->getOperand(0);
11745   SDValue BB = N->getOperand(1);
11746   SDValue ARMcc = N->getOperand(2);
11747   ARMCC::CondCodes CC =
11748     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11749 
11750   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11751   // -> (brcond Chain BB CC CPSR Cmp)
11752   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11753       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11754       LHS->getOperand(0)->hasOneUse()) {
11755     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11756     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11757     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11758     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11759     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11760         (LHS01C && LHS01C->getZExtValue() == 1) &&
11761         (LHS1C && LHS1C->getZExtValue() == 1) &&
11762         (RHSC && RHSC->getZExtValue() == 0)) {
11763       return DAG.getNode(
11764           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11765           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11766     }
11767   }
11768 
11769   return SDValue();
11770 }
11771 
11772 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11773 SDValue
11774 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11775   SDValue Cmp = N->getOperand(4);
11776   if (Cmp.getOpcode() != ARMISD::CMPZ)
11777     // Only looking at EQ and NE cases.
11778     return SDValue();
11779 
11780   EVT VT = N->getValueType(0);
11781   SDLoc dl(N);
11782   SDValue LHS = Cmp.getOperand(0);
11783   SDValue RHS = Cmp.getOperand(1);
11784   SDValue FalseVal = N->getOperand(0);
11785   SDValue TrueVal = N->getOperand(1);
11786   SDValue ARMcc = N->getOperand(2);
11787   ARMCC::CondCodes CC =
11788     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11789 
11790   // BFI is only available on V6T2+.
11791   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11792     SDValue R = PerformCMOVToBFICombine(N, DAG);
11793     if (R)
11794       return R;
11795   }
11796 
11797   // Simplify
11798   //   mov     r1, r0
11799   //   cmp     r1, x
11800   //   mov     r0, y
11801   //   moveq   r0, x
11802   // to
11803   //   cmp     r0, x
11804   //   movne   r0, y
11805   //
11806   //   mov     r1, r0
11807   //   cmp     r1, x
11808   //   mov     r0, x
11809   //   movne   r0, y
11810   // to
11811   //   cmp     r0, x
11812   //   movne   r0, y
11813   /// FIXME: Turn this into a target neutral optimization?
11814   SDValue Res;
11815   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11816     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11817                       N->getOperand(3), Cmp);
11818   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11819     SDValue ARMcc;
11820     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11821     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11822                       N->getOperand(3), NewCmp);
11823   }
11824 
11825   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11826   // -> (cmov F T CC CPSR Cmp)
11827   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11828     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11829     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11830     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11831     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11832         (LHS1C && LHS1C->getZExtValue() == 1) &&
11833         (RHSC && RHSC->getZExtValue() == 0)) {
11834       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11835                          LHS->getOperand(2), LHS->getOperand(3),
11836                          LHS->getOperand(4));
11837     }
11838   }
11839 
11840   if (Res.getNode()) {
11841     APInt KnownZero, KnownOne;
11842     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11843     // Capture demanded bits information that would be otherwise lost.
11844     if (KnownZero == 0xfffffffe)
11845       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11846                         DAG.getValueType(MVT::i1));
11847     else if (KnownZero == 0xffffff00)
11848       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11849                         DAG.getValueType(MVT::i8));
11850     else if (KnownZero == 0xffff0000)
11851       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11852                         DAG.getValueType(MVT::i16));
11853   }
11854 
11855   return Res;
11856 }
11857 
11858 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11859                                              DAGCombinerInfo &DCI) const {
11860   switch (N->getOpcode()) {
11861   default: break;
11862   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
11863   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
11864   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11865   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11866   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11867   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11868   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11869   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11870   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11871   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11872   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11873   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11874   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11875   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11876   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11877   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11878   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
11879   case ISD::FP_TO_SINT:
11880   case ISD::FP_TO_UINT:
11881     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11882   case ISD::FDIV:
11883     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11884   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11885   case ISD::SHL:
11886   case ISD::SRA:
11887   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11888   case ISD::SIGN_EXTEND:
11889   case ISD::ZERO_EXTEND:
11890   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11891   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11892   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11893   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11894   case ARMISD::VLD1DUP:
11895   case ARMISD::VLD2DUP:
11896   case ARMISD::VLD3DUP:
11897   case ARMISD::VLD4DUP:
11898     return PerformVLDCombine(N, DCI);
11899   case ARMISD::BUILD_VECTOR:
11900     return PerformARMBUILD_VECTORCombine(N, DCI);
11901   case ARMISD::SMULWB: {
11902     unsigned BitWidth = N->getValueType(0).getSizeInBits();
11903     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
11904     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
11905       return SDValue();
11906     break;
11907   }
11908   case ARMISD::SMULWT: {
11909     unsigned BitWidth = N->getValueType(0).getSizeInBits();
11910     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
11911     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
11912       return SDValue();
11913     break;
11914   }
11915   case ARMISD::SMLALBB: {
11916     unsigned BitWidth = N->getValueType(0).getSizeInBits();
11917     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
11918     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
11919         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
11920       return SDValue();
11921     break;
11922   }
11923   case ARMISD::SMLALBT: {
11924     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
11925     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
11926     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
11927     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
11928     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
11929         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
11930       return SDValue();
11931     break;
11932   }
11933   case ARMISD::SMLALTB: {
11934     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
11935     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
11936     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
11937     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
11938     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
11939         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
11940       return SDValue();
11941     break;
11942   }
11943   case ARMISD::SMLALTT: {
11944     unsigned BitWidth = N->getValueType(0).getSizeInBits();
11945     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
11946     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
11947         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
11948       return SDValue();
11949     break;
11950   }
11951   case ISD::INTRINSIC_VOID:
11952   case ISD::INTRINSIC_W_CHAIN:
11953     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11954     case Intrinsic::arm_neon_vld1:
11955     case Intrinsic::arm_neon_vld2:
11956     case Intrinsic::arm_neon_vld3:
11957     case Intrinsic::arm_neon_vld4:
11958     case Intrinsic::arm_neon_vld2lane:
11959     case Intrinsic::arm_neon_vld3lane:
11960     case Intrinsic::arm_neon_vld4lane:
11961     case Intrinsic::arm_neon_vst1:
11962     case Intrinsic::arm_neon_vst2:
11963     case Intrinsic::arm_neon_vst3:
11964     case Intrinsic::arm_neon_vst4:
11965     case Intrinsic::arm_neon_vst2lane:
11966     case Intrinsic::arm_neon_vst3lane:
11967     case Intrinsic::arm_neon_vst4lane:
11968       return PerformVLDCombine(N, DCI);
11969     default: break;
11970     }
11971     break;
11972   }
11973   return SDValue();
11974 }
11975 
11976 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
11977                                                           EVT VT) const {
11978   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
11979 }
11980 
11981 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11982                                                        unsigned,
11983                                                        unsigned,
11984                                                        bool *Fast) const {
11985   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
11986   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
11987 
11988   switch (VT.getSimpleVT().SimpleTy) {
11989   default:
11990     return false;
11991   case MVT::i8:
11992   case MVT::i16:
11993   case MVT::i32: {
11994     // Unaligned access can use (for example) LRDB, LRDH, LDR
11995     if (AllowsUnaligned) {
11996       if (Fast)
11997         *Fast = Subtarget->hasV7Ops();
11998       return true;
11999     }
12000     return false;
12001   }
12002   case MVT::f64:
12003   case MVT::v2f64: {
12004     // For any little-endian targets with neon, we can support unaligned ld/st
12005     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12006     // A big-endian target may also explicitly support unaligned accesses
12007     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12008       if (Fast)
12009         *Fast = true;
12010       return true;
12011     }
12012     return false;
12013   }
12014   }
12015 }
12016 
12017 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12018                        unsigned AlignCheck) {
12019   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12020           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12021 }
12022 
12023 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12024                                            unsigned DstAlign, unsigned SrcAlign,
12025                                            bool IsMemset, bool ZeroMemset,
12026                                            bool MemcpyStrSrc,
12027                                            MachineFunction &MF) const {
12028   const Function *F = MF.getFunction();
12029 
12030   // See if we can use NEON instructions for this...
12031   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12032       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12033     bool Fast;
12034     if (Size >= 16 &&
12035         (memOpAlign(SrcAlign, DstAlign, 16) ||
12036          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12037       return MVT::v2f64;
12038     } else if (Size >= 8 &&
12039                (memOpAlign(SrcAlign, DstAlign, 8) ||
12040                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12041                  Fast))) {
12042       return MVT::f64;
12043     }
12044   }
12045 
12046   // Lowering to i32/i16 if the size permits.
12047   if (Size >= 4)
12048     return MVT::i32;
12049   else if (Size >= 2)
12050     return MVT::i16;
12051 
12052   // Let the target-independent logic figure it out.
12053   return MVT::Other;
12054 }
12055 
12056 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12057   if (Val.getOpcode() != ISD::LOAD)
12058     return false;
12059 
12060   EVT VT1 = Val.getValueType();
12061   if (!VT1.isSimple() || !VT1.isInteger() ||
12062       !VT2.isSimple() || !VT2.isInteger())
12063     return false;
12064 
12065   switch (VT1.getSimpleVT().SimpleTy) {
12066   default: break;
12067   case MVT::i1:
12068   case MVT::i8:
12069   case MVT::i16:
12070     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12071     return true;
12072   }
12073 
12074   return false;
12075 }
12076 
12077 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12078   EVT VT = ExtVal.getValueType();
12079 
12080   if (!isTypeLegal(VT))
12081     return false;
12082 
12083   // Don't create a loadext if we can fold the extension into a wide/long
12084   // instruction.
12085   // If there's more than one user instruction, the loadext is desirable no
12086   // matter what.  There can be two uses by the same instruction.
12087   if (ExtVal->use_empty() ||
12088       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12089     return true;
12090 
12091   SDNode *U = *ExtVal->use_begin();
12092   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12093        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12094     return false;
12095 
12096   return true;
12097 }
12098 
12099 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12100   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12101     return false;
12102 
12103   if (!isTypeLegal(EVT::getEVT(Ty1)))
12104     return false;
12105 
12106   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12107 
12108   // Assuming the caller doesn't have a zeroext or signext return parameter,
12109   // truncation all the way down to i1 is valid.
12110   return true;
12111 }
12112 
12113 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12114                                                 const AddrMode &AM, Type *Ty,
12115                                                 unsigned AS) const {
12116   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12117     if (Subtarget->hasFPAO())
12118       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12119     return 0;
12120   }
12121   return -1;
12122 }
12123 
12124 
12125 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12126   if (V < 0)
12127     return false;
12128 
12129   unsigned Scale = 1;
12130   switch (VT.getSimpleVT().SimpleTy) {
12131   default: return false;
12132   case MVT::i1:
12133   case MVT::i8:
12134     // Scale == 1;
12135     break;
12136   case MVT::i16:
12137     // Scale == 2;
12138     Scale = 2;
12139     break;
12140   case MVT::i32:
12141     // Scale == 4;
12142     Scale = 4;
12143     break;
12144   }
12145 
12146   if ((V & (Scale - 1)) != 0)
12147     return false;
12148   V /= Scale;
12149   return V == (V & ((1LL << 5) - 1));
12150 }
12151 
12152 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12153                                       const ARMSubtarget *Subtarget) {
12154   bool isNeg = false;
12155   if (V < 0) {
12156     isNeg = true;
12157     V = - V;
12158   }
12159 
12160   switch (VT.getSimpleVT().SimpleTy) {
12161   default: return false;
12162   case MVT::i1:
12163   case MVT::i8:
12164   case MVT::i16:
12165   case MVT::i32:
12166     // + imm12 or - imm8
12167     if (isNeg)
12168       return V == (V & ((1LL << 8) - 1));
12169     return V == (V & ((1LL << 12) - 1));
12170   case MVT::f32:
12171   case MVT::f64:
12172     // Same as ARM mode. FIXME: NEON?
12173     if (!Subtarget->hasVFP2())
12174       return false;
12175     if ((V & 3) != 0)
12176       return false;
12177     V >>= 2;
12178     return V == (V & ((1LL << 8) - 1));
12179   }
12180 }
12181 
12182 /// isLegalAddressImmediate - Return true if the integer value can be used
12183 /// as the offset of the target addressing mode for load / store of the
12184 /// given type.
12185 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12186                                     const ARMSubtarget *Subtarget) {
12187   if (V == 0)
12188     return true;
12189 
12190   if (!VT.isSimple())
12191     return false;
12192 
12193   if (Subtarget->isThumb1Only())
12194     return isLegalT1AddressImmediate(V, VT);
12195   else if (Subtarget->isThumb2())
12196     return isLegalT2AddressImmediate(V, VT, Subtarget);
12197 
12198   // ARM mode.
12199   if (V < 0)
12200     V = - V;
12201   switch (VT.getSimpleVT().SimpleTy) {
12202   default: return false;
12203   case MVT::i1:
12204   case MVT::i8:
12205   case MVT::i32:
12206     // +- imm12
12207     return V == (V & ((1LL << 12) - 1));
12208   case MVT::i16:
12209     // +- imm8
12210     return V == (V & ((1LL << 8) - 1));
12211   case MVT::f32:
12212   case MVT::f64:
12213     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12214       return false;
12215     if ((V & 3) != 0)
12216       return false;
12217     V >>= 2;
12218     return V == (V & ((1LL << 8) - 1));
12219   }
12220 }
12221 
12222 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12223                                                       EVT VT) const {
12224   int Scale = AM.Scale;
12225   if (Scale < 0)
12226     return false;
12227 
12228   switch (VT.getSimpleVT().SimpleTy) {
12229   default: return false;
12230   case MVT::i1:
12231   case MVT::i8:
12232   case MVT::i16:
12233   case MVT::i32:
12234     if (Scale == 1)
12235       return true;
12236     // r + r << imm
12237     Scale = Scale & ~1;
12238     return Scale == 2 || Scale == 4 || Scale == 8;
12239   case MVT::i64:
12240     // r + r
12241     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12242       return true;
12243     return false;
12244   case MVT::isVoid:
12245     // Note, we allow "void" uses (basically, uses that aren't loads or
12246     // stores), because arm allows folding a scale into many arithmetic
12247     // operations.  This should be made more precise and revisited later.
12248 
12249     // Allow r << imm, but the imm has to be a multiple of two.
12250     if (Scale & 1) return false;
12251     return isPowerOf2_32(Scale);
12252   }
12253 }
12254 
12255 /// isLegalAddressingMode - Return true if the addressing mode represented
12256 /// by AM is legal for this target, for a load/store of the specified type.
12257 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12258                                               const AddrMode &AM, Type *Ty,
12259                                               unsigned AS) const {
12260   EVT VT = getValueType(DL, Ty, true);
12261   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12262     return false;
12263 
12264   // Can never fold addr of global into load/store.
12265   if (AM.BaseGV)
12266     return false;
12267 
12268   switch (AM.Scale) {
12269   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12270     break;
12271   case 1:
12272     if (Subtarget->isThumb1Only())
12273       return false;
12274     LLVM_FALLTHROUGH;
12275   default:
12276     // ARM doesn't support any R+R*scale+imm addr modes.
12277     if (AM.BaseOffs)
12278       return false;
12279 
12280     if (!VT.isSimple())
12281       return false;
12282 
12283     if (Subtarget->isThumb2())
12284       return isLegalT2ScaledAddressingMode(AM, VT);
12285 
12286     int Scale = AM.Scale;
12287     switch (VT.getSimpleVT().SimpleTy) {
12288     default: return false;
12289     case MVT::i1:
12290     case MVT::i8:
12291     case MVT::i32:
12292       if (Scale < 0) Scale = -Scale;
12293       if (Scale == 1)
12294         return true;
12295       // r + r << imm
12296       return isPowerOf2_32(Scale & ~1);
12297     case MVT::i16:
12298     case MVT::i64:
12299       // r + r
12300       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12301         return true;
12302       return false;
12303 
12304     case MVT::isVoid:
12305       // Note, we allow "void" uses (basically, uses that aren't loads or
12306       // stores), because arm allows folding a scale into many arithmetic
12307       // operations.  This should be made more precise and revisited later.
12308 
12309       // Allow r << imm, but the imm has to be a multiple of two.
12310       if (Scale & 1) return false;
12311       return isPowerOf2_32(Scale);
12312     }
12313   }
12314   return true;
12315 }
12316 
12317 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12318 /// icmp immediate, that is the target has icmp instructions which can compare
12319 /// a register against the immediate without having to materialize the
12320 /// immediate into a register.
12321 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12322   // Thumb2 and ARM modes can use cmn for negative immediates.
12323   if (!Subtarget->isThumb())
12324     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12325   if (Subtarget->isThumb2())
12326     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12327   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12328   return Imm >= 0 && Imm <= 255;
12329 }
12330 
12331 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12332 /// *or sub* immediate, that is the target has add or sub instructions which can
12333 /// add a register with the immediate without having to materialize the
12334 /// immediate into a register.
12335 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12336   // Same encoding for add/sub, just flip the sign.
12337   int64_t AbsImm = std::abs(Imm);
12338   if (!Subtarget->isThumb())
12339     return ARM_AM::getSOImmVal(AbsImm) != -1;
12340   if (Subtarget->isThumb2())
12341     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12342   // Thumb1 only has 8-bit unsigned immediate.
12343   return AbsImm >= 0 && AbsImm <= 255;
12344 }
12345 
12346 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12347                                       bool isSEXTLoad, SDValue &Base,
12348                                       SDValue &Offset, bool &isInc,
12349                                       SelectionDAG &DAG) {
12350   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12351     return false;
12352 
12353   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12354     // AddressingMode 3
12355     Base = Ptr->getOperand(0);
12356     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12357       int RHSC = (int)RHS->getZExtValue();
12358       if (RHSC < 0 && RHSC > -256) {
12359         assert(Ptr->getOpcode() == ISD::ADD);
12360         isInc = false;
12361         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12362         return true;
12363       }
12364     }
12365     isInc = (Ptr->getOpcode() == ISD::ADD);
12366     Offset = Ptr->getOperand(1);
12367     return true;
12368   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12369     // AddressingMode 2
12370     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12371       int RHSC = (int)RHS->getZExtValue();
12372       if (RHSC < 0 && RHSC > -0x1000) {
12373         assert(Ptr->getOpcode() == ISD::ADD);
12374         isInc = false;
12375         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12376         Base = Ptr->getOperand(0);
12377         return true;
12378       }
12379     }
12380 
12381     if (Ptr->getOpcode() == ISD::ADD) {
12382       isInc = true;
12383       ARM_AM::ShiftOpc ShOpcVal=
12384         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12385       if (ShOpcVal != ARM_AM::no_shift) {
12386         Base = Ptr->getOperand(1);
12387         Offset = Ptr->getOperand(0);
12388       } else {
12389         Base = Ptr->getOperand(0);
12390         Offset = Ptr->getOperand(1);
12391       }
12392       return true;
12393     }
12394 
12395     isInc = (Ptr->getOpcode() == ISD::ADD);
12396     Base = Ptr->getOperand(0);
12397     Offset = Ptr->getOperand(1);
12398     return true;
12399   }
12400 
12401   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12402   return false;
12403 }
12404 
12405 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12406                                      bool isSEXTLoad, SDValue &Base,
12407                                      SDValue &Offset, bool &isInc,
12408                                      SelectionDAG &DAG) {
12409   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12410     return false;
12411 
12412   Base = Ptr->getOperand(0);
12413   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12414     int RHSC = (int)RHS->getZExtValue();
12415     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12416       assert(Ptr->getOpcode() == ISD::ADD);
12417       isInc = false;
12418       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12419       return true;
12420     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12421       isInc = Ptr->getOpcode() == ISD::ADD;
12422       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12423       return true;
12424     }
12425   }
12426 
12427   return false;
12428 }
12429 
12430 /// getPreIndexedAddressParts - returns true by value, base pointer and
12431 /// offset pointer and addressing mode by reference if the node's address
12432 /// can be legally represented as pre-indexed load / store address.
12433 bool
12434 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12435                                              SDValue &Offset,
12436                                              ISD::MemIndexedMode &AM,
12437                                              SelectionDAG &DAG) const {
12438   if (Subtarget->isThumb1Only())
12439     return false;
12440 
12441   EVT VT;
12442   SDValue Ptr;
12443   bool isSEXTLoad = false;
12444   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12445     Ptr = LD->getBasePtr();
12446     VT  = LD->getMemoryVT();
12447     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12448   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12449     Ptr = ST->getBasePtr();
12450     VT  = ST->getMemoryVT();
12451   } else
12452     return false;
12453 
12454   bool isInc;
12455   bool isLegal = false;
12456   if (Subtarget->isThumb2())
12457     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12458                                        Offset, isInc, DAG);
12459   else
12460     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12461                                         Offset, isInc, DAG);
12462   if (!isLegal)
12463     return false;
12464 
12465   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12466   return true;
12467 }
12468 
12469 /// getPostIndexedAddressParts - returns true by value, base pointer and
12470 /// offset pointer and addressing mode by reference if this node can be
12471 /// combined with a load / store to form a post-indexed load / store.
12472 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12473                                                    SDValue &Base,
12474                                                    SDValue &Offset,
12475                                                    ISD::MemIndexedMode &AM,
12476                                                    SelectionDAG &DAG) const {
12477   EVT VT;
12478   SDValue Ptr;
12479   bool isSEXTLoad = false, isNonExt;
12480   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12481     VT  = LD->getMemoryVT();
12482     Ptr = LD->getBasePtr();
12483     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12484     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12485   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12486     VT  = ST->getMemoryVT();
12487     Ptr = ST->getBasePtr();
12488     isNonExt = !ST->isTruncatingStore();
12489   } else
12490     return false;
12491 
12492   if (Subtarget->isThumb1Only()) {
12493     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12494     // must be non-extending/truncating, i32, with an offset of 4.
12495     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12496     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12497       return false;
12498     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12499     if (!RHS || RHS->getZExtValue() != 4)
12500       return false;
12501 
12502     Offset = Op->getOperand(1);
12503     Base = Op->getOperand(0);
12504     AM = ISD::POST_INC;
12505     return true;
12506   }
12507 
12508   bool isInc;
12509   bool isLegal = false;
12510   if (Subtarget->isThumb2())
12511     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12512                                        isInc, DAG);
12513   else
12514     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12515                                         isInc, DAG);
12516   if (!isLegal)
12517     return false;
12518 
12519   if (Ptr != Base) {
12520     // Swap base ptr and offset to catch more post-index load / store when
12521     // it's legal. In Thumb2 mode, offset must be an immediate.
12522     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12523         !Subtarget->isThumb2())
12524       std::swap(Base, Offset);
12525 
12526     // Post-indexed load / store update the base pointer.
12527     if (Ptr != Base)
12528       return false;
12529   }
12530 
12531   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12532   return true;
12533 }
12534 
12535 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12536                                                       APInt &KnownZero,
12537                                                       APInt &KnownOne,
12538                                                       const SelectionDAG &DAG,
12539                                                       unsigned Depth) const {
12540   unsigned BitWidth = KnownOne.getBitWidth();
12541   KnownZero = KnownOne = APInt(BitWidth, 0);
12542   switch (Op.getOpcode()) {
12543   default: break;
12544   case ARMISD::ADDC:
12545   case ARMISD::ADDE:
12546   case ARMISD::SUBC:
12547   case ARMISD::SUBE:
12548     // These nodes' second result is a boolean
12549     if (Op.getResNo() == 0)
12550       break;
12551     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12552     break;
12553   case ARMISD::CMOV: {
12554     // Bits are known zero/one if known on the LHS and RHS.
12555     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
12556     if (KnownZero == 0 && KnownOne == 0) return;
12557 
12558     APInt KnownZeroRHS, KnownOneRHS;
12559     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
12560     KnownZero &= KnownZeroRHS;
12561     KnownOne  &= KnownOneRHS;
12562     return;
12563   }
12564   case ISD::INTRINSIC_W_CHAIN: {
12565     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12566     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12567     switch (IntID) {
12568     default: return;
12569     case Intrinsic::arm_ldaex:
12570     case Intrinsic::arm_ldrex: {
12571       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12572       unsigned MemBits = VT.getScalarSizeInBits();
12573       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12574       return;
12575     }
12576     }
12577   }
12578   }
12579 }
12580 
12581 //===----------------------------------------------------------------------===//
12582 //                           ARM Inline Assembly Support
12583 //===----------------------------------------------------------------------===//
12584 
12585 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12586   // Looking for "rev" which is V6+.
12587   if (!Subtarget->hasV6Ops())
12588     return false;
12589 
12590   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12591   std::string AsmStr = IA->getAsmString();
12592   SmallVector<StringRef, 4> AsmPieces;
12593   SplitString(AsmStr, AsmPieces, ";\n");
12594 
12595   switch (AsmPieces.size()) {
12596   default: return false;
12597   case 1:
12598     AsmStr = AsmPieces[0];
12599     AsmPieces.clear();
12600     SplitString(AsmStr, AsmPieces, " \t,");
12601 
12602     // rev $0, $1
12603     if (AsmPieces.size() == 3 &&
12604         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12605         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12606       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12607       if (Ty && Ty->getBitWidth() == 32)
12608         return IntrinsicLowering::LowerToByteSwap(CI);
12609     }
12610     break;
12611   }
12612 
12613   return false;
12614 }
12615 
12616 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12617   // At this point, we have to lower this constraint to something else, so we
12618   // lower it to an "r" or "w". However, by doing this we will force the result
12619   // to be in register, while the X constraint is much more permissive.
12620   //
12621   // Although we are correct (we are free to emit anything, without
12622   // constraints), we might break use cases that would expect us to be more
12623   // efficient and emit something else.
12624   if (!Subtarget->hasVFP2())
12625     return "r";
12626   if (ConstraintVT.isFloatingPoint())
12627     return "w";
12628   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12629      (ConstraintVT.getSizeInBits() == 64 ||
12630       ConstraintVT.getSizeInBits() == 128))
12631     return "w";
12632 
12633   return "r";
12634 }
12635 
12636 /// getConstraintType - Given a constraint letter, return the type of
12637 /// constraint it is for this target.
12638 ARMTargetLowering::ConstraintType
12639 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12640   if (Constraint.size() == 1) {
12641     switch (Constraint[0]) {
12642     default:  break;
12643     case 'l': return C_RegisterClass;
12644     case 'w': return C_RegisterClass;
12645     case 'h': return C_RegisterClass;
12646     case 'x': return C_RegisterClass;
12647     case 't': return C_RegisterClass;
12648     case 'j': return C_Other; // Constant for movw.
12649       // An address with a single base register. Due to the way we
12650       // currently handle addresses it is the same as an 'r' memory constraint.
12651     case 'Q': return C_Memory;
12652     }
12653   } else if (Constraint.size() == 2) {
12654     switch (Constraint[0]) {
12655     default: break;
12656     // All 'U+' constraints are addresses.
12657     case 'U': return C_Memory;
12658     }
12659   }
12660   return TargetLowering::getConstraintType(Constraint);
12661 }
12662 
12663 /// Examine constraint type and operand type and determine a weight value.
12664 /// This object must already have been set up with the operand type
12665 /// and the current alternative constraint selected.
12666 TargetLowering::ConstraintWeight
12667 ARMTargetLowering::getSingleConstraintMatchWeight(
12668     AsmOperandInfo &info, const char *constraint) const {
12669   ConstraintWeight weight = CW_Invalid;
12670   Value *CallOperandVal = info.CallOperandVal;
12671     // If we don't have a value, we can't do a match,
12672     // but allow it at the lowest weight.
12673   if (!CallOperandVal)
12674     return CW_Default;
12675   Type *type = CallOperandVal->getType();
12676   // Look at the constraint type.
12677   switch (*constraint) {
12678   default:
12679     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12680     break;
12681   case 'l':
12682     if (type->isIntegerTy()) {
12683       if (Subtarget->isThumb())
12684         weight = CW_SpecificReg;
12685       else
12686         weight = CW_Register;
12687     }
12688     break;
12689   case 'w':
12690     if (type->isFloatingPointTy())
12691       weight = CW_Register;
12692     break;
12693   }
12694   return weight;
12695 }
12696 
12697 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12698 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12699     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12700   if (Constraint.size() == 1) {
12701     // GCC ARM Constraint Letters
12702     switch (Constraint[0]) {
12703     case 'l': // Low regs or general regs.
12704       if (Subtarget->isThumb())
12705         return RCPair(0U, &ARM::tGPRRegClass);
12706       return RCPair(0U, &ARM::GPRRegClass);
12707     case 'h': // High regs or no regs.
12708       if (Subtarget->isThumb())
12709         return RCPair(0U, &ARM::hGPRRegClass);
12710       break;
12711     case 'r':
12712       if (Subtarget->isThumb1Only())
12713         return RCPair(0U, &ARM::tGPRRegClass);
12714       return RCPair(0U, &ARM::GPRRegClass);
12715     case 'w':
12716       if (VT == MVT::Other)
12717         break;
12718       if (VT == MVT::f32)
12719         return RCPair(0U, &ARM::SPRRegClass);
12720       if (VT.getSizeInBits() == 64)
12721         return RCPair(0U, &ARM::DPRRegClass);
12722       if (VT.getSizeInBits() == 128)
12723         return RCPair(0U, &ARM::QPRRegClass);
12724       break;
12725     case 'x':
12726       if (VT == MVT::Other)
12727         break;
12728       if (VT == MVT::f32)
12729         return RCPair(0U, &ARM::SPR_8RegClass);
12730       if (VT.getSizeInBits() == 64)
12731         return RCPair(0U, &ARM::DPR_8RegClass);
12732       if (VT.getSizeInBits() == 128)
12733         return RCPair(0U, &ARM::QPR_8RegClass);
12734       break;
12735     case 't':
12736       if (VT == MVT::f32)
12737         return RCPair(0U, &ARM::SPRRegClass);
12738       break;
12739     }
12740   }
12741   if (StringRef("{cc}").equals_lower(Constraint))
12742     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12743 
12744   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12745 }
12746 
12747 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12748 /// vector.  If it is invalid, don't add anything to Ops.
12749 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12750                                                      std::string &Constraint,
12751                                                      std::vector<SDValue>&Ops,
12752                                                      SelectionDAG &DAG) const {
12753   SDValue Result;
12754 
12755   // Currently only support length 1 constraints.
12756   if (Constraint.length() != 1) return;
12757 
12758   char ConstraintLetter = Constraint[0];
12759   switch (ConstraintLetter) {
12760   default: break;
12761   case 'j':
12762   case 'I': case 'J': case 'K': case 'L':
12763   case 'M': case 'N': case 'O':
12764     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12765     if (!C)
12766       return;
12767 
12768     int64_t CVal64 = C->getSExtValue();
12769     int CVal = (int) CVal64;
12770     // None of these constraints allow values larger than 32 bits.  Check
12771     // that the value fits in an int.
12772     if (CVal != CVal64)
12773       return;
12774 
12775     switch (ConstraintLetter) {
12776       case 'j':
12777         // Constant suitable for movw, must be between 0 and
12778         // 65535.
12779         if (Subtarget->hasV6T2Ops())
12780           if (CVal >= 0 && CVal <= 65535)
12781             break;
12782         return;
12783       case 'I':
12784         if (Subtarget->isThumb1Only()) {
12785           // This must be a constant between 0 and 255, for ADD
12786           // immediates.
12787           if (CVal >= 0 && CVal <= 255)
12788             break;
12789         } else if (Subtarget->isThumb2()) {
12790           // A constant that can be used as an immediate value in a
12791           // data-processing instruction.
12792           if (ARM_AM::getT2SOImmVal(CVal) != -1)
12793             break;
12794         } else {
12795           // A constant that can be used as an immediate value in a
12796           // data-processing instruction.
12797           if (ARM_AM::getSOImmVal(CVal) != -1)
12798             break;
12799         }
12800         return;
12801 
12802       case 'J':
12803         if (Subtarget->isThumb1Only()) {
12804           // This must be a constant between -255 and -1, for negated ADD
12805           // immediates. This can be used in GCC with an "n" modifier that
12806           // prints the negated value, for use with SUB instructions. It is
12807           // not useful otherwise but is implemented for compatibility.
12808           if (CVal >= -255 && CVal <= -1)
12809             break;
12810         } else {
12811           // This must be a constant between -4095 and 4095. It is not clear
12812           // what this constraint is intended for. Implemented for
12813           // compatibility with GCC.
12814           if (CVal >= -4095 && CVal <= 4095)
12815             break;
12816         }
12817         return;
12818 
12819       case 'K':
12820         if (Subtarget->isThumb1Only()) {
12821           // A 32-bit value where only one byte has a nonzero value. Exclude
12822           // zero to match GCC. This constraint is used by GCC internally for
12823           // constants that can be loaded with a move/shift combination.
12824           // It is not useful otherwise but is implemented for compatibility.
12825           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12826             break;
12827         } else if (Subtarget->isThumb2()) {
12828           // A constant whose bitwise inverse can be used as an immediate
12829           // value in a data-processing instruction. This can be used in GCC
12830           // with a "B" modifier that prints the inverted value, for use with
12831           // BIC and MVN instructions. It is not useful otherwise but is
12832           // implemented for compatibility.
12833           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12834             break;
12835         } else {
12836           // A constant whose bitwise inverse can be used as an immediate
12837           // value in a data-processing instruction. This can be used in GCC
12838           // with a "B" modifier that prints the inverted value, for use with
12839           // BIC and MVN instructions. It is not useful otherwise but is
12840           // implemented for compatibility.
12841           if (ARM_AM::getSOImmVal(~CVal) != -1)
12842             break;
12843         }
12844         return;
12845 
12846       case 'L':
12847         if (Subtarget->isThumb1Only()) {
12848           // This must be a constant between -7 and 7,
12849           // for 3-operand ADD/SUB immediate instructions.
12850           if (CVal >= -7 && CVal < 7)
12851             break;
12852         } else if (Subtarget->isThumb2()) {
12853           // A constant whose negation can be used as an immediate value in a
12854           // data-processing instruction. This can be used in GCC with an "n"
12855           // modifier that prints the negated value, for use with SUB
12856           // instructions. It is not useful otherwise but is implemented for
12857           // compatibility.
12858           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
12859             break;
12860         } else {
12861           // A constant whose negation can be used as an immediate value in a
12862           // data-processing instruction. This can be used in GCC with an "n"
12863           // modifier that prints the negated value, for use with SUB
12864           // instructions. It is not useful otherwise but is implemented for
12865           // compatibility.
12866           if (ARM_AM::getSOImmVal(-CVal) != -1)
12867             break;
12868         }
12869         return;
12870 
12871       case 'M':
12872         if (Subtarget->isThumb1Only()) {
12873           // This must be a multiple of 4 between 0 and 1020, for
12874           // ADD sp + immediate.
12875           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
12876             break;
12877         } else {
12878           // A power of two or a constant between 0 and 32.  This is used in
12879           // GCC for the shift amount on shifted register operands, but it is
12880           // useful in general for any shift amounts.
12881           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12882             break;
12883         }
12884         return;
12885 
12886       case 'N':
12887         if (Subtarget->isThumb()) {  // FIXME thumb2
12888           // This must be a constant between 0 and 31, for shift amounts.
12889           if (CVal >= 0 && CVal <= 31)
12890             break;
12891         }
12892         return;
12893 
12894       case 'O':
12895         if (Subtarget->isThumb()) {  // FIXME thumb2
12896           // This must be a multiple of 4 between -508 and 508, for
12897           // ADD/SUB sp = sp + immediate.
12898           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12899             break;
12900         }
12901         return;
12902     }
12903     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12904     break;
12905   }
12906 
12907   if (Result.getNode()) {
12908     Ops.push_back(Result);
12909     return;
12910   }
12911   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12912 }
12913 
12914 static RTLIB::Libcall getDivRemLibcall(
12915     const SDNode *N, MVT::SimpleValueType SVT) {
12916   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12917           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12918          "Unhandled Opcode in getDivRemLibcall");
12919   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12920                   N->getOpcode() == ISD::SREM;
12921   RTLIB::Libcall LC;
12922   switch (SVT) {
12923   default: llvm_unreachable("Unexpected request for libcall!");
12924   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
12925   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
12926   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
12927   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
12928   }
12929   return LC;
12930 }
12931 
12932 static TargetLowering::ArgListTy getDivRemArgList(
12933     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
12934   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12935           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12936          "Unhandled Opcode in getDivRemArgList");
12937   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12938                   N->getOpcode() == ISD::SREM;
12939   TargetLowering::ArgListTy Args;
12940   TargetLowering::ArgListEntry Entry;
12941   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12942     EVT ArgVT = N->getOperand(i).getValueType();
12943     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
12944     Entry.Node = N->getOperand(i);
12945     Entry.Ty = ArgTy;
12946     Entry.IsSExt = isSigned;
12947     Entry.IsZExt = !isSigned;
12948     Args.push_back(Entry);
12949   }
12950   if (Subtarget->isTargetWindows() && Args.size() >= 2)
12951     std::swap(Args[0], Args[1]);
12952   return Args;
12953 }
12954 
12955 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
12956   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
12957           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
12958           Subtarget->isTargetWindows()) &&
12959          "Register-based DivRem lowering only");
12960   unsigned Opcode = Op->getOpcode();
12961   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
12962          "Invalid opcode for Div/Rem lowering");
12963   bool isSigned = (Opcode == ISD::SDIVREM);
12964   EVT VT = Op->getValueType(0);
12965   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
12966   SDLoc dl(Op);
12967 
12968   // If the target has hardware divide, use divide + multiply + subtract:
12969   //     div = a / b
12970   //     rem = a - b * div
12971   //     return {div, rem}
12972   // This should be lowered into UDIV/SDIV + MLS later on.
12973   if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() &&
12974       Op->getSimpleValueType(0) == MVT::i32) {
12975     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
12976     const SDValue Dividend = Op->getOperand(0);
12977     const SDValue Divisor = Op->getOperand(1);
12978     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
12979     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
12980     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
12981 
12982     SDValue Values[2] = {Div, Rem};
12983     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
12984   }
12985 
12986   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
12987                                        VT.getSimpleVT().SimpleTy);
12988   SDValue InChain = DAG.getEntryNode();
12989 
12990   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
12991                                                     DAG.getContext(),
12992                                                     Subtarget);
12993 
12994   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12995                                          getPointerTy(DAG.getDataLayout()));
12996 
12997   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
12998 
12999   if (Subtarget->isTargetWindows())
13000     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13001 
13002   TargetLowering::CallLoweringInfo CLI(DAG);
13003   CLI.setDebugLoc(dl).setChain(InChain)
13004     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13005     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13006 
13007   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13008   return CallInfo.first;
13009 }
13010 
13011 // Lowers REM using divmod helpers
13012 // see RTABI section 4.2/4.3
13013 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13014   // Build return types (div and rem)
13015   std::vector<Type*> RetTyParams;
13016   Type *RetTyElement;
13017 
13018   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13019   default: llvm_unreachable("Unexpected request for libcall!");
13020   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13021   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13022   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13023   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13024   }
13025 
13026   RetTyParams.push_back(RetTyElement);
13027   RetTyParams.push_back(RetTyElement);
13028   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13029   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13030 
13031   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13032                                                              SimpleTy);
13033   SDValue InChain = DAG.getEntryNode();
13034   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13035                                                     Subtarget);
13036   bool isSigned = N->getOpcode() == ISD::SREM;
13037   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13038                                          getPointerTy(DAG.getDataLayout()));
13039 
13040   if (Subtarget->isTargetWindows())
13041     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13042 
13043   // Lower call
13044   CallLoweringInfo CLI(DAG);
13045   CLI.setChain(InChain)
13046      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13047      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13048   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13049 
13050   // Return second (rem) result operand (first contains div)
13051   SDNode *ResNode = CallResult.first.getNode();
13052   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13053   return ResNode->getOperand(1);
13054 }
13055 
13056 SDValue
13057 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13058   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13059   SDLoc DL(Op);
13060 
13061   // Get the inputs.
13062   SDValue Chain = Op.getOperand(0);
13063   SDValue Size  = Op.getOperand(1);
13064 
13065   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13066                               DAG.getConstant(2, DL, MVT::i32));
13067 
13068   SDValue Flag;
13069   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13070   Flag = Chain.getValue(1);
13071 
13072   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13073   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13074 
13075   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13076   Chain = NewSP.getValue(1);
13077 
13078   SDValue Ops[2] = { NewSP, Chain };
13079   return DAG.getMergeValues(Ops, DL);
13080 }
13081 
13082 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13083   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13084          "Unexpected type for custom-lowering FP_EXTEND");
13085 
13086   RTLIB::Libcall LC;
13087   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13088 
13089   SDValue SrcVal = Op.getOperand(0);
13090   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13091                      SDLoc(Op)).first;
13092 }
13093 
13094 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13095   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13096          Subtarget->isFPOnlySP() &&
13097          "Unexpected type for custom-lowering FP_ROUND");
13098 
13099   RTLIB::Libcall LC;
13100   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13101 
13102   SDValue SrcVal = Op.getOperand(0);
13103   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13104                      SDLoc(Op)).first;
13105 }
13106 
13107 bool
13108 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13109   // The ARM target isn't yet aware of offsets.
13110   return false;
13111 }
13112 
13113 bool ARM::isBitFieldInvertedMask(unsigned v) {
13114   if (v == 0xffffffff)
13115     return false;
13116 
13117   // there can be 1's on either or both "outsides", all the "inside"
13118   // bits must be 0's
13119   return isShiftedMask_32(~v);
13120 }
13121 
13122 /// isFPImmLegal - Returns true if the target can instruction select the
13123 /// specified FP immediate natively. If false, the legalizer will
13124 /// materialize the FP immediate as a load from a constant pool.
13125 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13126   if (!Subtarget->hasVFP3())
13127     return false;
13128   if (VT == MVT::f32)
13129     return ARM_AM::getFP32Imm(Imm) != -1;
13130   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13131     return ARM_AM::getFP64Imm(Imm) != -1;
13132   return false;
13133 }
13134 
13135 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13136 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13137 /// specified in the intrinsic calls.
13138 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13139                                            const CallInst &I,
13140                                            unsigned Intrinsic) const {
13141   switch (Intrinsic) {
13142   case Intrinsic::arm_neon_vld1:
13143   case Intrinsic::arm_neon_vld2:
13144   case Intrinsic::arm_neon_vld3:
13145   case Intrinsic::arm_neon_vld4:
13146   case Intrinsic::arm_neon_vld2lane:
13147   case Intrinsic::arm_neon_vld3lane:
13148   case Intrinsic::arm_neon_vld4lane: {
13149     Info.opc = ISD::INTRINSIC_W_CHAIN;
13150     // Conservatively set memVT to the entire set of vectors loaded.
13151     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13152     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13153     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13154     Info.ptrVal = I.getArgOperand(0);
13155     Info.offset = 0;
13156     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13157     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13158     Info.vol = false; // volatile loads with NEON intrinsics not supported
13159     Info.readMem = true;
13160     Info.writeMem = false;
13161     return true;
13162   }
13163   case Intrinsic::arm_neon_vst1:
13164   case Intrinsic::arm_neon_vst2:
13165   case Intrinsic::arm_neon_vst3:
13166   case Intrinsic::arm_neon_vst4:
13167   case Intrinsic::arm_neon_vst2lane:
13168   case Intrinsic::arm_neon_vst3lane:
13169   case Intrinsic::arm_neon_vst4lane: {
13170     Info.opc = ISD::INTRINSIC_VOID;
13171     // Conservatively set memVT to the entire set of vectors stored.
13172     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13173     unsigned NumElts = 0;
13174     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13175       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13176       if (!ArgTy->isVectorTy())
13177         break;
13178       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13179     }
13180     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13181     Info.ptrVal = I.getArgOperand(0);
13182     Info.offset = 0;
13183     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13184     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13185     Info.vol = false; // volatile stores with NEON intrinsics not supported
13186     Info.readMem = false;
13187     Info.writeMem = true;
13188     return true;
13189   }
13190   case Intrinsic::arm_ldaex:
13191   case Intrinsic::arm_ldrex: {
13192     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13193     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13194     Info.opc = ISD::INTRINSIC_W_CHAIN;
13195     Info.memVT = MVT::getVT(PtrTy->getElementType());
13196     Info.ptrVal = I.getArgOperand(0);
13197     Info.offset = 0;
13198     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13199     Info.vol = true;
13200     Info.readMem = true;
13201     Info.writeMem = false;
13202     return true;
13203   }
13204   case Intrinsic::arm_stlex:
13205   case Intrinsic::arm_strex: {
13206     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13207     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13208     Info.opc = ISD::INTRINSIC_W_CHAIN;
13209     Info.memVT = MVT::getVT(PtrTy->getElementType());
13210     Info.ptrVal = I.getArgOperand(1);
13211     Info.offset = 0;
13212     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13213     Info.vol = true;
13214     Info.readMem = false;
13215     Info.writeMem = true;
13216     return true;
13217   }
13218   case Intrinsic::arm_stlexd:
13219   case Intrinsic::arm_strexd:
13220     Info.opc = ISD::INTRINSIC_W_CHAIN;
13221     Info.memVT = MVT::i64;
13222     Info.ptrVal = I.getArgOperand(2);
13223     Info.offset = 0;
13224     Info.align = 8;
13225     Info.vol = true;
13226     Info.readMem = false;
13227     Info.writeMem = true;
13228     return true;
13229 
13230   case Intrinsic::arm_ldaexd:
13231   case Intrinsic::arm_ldrexd:
13232     Info.opc = ISD::INTRINSIC_W_CHAIN;
13233     Info.memVT = MVT::i64;
13234     Info.ptrVal = I.getArgOperand(0);
13235     Info.offset = 0;
13236     Info.align = 8;
13237     Info.vol = true;
13238     Info.readMem = true;
13239     Info.writeMem = false;
13240     return true;
13241 
13242   default:
13243     break;
13244   }
13245 
13246   return false;
13247 }
13248 
13249 /// \brief Returns true if it is beneficial to convert a load of a constant
13250 /// to just the constant itself.
13251 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13252                                                           Type *Ty) const {
13253   assert(Ty->isIntegerTy());
13254 
13255   unsigned Bits = Ty->getPrimitiveSizeInBits();
13256   if (Bits == 0 || Bits > 32)
13257     return false;
13258   return true;
13259 }
13260 
13261 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT,
13262                                                 unsigned Index) const {
13263   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13264     return false;
13265 
13266   return (Index == 0 || Index == ResVT.getVectorNumElements());
13267 }
13268 
13269 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13270                                         ARM_MB::MemBOpt Domain) const {
13271   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13272 
13273   // First, if the target has no DMB, see what fallback we can use.
13274   if (!Subtarget->hasDataBarrier()) {
13275     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13276     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13277     // here.
13278     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13279       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13280       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13281                         Builder.getInt32(0), Builder.getInt32(7),
13282                         Builder.getInt32(10), Builder.getInt32(5)};
13283       return Builder.CreateCall(MCR, args);
13284     } else {
13285       // Instead of using barriers, atomic accesses on these subtargets use
13286       // libcalls.
13287       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13288     }
13289   } else {
13290     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13291     // Only a full system barrier exists in the M-class architectures.
13292     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13293     Constant *CDomain = Builder.getInt32(Domain);
13294     return Builder.CreateCall(DMB, CDomain);
13295   }
13296 }
13297 
13298 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13299 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13300                                          AtomicOrdering Ord, bool IsStore,
13301                                          bool IsLoad) const {
13302   switch (Ord) {
13303   case AtomicOrdering::NotAtomic:
13304   case AtomicOrdering::Unordered:
13305     llvm_unreachable("Invalid fence: unordered/non-atomic");
13306   case AtomicOrdering::Monotonic:
13307   case AtomicOrdering::Acquire:
13308     return nullptr; // Nothing to do
13309   case AtomicOrdering::SequentiallyConsistent:
13310     if (!IsStore)
13311       return nullptr; // Nothing to do
13312     /*FALLTHROUGH*/
13313   case AtomicOrdering::Release:
13314   case AtomicOrdering::AcquireRelease:
13315     if (Subtarget->preferISHSTBarriers())
13316       return makeDMB(Builder, ARM_MB::ISHST);
13317     // FIXME: add a comment with a link to documentation justifying this.
13318     else
13319       return makeDMB(Builder, ARM_MB::ISH);
13320   }
13321   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13322 }
13323 
13324 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13325                                           AtomicOrdering Ord, bool IsStore,
13326                                           bool IsLoad) const {
13327   switch (Ord) {
13328   case AtomicOrdering::NotAtomic:
13329   case AtomicOrdering::Unordered:
13330     llvm_unreachable("Invalid fence: unordered/not-atomic");
13331   case AtomicOrdering::Monotonic:
13332   case AtomicOrdering::Release:
13333     return nullptr; // Nothing to do
13334   case AtomicOrdering::Acquire:
13335   case AtomicOrdering::AcquireRelease:
13336   case AtomicOrdering::SequentiallyConsistent:
13337     return makeDMB(Builder, ARM_MB::ISH);
13338   }
13339   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13340 }
13341 
13342 // Loads and stores less than 64-bits are already atomic; ones above that
13343 // are doomed anyway, so defer to the default libcall and blame the OS when
13344 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13345 // anything for those.
13346 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13347   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13348   return (Size == 64) && !Subtarget->isMClass();
13349 }
13350 
13351 // Loads and stores less than 64-bits are already atomic; ones above that
13352 // are doomed anyway, so defer to the default libcall and blame the OS when
13353 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13354 // anything for those.
13355 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13356 // guarantee, see DDI0406C ARM architecture reference manual,
13357 // sections A8.8.72-74 LDRD)
13358 TargetLowering::AtomicExpansionKind
13359 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13360   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13361   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13362                                                   : AtomicExpansionKind::None;
13363 }
13364 
13365 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13366 // and up to 64 bits on the non-M profiles
13367 TargetLowering::AtomicExpansionKind
13368 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13369   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13370   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13371   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13372              ? AtomicExpansionKind::LLSC
13373              : AtomicExpansionKind::None;
13374 }
13375 
13376 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13377     AtomicCmpXchgInst *AI) const {
13378   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13379   // implement cmpxchg without spilling. If the address being exchanged is also
13380   // on the stack and close enough to the spill slot, this can lead to a
13381   // situation where the monitor always gets cleared and the atomic operation
13382   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13383   bool hasAtomicCmpXchg =
13384       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13385   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13386 }
13387 
13388 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13389     const Instruction *I) const {
13390   return InsertFencesForAtomic;
13391 }
13392 
13393 // This has so far only been implemented for MachO.
13394 bool ARMTargetLowering::useLoadStackGuardNode() const {
13395   return Subtarget->isTargetMachO();
13396 }
13397 
13398 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13399                                                   unsigned &Cost) const {
13400   // If we do not have NEON, vector types are not natively supported.
13401   if (!Subtarget->hasNEON())
13402     return false;
13403 
13404   // Floating point values and vector values map to the same register file.
13405   // Therefore, although we could do a store extract of a vector type, this is
13406   // better to leave at float as we have more freedom in the addressing mode for
13407   // those.
13408   if (VectorTy->isFPOrFPVectorTy())
13409     return false;
13410 
13411   // If the index is unknown at compile time, this is very expensive to lower
13412   // and it is not possible to combine the store with the extract.
13413   if (!isa<ConstantInt>(Idx))
13414     return false;
13415 
13416   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13417   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13418   // We can do a store + vector extract on any vector that fits perfectly in a D
13419   // or Q register.
13420   if (BitWidth == 64 || BitWidth == 128) {
13421     Cost = 0;
13422     return true;
13423   }
13424   return false;
13425 }
13426 
13427 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13428   return Subtarget->hasV6T2Ops();
13429 }
13430 
13431 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13432   return Subtarget->hasV6T2Ops();
13433 }
13434 
13435 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13436                                          AtomicOrdering Ord) const {
13437   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13438   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13439   bool IsAcquire = isAcquireOrStronger(Ord);
13440 
13441   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13442   // intrinsic must return {i32, i32} and we have to recombine them into a
13443   // single i64 here.
13444   if (ValTy->getPrimitiveSizeInBits() == 64) {
13445     Intrinsic::ID Int =
13446         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13447     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13448 
13449     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13450     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13451 
13452     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13453     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13454     if (!Subtarget->isLittle())
13455       std::swap (Lo, Hi);
13456     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13457     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13458     return Builder.CreateOr(
13459         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13460   }
13461 
13462   Type *Tys[] = { Addr->getType() };
13463   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13464   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13465 
13466   return Builder.CreateTruncOrBitCast(
13467       Builder.CreateCall(Ldrex, Addr),
13468       cast<PointerType>(Addr->getType())->getElementType());
13469 }
13470 
13471 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13472     IRBuilder<> &Builder) const {
13473   if (!Subtarget->hasV7Ops())
13474     return;
13475   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13476   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13477 }
13478 
13479 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13480                                                Value *Addr,
13481                                                AtomicOrdering Ord) const {
13482   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13483   bool IsRelease = isReleaseOrStronger(Ord);
13484 
13485   // Since the intrinsics must have legal type, the i64 intrinsics take two
13486   // parameters: "i32, i32". We must marshal Val into the appropriate form
13487   // before the call.
13488   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13489     Intrinsic::ID Int =
13490         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13491     Function *Strex = Intrinsic::getDeclaration(M, Int);
13492     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13493 
13494     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13495     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13496     if (!Subtarget->isLittle())
13497       std::swap (Lo, Hi);
13498     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13499     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13500   }
13501 
13502   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13503   Type *Tys[] = { Addr->getType() };
13504   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13505 
13506   return Builder.CreateCall(
13507       Strex, {Builder.CreateZExtOrBitCast(
13508                   Val, Strex->getFunctionType()->getParamType(0)),
13509               Addr});
13510 }
13511 
13512 /// A helper function for determining the number of interleaved accesses we
13513 /// will generate when lowering accesses of the given type.
13514 static unsigned getNumInterleavedAccesses(VectorType *VecTy,
13515                                           const DataLayout &DL) {
13516   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13517 }
13518 
13519 /// \brief Lower an interleaved load into a vldN intrinsic.
13520 ///
13521 /// E.g. Lower an interleaved load (Factor = 2):
13522 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13523 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13524 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13525 ///
13526 ///      Into:
13527 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13528 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13529 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13530 bool ARMTargetLowering::lowerInterleavedLoad(
13531     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13532     ArrayRef<unsigned> Indices, unsigned Factor) const {
13533   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13534          "Invalid interleave factor");
13535   assert(!Shuffles.empty() && "Empty shufflevector input");
13536   assert(Shuffles.size() == Indices.size() &&
13537          "Unmatched number of shufflevectors and indices");
13538 
13539   VectorType *VecTy = Shuffles[0]->getType();
13540   Type *EltTy = VecTy->getVectorElementType();
13541 
13542   const DataLayout &DL = LI->getModule()->getDataLayout();
13543   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13544   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13545 
13546   // Skip if we do not have NEON and skip illegal vector types and vector types
13547   // with i64/f64 elements (vldN doesn't support i64/f64 elements). We can
13548   // "legalize" wide vector types into multiple interleaved accesses as long as
13549   // the vector types are divisible by 128.
13550   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize % 128 != 0) ||
13551       EltIs64Bits)
13552     return false;
13553 
13554   // Skip if the vector has f16 elements: even though we could do an i16 vldN,
13555   // we can't hold the f16 vectors and will end up converting via f32.
13556   if (EltTy->isHalfTy())
13557     return false;
13558 
13559   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13560 
13561   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13562   // load integer vectors first and then convert to pointer vectors.
13563   if (EltTy->isPointerTy())
13564     VecTy =
13565         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13566 
13567   IRBuilder<> Builder(LI);
13568 
13569   // The base address of the load.
13570   Value *BaseAddr = LI->getPointerOperand();
13571 
13572   if (NumLoads > 1) {
13573     // If we're going to generate more than one load, reset the sub-vector type
13574     // to something legal.
13575     VecTy = VectorType::get(VecTy->getVectorElementType(),
13576                             VecTy->getVectorNumElements() / NumLoads);
13577 
13578     // We will compute the pointer operand of each load from the original base
13579     // address using GEPs. Cast the base address to a pointer to the scalar
13580     // element type.
13581     BaseAddr = Builder.CreateBitCast(
13582         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13583                       LI->getPointerAddressSpace()));
13584   }
13585 
13586   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13587 
13588   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13589   Type *Tys[] = {VecTy, Int8Ptr};
13590   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13591                                             Intrinsic::arm_neon_vld3,
13592                                             Intrinsic::arm_neon_vld4};
13593   Function *VldnFunc =
13594       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13595 
13596   // Holds sub-vectors extracted from the load intrinsic return values. The
13597   // sub-vectors are associated with the shufflevector instructions they will
13598   // replace.
13599   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13600 
13601   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13602 
13603     // If we're generating more than one load, compute the base address of
13604     // subsequent loads as an offset from the previous.
13605     if (LoadCount > 0)
13606       BaseAddr = Builder.CreateConstGEP1_32(
13607           BaseAddr, VecTy->getVectorNumElements() * Factor);
13608 
13609     SmallVector<Value *, 2> Ops;
13610     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13611     Ops.push_back(Builder.getInt32(LI->getAlignment()));
13612 
13613     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13614 
13615     // Replace uses of each shufflevector with the corresponding vector loaded
13616     // by ldN.
13617     for (unsigned i = 0; i < Shuffles.size(); i++) {
13618       ShuffleVectorInst *SV = Shuffles[i];
13619       unsigned Index = Indices[i];
13620 
13621       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13622 
13623       // Convert the integer vector to pointer vector if the element is pointer.
13624       if (EltTy->isPointerTy())
13625         SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
13626 
13627       SubVecs[SV].push_back(SubVec);
13628     }
13629   }
13630 
13631   // Replace uses of the shufflevector instructions with the sub-vectors
13632   // returned by the load intrinsic. If a shufflevector instruction is
13633   // associated with more than one sub-vector, those sub-vectors will be
13634   // concatenated into a single wide vector.
13635   for (ShuffleVectorInst *SVI : Shuffles) {
13636     auto &SubVec = SubVecs[SVI];
13637     auto *WideVec =
13638         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13639     SVI->replaceAllUsesWith(WideVec);
13640   }
13641 
13642   return true;
13643 }
13644 
13645 /// \brief Lower an interleaved store into a vstN intrinsic.
13646 ///
13647 /// E.g. Lower an interleaved store (Factor = 3):
13648 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13649 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13650 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13651 ///
13652 ///      Into:
13653 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13654 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13655 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13656 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13657 ///
13658 /// Note that the new shufflevectors will be removed and we'll only generate one
13659 /// vst3 instruction in CodeGen.
13660 ///
13661 /// Example for a more general valid mask (Factor 3). Lower:
13662 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
13663 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
13664 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
13665 ///
13666 ///      Into:
13667 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
13668 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
13669 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
13670 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13671 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13672                                               ShuffleVectorInst *SVI,
13673                                               unsigned Factor) const {
13674   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13675          "Invalid interleave factor");
13676 
13677   VectorType *VecTy = SVI->getType();
13678   assert(VecTy->getVectorNumElements() % Factor == 0 &&
13679          "Invalid interleaved store");
13680 
13681   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
13682   Type *EltTy = VecTy->getVectorElementType();
13683   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
13684 
13685   const DataLayout &DL = SI->getModule()->getDataLayout();
13686   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
13687   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13688 
13689   // Skip if we do not have NEON and skip illegal vector types and vector types
13690   // with i64/f64 elements (vldN doesn't support i64/f64 elements). We can
13691   // "legalize" wide vector types into multiple interleaved accesses as long as
13692   // the vector types are divisible by 128.
13693   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize % 128 != 0) ||
13694       EltIs64Bits)
13695     return false;
13696 
13697   // Skip if the vector has f16 elements: even though we could do an i16 vldN,
13698   // we can't hold the f16 vectors and will end up converting via f32.
13699   if (EltTy->isHalfTy())
13700     return false;
13701 
13702   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
13703 
13704   Value *Op0 = SVI->getOperand(0);
13705   Value *Op1 = SVI->getOperand(1);
13706   IRBuilder<> Builder(SI);
13707 
13708   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13709   // vectors to integer vectors.
13710   if (EltTy->isPointerTy()) {
13711     Type *IntTy = DL.getIntPtrType(EltTy);
13712 
13713     // Convert to the corresponding integer vector.
13714     Type *IntVecTy =
13715         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13716     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13717     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13718 
13719     SubVecTy = VectorType::get(IntTy, LaneLen);
13720   }
13721 
13722   // The base address of the store.
13723   Value *BaseAddr = SI->getPointerOperand();
13724 
13725   if (NumStores > 1) {
13726     // If we're going to generate more than one store, reset the lane length
13727     // and sub-vector type to something legal.
13728     LaneLen /= NumStores;
13729     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
13730 
13731     // We will compute the pointer operand of each store from the original base
13732     // address using GEPs. Cast the base address to a pointer to the scalar
13733     // element type.
13734     BaseAddr = Builder.CreateBitCast(
13735         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
13736                       SI->getPointerAddressSpace()));
13737   }
13738 
13739   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
13740 
13741   auto Mask = SVI->getShuffleMask();
13742 
13743   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13744   Type *Tys[] = {Int8Ptr, SubVecTy};
13745   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13746                                              Intrinsic::arm_neon_vst3,
13747                                              Intrinsic::arm_neon_vst4};
13748 
13749   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
13750 
13751     // If we generating more than one store, we compute the base address of
13752     // subsequent stores as an offset from the previous.
13753     if (StoreCount > 0)
13754       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
13755 
13756     SmallVector<Value *, 6> Ops;
13757     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13758 
13759     Function *VstNFunc =
13760         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
13761 
13762     // Split the shufflevector operands into sub vectors for the new vstN call.
13763     for (unsigned i = 0; i < Factor; i++) {
13764       unsigned IdxI = StoreCount * LaneLen * Factor + i;
13765       if (Mask[IdxI] >= 0) {
13766         Ops.push_back(Builder.CreateShuffleVector(
13767             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
13768       } else {
13769         unsigned StartMask = 0;
13770         for (unsigned j = 1; j < LaneLen; j++) {
13771           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
13772           if (Mask[IdxJ * Factor + IdxI] >= 0) {
13773             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
13774             break;
13775           }
13776         }
13777         // Note: If all elements in a chunk are undefs, StartMask=0!
13778         // Note: Filling undef gaps with random elements is ok, since
13779         // those elements were being written anyway (with undefs).
13780         // In the case of all undefs we're defaulting to using elems from 0
13781         // Note: StartMask cannot be negative, it's checked in
13782         // isReInterleaveMask
13783         Ops.push_back(Builder.CreateShuffleVector(
13784             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
13785       }
13786     }
13787 
13788     Ops.push_back(Builder.getInt32(SI->getAlignment()));
13789     Builder.CreateCall(VstNFunc, Ops);
13790   }
13791   return true;
13792 }
13793 
13794 enum HABaseType {
13795   HA_UNKNOWN = 0,
13796   HA_FLOAT,
13797   HA_DOUBLE,
13798   HA_VECT64,
13799   HA_VECT128
13800 };
13801 
13802 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13803                                    uint64_t &Members) {
13804   if (auto *ST = dyn_cast<StructType>(Ty)) {
13805     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13806       uint64_t SubMembers = 0;
13807       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13808         return false;
13809       Members += SubMembers;
13810     }
13811   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13812     uint64_t SubMembers = 0;
13813     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13814       return false;
13815     Members += SubMembers * AT->getNumElements();
13816   } else if (Ty->isFloatTy()) {
13817     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13818       return false;
13819     Members = 1;
13820     Base = HA_FLOAT;
13821   } else if (Ty->isDoubleTy()) {
13822     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13823       return false;
13824     Members = 1;
13825     Base = HA_DOUBLE;
13826   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13827     Members = 1;
13828     switch (Base) {
13829     case HA_FLOAT:
13830     case HA_DOUBLE:
13831       return false;
13832     case HA_VECT64:
13833       return VT->getBitWidth() == 64;
13834     case HA_VECT128:
13835       return VT->getBitWidth() == 128;
13836     case HA_UNKNOWN:
13837       switch (VT->getBitWidth()) {
13838       case 64:
13839         Base = HA_VECT64;
13840         return true;
13841       case 128:
13842         Base = HA_VECT128;
13843         return true;
13844       default:
13845         return false;
13846       }
13847     }
13848   }
13849 
13850   return (Members > 0 && Members <= 4);
13851 }
13852 
13853 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
13854 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
13855 /// passing according to AAPCS rules.
13856 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
13857     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13858   if (getEffectiveCallingConv(CallConv, isVarArg) !=
13859       CallingConv::ARM_AAPCS_VFP)
13860     return false;
13861 
13862   HABaseType Base = HA_UNKNOWN;
13863   uint64_t Members = 0;
13864   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
13865   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
13866 
13867   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
13868   return IsHA || IsIntArray;
13869 }
13870 
13871 unsigned ARMTargetLowering::getExceptionPointerRegister(
13872     const Constant *PersonalityFn) const {
13873   // Platforms which do not use SjLj EH may return values in these registers
13874   // via the personality function.
13875   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
13876 }
13877 
13878 unsigned ARMTargetLowering::getExceptionSelectorRegister(
13879     const Constant *PersonalityFn) const {
13880   // Platforms which do not use SjLj EH may return values in these registers
13881   // via the personality function.
13882   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
13883 }
13884 
13885 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13886   // Update IsSplitCSR in ARMFunctionInfo.
13887   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
13888   AFI->setIsSplitCSR(true);
13889 }
13890 
13891 void ARMTargetLowering::insertCopiesSplitCSR(
13892     MachineBasicBlock *Entry,
13893     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13894   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
13895   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13896   if (!IStart)
13897     return;
13898 
13899   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13900   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13901   MachineBasicBlock::iterator MBBI = Entry->begin();
13902   for (const MCPhysReg *I = IStart; *I; ++I) {
13903     const TargetRegisterClass *RC = nullptr;
13904     if (ARM::GPRRegClass.contains(*I))
13905       RC = &ARM::GPRRegClass;
13906     else if (ARM::DPRRegClass.contains(*I))
13907       RC = &ARM::DPRRegClass;
13908     else
13909       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13910 
13911     unsigned NewVR = MRI->createVirtualRegister(RC);
13912     // Create copy from CSR to a virtual register.
13913     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13914     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13915     // nounwind. If we want to generalize this later, we may need to emit
13916     // CFI pseudo-instructions.
13917     assert(Entry->getParent()->getFunction()->hasFnAttribute(
13918                Attribute::NoUnwind) &&
13919            "Function should be nounwind in insertCopiesSplitCSR!");
13920     Entry->addLiveIn(*I);
13921     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13922         .addReg(*I);
13923 
13924     // Insert the copy-back instructions right before the terminator.
13925     for (auto *Exit : Exits)
13926       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13927               TII->get(TargetOpcode::COPY), *I)
13928           .addReg(NewVR);
13929   }
13930 }
13931